

# Real-time item recommendations in Amazon Personalize
Real-time item recommendations

 If your use case or recipe generates item recommendations, after you [create a recommender](creating-recommenders.md) or [create a campaign](campaigns.md), you can get real-time personalized or related item recommendations for your users. 

 If your domain use case or recipe provides [real-time personalization](use-case-recipe-features.md#about-real-time-personalization), such as the *Top picks for you* use case or the *User-Personalization-v2* recipe, Amazon Personalize updates recommendations based on your user's most recent activity as you record their interactions with your catalog. For more information on recording real-time events and personalization, see [Recording real-time events to influence recommendations](recording-events.md). 

 When you get real-time item recommendations, you can do the following: 
+  If you configured your campaign to return metadata for recommended items, you can specify the columns to include in your [GetRecommendations](API_RS_GetRecommendations.md) API operation. Or you can specify the columns when you test the campaign with the Amazon Personalize console. For code samples, see [Getting item metadata with real-time recommendations](getting-recommendations-with-metadata.md). For information about enabling metadata for a campaign, see [Item metadata in recommendations](campaigns.md#create-campaign-return-metadata). For information about enabling metadata for a recommender, see [Enabling metadata in recommendations for a domain recommender in Amazon Personalize](create-recommender-return-metadata.md). 
+  For some use cases and recipes, you can specify a promotion in your recommendation request. A *promotion* defines additional business rules that apply to a configurable subset of recommended items. For more information, see [Promoting items in real-time recommendations](promoting-items.md). 
+  You can filter results based on custom criteria. For example, you might not want to recommend products that a user has already purchased or recommend only items for a particular age group. For more information, see [Filtering recommendations and user segments](filter.md). 

**Note**  
 If you used a PERSONALIZED\$1RANKING custom recipe, see [Getting a personalized ranking (custom resources)](rankings.md). 

**Topics**
+ [

## How recommendation scoring works (custom resources)
](#how-recommendation-scoring-works)
+ [

## Recommendation reasons with User-Personalization-v2
](#recommendation-reasons)
+ [

# Getting real-time item recommendations
](getting-real-time-item-recommendations.md)
+ [

# Getting item metadata with real-time recommendations
](getting-recommendations-with-metadata.md)
+ [

# Promoting items in real-time recommendations
](promoting-items.md)

## How recommendation scoring works (custom resources)


With the User-Personalization-v2 and User-Personalization recipes, Amazon Personalize generates scores for items based on on a user's interaction data and metadata. These scores represent the relative certainty that Amazon Personalize has in whether the user will interact with the item next. Higher scores represent greater certainty.

**Note**  
Amazon Personalize doesn't show scores for domain recommenders or the Similar-Items, SIMS or Popularity-Count recipes. For information on scores for Personalized-Ranking recommendations, see [How personalized ranking scoring works](rankings.md#how-ranking-scoring-works).

Amazon Personalize generates scores for items relative to each other on a scale from 0 to 1 (both inclusive). With User-Personalization-v2, Amazon Personalize generates scores for a subset of your items. With User-Personalization, Amazon Personalize scores all of the items in your catalog.

 If you use User-Personalization-v2 and apply a filter to recommendations, depending on how many recommendations the filter removes, Amazon Personalize might add placeholder items. It does this to meet the `numResults` for your recommendation request. These items are popular items, based on amount of interactions data, that satisfy your filter criteria. They don't have a relevance score for the user. 

For both User-Personalization-v2 and User-Personalization, the total of all scores equals 1. For example, if you're getting movie recommendations for a user and there are three movies appearing the Items dataset and Interactions dataset, their scores might be `0.6`, `0.3`, and `0.1`. Similarly, if you have 10,000 movies in your inventory, the highest-scoring movies might have very small scores (the average score would be`.001`), but, because scoring is relative, the recommendations are still valid.

In mathematical terms, scores for each user-item pair (u,i) are computed according to the following formula, where `exp` is the exponential function, w̅u and wi/j are user and item embeddings respectively, and the Greek letter sigma (Σ) represents summation over all items with scores:

![\[Depicts the formula used to calculate scores for each item in recommendations.\]](http://docs.aws.amazon.com/personalize/latest/dg/images/get_recommendations_score.png)


## Recommendation reasons with User-Personalization-v2


If you use User-Personalization-v2, items the model wouldn't normally recommend include a `reason` list. These reasons explain why the item was included in recommendations. Possible reasons include the following:
+ Promoted item – Indicates the item was included as part of a promotion that you applied in your recommendation request.
+ Exploration – Indicates the item was included with exploration. With exploration, recommendations include items with less interactions data or relevance for the user. For more information about exploration, see [Exploration](https://docs.aws.amazon.com/personalize/latest/dg/use-case-recipe-features.html#about-exploration).
+  Popular item – Indicates the item was included as a placeholder popular item. If you use a filter, depending on how many recommendations the filter removes, Amazon Personalize might add placeholder items to meet the `numResults` for your recommendation request. These items are popular items, based on interactions data, that satisfy your filter criteria. They don't have a relevance score for the user. 

# Getting real-time item recommendations


 You can get real-time item recommendations from an Amazon Personalize recommender or custom campaign with the Amazon Personalize console, AWS Command Line Interface (AWS CLI), or AWS SDKs. 

**Topics**
+ [

## Getting item recommendations (console)
](#get-real-time-recommendations-console)
+ [

## Getting item recommendations (AWS CLI)
](#get-item-rec-cli)
+ [

## Getting item recommendations (AWS SDKs)
](#get-item-rec-sdk)

## Getting item recommendations (console)


 To get recommendations with the Amazon Personalize console, you provide the request information on the details page of either a recommender (Domain dataset group) or a custom campaign.

**To get recommendations**

1. Open the Amazon Personalize console at [https://console.aws.amazon.com/personalize/home](https://console.aws.amazon.com/personalize/home) and sign into your account. 

1. Choose the dataset group that contains the campaign or recommender you are using.

1. In the navigation pane, choose **Campaigns** or **Recommenders**.

1. Choose the target campaign or recommender.

1.  For a campaigns, under **Test campaign results**, enter your recommendation request details based on the recipe you used. For a recommenders choose **Test recommender** and enter your recommendation request details based on your use case. 

    If you recorded events for a user before they logged in (an anonymous user), you can get recommendations for this user by providing the `sessionId` from those events as if it is their `userId`. For more information about recording events for anonymous users, see [Recording events for anonymous users](recording-events.md#recording-anonymous-user-events). 

1. Optionally choose a filter. For more information, see [Filtering recommendations and user segments](filter.md). 

1. If you use contextual metadata, provide data for each context. For each context, for the **Key** enter the metadata field. For the **Value** enter the context data. For more information, see [Increasing recommendation relevance with contextual metadata](contextual-metadata.md). 

1. If you enabled metadata in recommendations for your campaign or recommender, for **Items dataset columns**, choose the metadata columns that you want to include in recommendation results. For information about enabling metadata for a campaign, see [Item metadata in recommendations](campaigns.md#create-campaign-return-metadata). For information about enabling metadata for a recommender, see [Enabling metadata in recommendations for a domain recommender in Amazon Personalize](create-recommender-return-metadata.md).

1.  If you want to promote a subset of items, optionally complete the **Promotion** fields. For more information see [Promoting items in real-time recommendations](promoting-items.md). 

1. Choose **Get recommendations**. A table containing the user’s top 25 recommended items displays. If you use User-Personalization-v2, each recommended item includes a list of reasons for why the item was included in recommendations. For more information, see [Recommendation reasons with User-Personalization-v2](recommendations.md#recommendation-reasons). 

## Getting item recommendations (AWS CLI)


Use the following code to get recommendations from a campaign. To get recommendations from a recommender, replace the `campaign-arn` parameter with the `recommender-arn`.

 Specify the ID of the user you want to get recommendations for, and the Amazon Resource Name (ARN) of your campaign or recommender. A list of the top 10 recommended items for the user displays. If you use User-Personalization-v2, each recommended item includes a list of reasons for why the item was included in recommendations. For more information, see [Recommendation reasons with User-Personalization-v2](recommendations.md#recommendation-reasons). 

To change the number of recommended items, change the value for `numResults`. The default is 25 items. The maximum is 500 items. If you used a RELATED\$1ITEMS recipe to train the solution version backing the campaign, replace the `user-id` parameter with `item-id` and specify the item ID. 

 If you recorded events for a user before they logged in (an anonymous user), you can get recommendations for this user by providing the `sessionId` from those events as if it is their `userId`. For more information about recording events for anonymous users, see [Recording events for anonymous users](recording-events.md#recording-anonymous-user-events). 

```
aws personalize-runtime get-recommendations \
--campaign-arn campaign arn \
--user-id User ID \
--num-results 10
```

## Getting item recommendations (AWS SDKs)


The following code shows how to get Amazon Personalize recommendations for a user from a campaign with the AWS SDKs. To get recommendations from a recommender, replace the `campaignArn` parameter with the `recommenderArn`. 

Specify the ID of the user you want to get recommendations for, and the Amazon Resource Name (ARN) of your campaign or recommender. A list of the top 10 recommended items for the user displays. If you use User-Personalization-v2, each recommended item includes a list of reasons for why the item was included in recommendations. For more information, see [Recommendation reasons with User-Personalization-v2](recommendations.md#recommendation-reasons).

To change the number of recommended items, change the value for `numResults`. The default is 25 items. The maximum is 500 items. If you used a RELATED\$1ITEMS recipe to train the solution version backing the campaign, replace the `userId` parameter with `itemId` and specify the item ID. 

If you enabled metadata in recommendations for your campaign or recommender, you can specify the Items dataset metadata columns to include in the response. For a code sample, see [Including item metadata with recommendations (AWS SDKs)](getting-recommendations-with-metadata.md#getting-recommendations-with-metadata-sdk). For information about enabling metadata, see [Item metadata in recommendations](campaigns.md#create-campaign-return-metadata).

 If you recorded events for a user before they logged in (an anonymous user), you can get recommendations for this user by providing the `sessionId` from those events as if it is their `userId`. For more information about recording events for anonymous users, see [Recording events for anonymous users](recording-events.md#recording-anonymous-user-events). 

------
#### [ SDK for Python (Boto3) ]

```
import boto3

personalizeRt = boto3.client('personalize-runtime')

response = personalizeRt.get_recommendations(
    campaignArn = 'Campaign ARN',
    userId = 'User ID',
    numResults = 10
)

print("Recommended items")
for item in response['itemList']:
    print (item['itemId'])
```

------
#### [ SDK for Java 2.x ]

```
    public static void getRecs(PersonalizeRuntimeClient personalizeRuntimeClient, String campaignArn, String userId) {

        try {
            GetRecommendationsRequest recommendationsRequest = GetRecommendationsRequest.builder()
                    .campaignArn(campaignArn)
                    .numResults(20)
                    .userId(userId)
                    .build();

            GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient
                    .getRecommendations(recommendationsRequest);
            List<PredictedItem> items = recommendationsResponse.itemList();
            for (PredictedItem item : items) {
                System.out.println("Item Id is : " + item.itemId());
                System.out.println("Item score is : " + item.score());
            }

        } catch (AwsServiceException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```

------
#### [ SDK for JavaScript v3 ]

```
// Get service clients module and commands using ES6 syntax.
import { GetRecommendationsCommand } from "@aws-sdk/client-personalize-runtime";

import { personalizeRuntimeClient } from "./libs/personalizeClients.js";
// Or, create the client here.
// const personalizeRuntimeClient = new PersonalizeRuntimeClient({ region: "REGION"});

// Set the recommendation request parameters.
export const getRecommendationsParam = {
  campaignArn: "CAMPAIGN_ARN" /* required */,
  userId: "USER_ID" /* required */,
  numResults: 15 /* optional */,
};

export const run = async () => {
  try {
    const response = await personalizeRuntimeClient.send(
      new GetRecommendationsCommand(getRecommendationsParam),
    );
    console.log("Success!", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

------

# Getting item metadata with real-time recommendations
Getting item metadata with recommendations

 If you configured your campaign or recommender to return metadata for recommended items, you can specify the columns to include in your [GetRecommendations](API_RS_GetRecommendations.md) API operation. Or you can specify the columns when you test the campaign with the Amazon Personalize console. 

 For information about enabling metadata for a campaign, see [Item metadata in recommendations](campaigns.md#create-campaign-return-metadata). For information about enabling metadata for a recommender, see [Enabling metadata in recommendations for a domain recommender in Amazon Personalize](create-recommender-return-metadata.md). 

The following code samples show how to specify the metadata columns to include with the AWS CLI or the AWS SDKs. To do this with the Amazon Personalize console, you specify the columns when you test your campaign. For more information, see [Getting item recommendations (console)](getting-real-time-item-recommendations.md#get-real-time-recommendations-console). 

**Topics**
+ [

## Including item metadata with recommendations (AWS CLI)
](#getting-recommendations-with-metadata-cli)
+ [

## Including item metadata with recommendations (AWS SDKs)
](#getting-recommendations-with-metadata-sdk)

## Including item metadata with recommendations (AWS CLI)


If you enabled metadata in recommendations for your campaign or recommender, you can specify the Items dataset metadata columns to include in the response. The following code sample shows how to specify the metadata columns as part of your request for recommendations.

```
aws personalize-runtime get-recommendations \
--campaign-arn campaign arn \
--user-id User ID \
--num-results 10 \
--metadata-columns "{\"ITEMS\": ["\"columnNameA"\","\"columnNameB"\"]}"
```

## Including item metadata with recommendations (AWS SDKs)


If you enabled metadata in recommendations for your campaign or recommender, you can specify the Items dataset metadata columns to include in the response. The following code sample shows how to specify the metadata columns as part of your request for recommendations.

```
import boto3

personalizeRt = boto3.client('personalize-runtime')

response = personalizeRt.get_recommendations(
  campaignArn = 'Campaign ARN',
  userId = 'User ID',
  numResults = 10
  metadataColumns = {
    "ITEMS": ['columnNameA','columnNameB']
  }
)

print("Recommended items")
for item in response['itemList']:
  print(item['itemId'])
  print(item['metadata'])
```

# Promoting items in real-time recommendations
Promoting items

 With all domain use cases and some custom recipes, you can specify a promotion when you get real-time recommendations. 

 A *promotion* defines additional business rules that apply to a configurable subset of recommended items. For example, you might have a streaming app and want to promote your own shows and movies but also recommend relevant titles. You could use a promotion to specify that a certain percentage of recommended items must come from the category *in-house*. The remaining recommended items would continue to be relevant recommendations based on your recipe and any request filters. 

 To apply a promotion, you specify the following in your recommendation request: 
+ The percentage of recommended items to apply the promotion filter to.
+ A filter that specifies the promotion criteria. For more information, see [Promotion filters](#promotion-filters). 

In the recommendation response, promoted items are positioned randomly relative to other recommended items, but in sorted order relative to other promoted items. Depending on your recipe, recommended items that aren't part of a promotion are sorted by relevance to the user, popularity, or similarity. If there aren't enough items that meet the promotion criteria, the result will contain as many promoted items as possible. 

You can apply a promotion to recommendations with the Amazon Personalize console, AWS Command Line Interface (AWS CLI), or AWS SDKs.

**Topics**
+ [

## Use cases and recipes that support promotions
](#promotion-use-case-recipes)
+ [

## Promotion filters
](#promotion-filters)
+ [

## Promoting new items
](#promoting-new-items)
+ [

## Promoting items (console)
](#promoting-items-console)
+ [

## Promoting items (AWS CLI)
](#promoting-items-cli)
+ [

## Promoting items (AWS SDKs)
](#promoting-items-sdk)

## Use cases and recipes that support promotions


All use cases support promotions. The following custom recipes support promotions:
+ [User-Personalization-v2](native-recipe-user-personalization-v2.md) and [User-Personalization](native-recipe-new-item-USER_PERSONALIZATION.md) recipes
+ [Similar-Items](native-recipe-similar-items.md) and [SIMS](native-recipe-sims.md)recipes
+ [Trending-Now](native-recipe-trending-now.md) and [Popularity-Count](native-recipe-popularity.md) recipes

## Promotion filters


 When you apply a promotion to a recommendation request, you choose a filter that specifies the promotion criteria. You can use an existing filter or create a new one. You create and manage filters for promotions as you would other filters in Amazon Personalize. For information about creating and managing filters, see [Filtering results](filter.md). 

 The only difference between a promotion filter and a filter that you choose outside the promotion (the *request filter*) is how Amazon Personalize applies them. A promotion filter applies to only promoted items, while a request filter applies to only the remaining recommended items. If you specify a request filter and promotion filter, and want to apply both filters to promoted items, your promotion filter's expression must include both expressions. The way you combine two expressions depends on the datasets you use. For more information on filter expressions, their rules, and how to create them, see [Filter expressions](filter-expressions.md). 

 **Filter expression examples** 

The following expression includes only items from the category "in-house". You might use this expression if you want to promote your own content in your recommendations. 

```
INCLUDE ItemID WHERE Items.OWNER IN ("in-house")
```

The following expression includes only items created more recently than a timestamp you specify. You might use this expression to promote new items in recommendations.

```
INCLUDE ItemID WHERE Items.CREATION_TIMESTAMP > $DATE
```

The following expression shows how you might apply a request filter to promoted items. It includes only available clothing items as promoted items. In this scenario, the `Items.AVAILABLE IN ("True")` would also be used in the request filter expression, so that all recommendations are for items that are available. 

```
INCLUDE ItemID WHERE Items.CATEGORY IN ("clothing") AND Items.AVAILABLE IN ("True")
```

For a more complete list of filter examples, see [Filter expression examples](filter-expression-examples.md).

## Promoting new items


 If you use the [User-Personalization-v2 recipe](native-recipe-user-personalization-v2.md), Amazon Personalize recommends the most relevant items to users and more frequently recommends existing items with interactions data. To make sure recommendations include some new items, you can apply a promotion to recommendation requests that includes items based on creation timestamp. 

If you don't already use a promotion, your filter expression can promote items created after a certain date:

```
INCLUDE ItemID WHERE Items.CREATION_TIMESTAMP > $DATE
```

If you already use a promotion, you create an expression that chains both the promotion and the new item condition statements:

```
INCLUDE ItemID WHERE Items.CATEGORY IN ("clothing") OR Items.CREATION_TIMESTAMP > $DATE
```

## Promoting items (console)


 To promote certain items in recommendations with the Amazon Personalize console, create a filter, and then provide the promotion details in the recommendation request. For information on other fields, see [Getting item recommendations (console)](getting-real-time-item-recommendations.md#get-real-time-recommendations-console). 

**To promote items in recommendations**

1. Open the Amazon Personalize console at [https://console.aws.amazon.com/personalize/home](https://console.aws.amazon.com/personalize/home) and sign into your account. 

1. Choose the dataset group that contains the campaign or recommender you are using.

1. If you haven't already, create a filter that specifies the promotion criteria. You create filters for promotions the same way that you create request filters. For information on creating and managing filters, see [Filtering results](filter.md).

1. In the navigation pane, choose **Recommenders** or **Campaigns**.

1. Choose the target campaign or recommender.

1.  For campaigns, under **Test campaign results**, enter your recommendation request details based on the recipe you used. For recommenders, choose **Test recommender** and enter your recommendation request details. 

1. Optionally choose a filter for the request. This filter applies to only non-promoted items. For information on creating and managing filters, see [Filtering results](filter.md). 

1. If you use contextual metadata, provide data for each context. For each context, for the **Key** enter the metadata field. For the **Value**, enter the context data. For more information, see [Increasing recommendation relevance with contextual metadata](contextual-metadata.md). 

1. For **Promotion** specify the following:
   + **Percent promoted items**: Enter the percentage of recommended items to apply the promotion to.
   + **Filter**: Choose a filter that specifies the promotion criteria. This filter applies to the promoted items instead of any request filter that you may have specified in step 7.
   + **Filter parameter**: If your promotion uses a filter with placeholder parameters, for each parameter, enter the value to set the filter criteria. To use multiple values for one parameter, separate each value with a comma.

1. Choose **Get recommendations**. A table containing the user’s top 25 recommended items displays. The **Promoted item** column indicates whether the item was included because of your promotion. Promoted items are positioned randomly relative to other recommended items, but in sorted order relative to other promoted items. Depending on your use case or recipe, recommended items that aren't part of a promotion are sorted by relevance to the user, popularity, or similarity. If there aren't enough items that meet the promotion criteria, the result will contain as many promoted items as possible. 

## Promoting items (AWS CLI)


The following code shows how to promote items in recommendations with the AWS CLI and a custom campaign. To promote items with a recommender, replace the `campaign-arn` parameter with a `recommender-arn` and specify the Amazon Resource Name (ARN) for the recommender. For the promotion fields, specify the following: 
+ name: Give the promotion a name. The recommendation response uses the name to identify promoted items.
+ percent-promoted-items: The percentage of recommended items to apply the promotion to. In this example, 50% of items will be promoted items.
+ filterArn: Specify the Amazon Resource Name (ARN) of the filter that defines the promotion criteria. For more information, see [Promotion filters](#promotion-filters).
+ parameter names and values: If your filter expression has any parameters, provide the parameter names (case sensitive) and the values. For example, if your filter expression has a `$GENRE` parameter, provide GENRE as the key, and a genre or genres, such as *Comedy*, as the value. Separate multiple values with a comma. When you use the AWS CLI, for each value you must use the `/` character to escape both quotes and the `/` character. The following code example shows how to format the values.

The code shows how to use both a request filter and a promotion filter. A promotion filter applies to only promoted items, while a request filter applies to only the remaining recommended items. For more information, see [Promotion filters](#promotion-filters). 

For information about additional fields, see [Getting item recommendations (AWS SDKs)](getting-real-time-item-recommendations.md#get-item-rec-sdk) and [Getting a personalized ranking using contextual metadata](get-personalized-rankings-sdk.md#personalized-ranking-contextual-metadata-example).

```
aws personalize-runtime get-recommendations \
--campaign-arn CampaignArn \
--user-id 1 \
--num-results 10  \
--filter-arn RequestFilterArn \
--filter-values '{
    "RequestFilterParameterName": "\"value\"",
    "RequestFilterParameterName": "\"value1\",\"value2\",\"value3\""
  }' \
--promotions "[{
  \"name\": \"promotionName\",
  \"percentPromotedItems\": 50,
  \"filterArn\": \"PromotionFilterARN\",
  \"filterValues\": {\"PromotionParameterName\":\"\\\"value1, value2\\\"\"}
}]"
```

 A list of recommended items displays. Promoted items are positioned randomly relative to other recommended items, but in sorted order relative to other promoted items. Depending on your recipe, recommended items that aren't part of a promotion are sorted by relevance to the user, popularity, or similarity. If there aren't enough items that meet the promotion criteria, the result will contain as many promoted items as possible. 

```
{
  "itemList": [
      { 
          "itemId1": "123",
          "score": .0117211,
          "promotionName": "promotionName"
      },
      { 
         "itemId2": "456",
         "score": .0077976
      },
      { 
         "itemId3": "789",
         "score": .0067171
      },
      .....
 ]
```

## Promoting items (AWS SDKs)


The following code shows how to promote items in recommendations with the SDK for Python (Boto3) and the SDK for Java 2.x and a custom campaign. To promote items with a recommender, replace the `campaignArn` parameter with `recommenderArn` and specify the Amazon Resource Name (ARN) for the recommender. For the promotion fields, specify the following: 
+ name: Specify the name of the promotion. The recommendation response includes the name to identify promoted items.
+ percentPromotedItems: The percentage of recommended items to apply the promotion to.
+ promotionFilterARN: The Amazon Resource Name (ARN) of the filter that defines the promotion criteria. For more information, see [Promotion filters](#promotion-filters).
+ Any parameter names and values: If your filter expression has any parameters, for each parameter in your filter expression, provide the parameter name (case sensitive) and the values. For example, if your filter expression has a `$GENRE` parameter, provide `"GENRE"` as the key, and a genre or genres, such as "\$1"Comedy"\$1", as the value. Separate multiple values with a comma. For example, `"\"comedy\",\"drama\",\"horror"\"`. 

The following code shows how to use both a request filter and a promotion filter. A promotion filter applies to only promoted items, while a request filter applies to only the remaining recommended items. For more information, see [Promotion filters](#promotion-filters). 

For information about additional fields, see [Getting item recommendations (AWS SDKs)](getting-real-time-item-recommendations.md#get-item-rec-sdk) and [Getting a personalized ranking using contextual metadata](get-personalized-rankings-sdk.md#personalized-ranking-contextual-metadata-example).

------
#### [ SDK for Python (Boto3) ]

```
import boto3

personalizeRt = boto3.client('personalize-runtime')

response = personalizeRt.get_recommendations(
  campaignArn = "CampaignARN",
  userId = '1',
  numResults = 10,
  filterArn = 'RequestFilterARN',
  filterValues = {
      "RequestFilterParameterName": "\"value1\"",
      "RequestFilterParameterName": "\"value1\",\"value2\",\"value3\""
      ....
  },
  promotions = [{
    "name" : "promotionName",
    "percentPromotedItems" : 50,
    "filterArn": "promotionFilterARN",
    "filterValues": {
      "PromotionParameterName": "\"Value1\",\"Value2\""
      ...
    } 
  }]
)

print("Recommended items")
for item in response['itemList']:
    print (item['itemId'])
    if ("promotionName" in item):
        print(item['promotionName'])
```

------
#### [ SDK for Java 2.x ]

```
public static void getRecommendationsWithPromotedItems(PersonalizeRuntimeClient personalizeRuntimeClient,
                                       String campaignArn,
                                       String userId,
                                       String requestFilterArn,
                                       String requestParameterName,
                                       String requestParameterValue1,
                                       String requestParameterValue2,
                                       String promotionName,
                                       int percentPromotedItems,
                                       String promotionFilterArn,
                                       String promotionParameterName,
                                       String promotionParameterValue1,
                                       String promotionParameterValue2) {

  try {
        
      Map<String, String> promotionFilterValues = new HashMap<>();

      promotionFilterValues.put(promotionParameterName, String.format("\"%1$s\",\"%2$s\"",
              promotionParameterValue1, promotionParameterValue2));
              
      Promotion newPromotion = Promotion.builder()
              .name(promotionName)
              .percentPromotedItems(percentPromotedItems)
              .filterArn(promotionFilterArn)
              .filterValues(promotionFilterValues)
              .build();
              
      List<Promotion> promotionList = new List<>();
      
      promotionList.add(newPromotion);
      
      Map<String, String> requestfilterValues = new HashMap<>();

      requestfilterValues.put(requestParameterName, String.format("\"%1$s\",\"%2$s\"",
              requestParameterValue1, requestParameterValue2));
              
      GetRecommendationsRequest recommendationsRequest = GetRecommendationsRequest.builder()
              .campaignArn(campaignArn)
              .numResults(20)
              .userId(userId)
              .filterArn(requestFilterArn)
              .fitlerValues(requestFilterValues)
              .promotions(promotionList)
              .build();

      GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient.getRecommendations(recommendationsRequest);
      List<PredictedItem> items = recommendationsResponse.itemList();

      for (PredictedItem item: items) {
          System.out.println("Item Id is : "+item.itemId());
          System.out.println("Item score is : "+item.score());
          System.out.println("Promotion name is : "+item.promotionName());
      }
  } catch (PersonalizeRuntimeException e) {
      System.err.println(e.awsErrorDetails().errorMessage());
      System.exit(1);
  }
}
```

------
#### [ SDK for JavaScript v3 ]

```
// Get service clients and commands using ES6 syntax.
import { GetRecommendationsCommand, PersonalizeRuntimeClient } from
  "@aws-sdk/client-personalize-runtime";

// create personalizeRuntimeClient.
const personalizeRuntimeClient = new PersonalizeRuntimeClient({
  region: "REGION",
});

// set recommendation request param
export const getRecommendationsParam = {
  campaignArn: "CAMPAIGN_ARN",  /* required */
  userId: "USER_ID", /* required */
  numResults: 25, /* optional */
  filterArn: "FILTER_ARN", /* provide if you are applying a custom filter */
  filterValues: {
    "PARAM_NAME": "\"PARAM_VALUE\"" /* provide if your filter has a placeholder parameter */
  },
  promotions: [
    {
      name: "PROMOTION_NAME", /* specify the name of the promotion. The recommendation response includes the name to identify promoted items. */
      percentPromotedItems: 50, /* the percentage of recommended items to apply the promotion to. */
      filterArn:
        "PROMOTION_FILTER_ARN", /* the Amazon Resource Name (ARN) of the filter that defines the promotion criteria. */
      filterValues: {
        "PARAM_NAME": "\"PARAM_VALUE\"" /* provide if your promotion filter has a placeholder parameter */
      },
    },
  ],
};

export const run = async () => {
  try {
    const response = await personalizeRuntimeClient.send(new GetRecommendationsCommand(getRecommendationsParam));
    console.log("Success!", "\nItems are: ");
    response.itemList.forEach(element => console.log(element.itemId))
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

------

 A list of recommended items displays. Promoted items are positioned randomly relative to other recommended items, but in sorted order relative to other promoted items. Depending on your recipe, recommended items that aren't part of a promotion are sorted by relevance to the user, popularity, or similarity. If there aren't enough items that meet the promotion criteria, the result will contain as many promoted items as possible. 

```
{
  "itemList": [
      { 
          "itemId1": "123",
          "score": .0117211,
          "promotionName": "promotionName"
      },
      { 
         "itemId2": "456",
         "score": .0077976
      },
      { 
         "itemId3": "789",
         "score": .0067171
      },
      .....
 ]
```