

# Getting recommendations from Amazon Personalize
<a name="getting-recommendations"></a>

 After you [create a recommender](creating-recommenders.md) or [create a campaign](campaigns.md), you are ready to get recommendations. Depending on your resources, you can get recommendations in real time or with a batch workflow. 
+  With custom resources, you can get real-time recommendations or batch recommendations. For real-time recommendations, you must create a custom campaign before you get recommendations. For batch recommendations, you don't need to create a campaign.
+  With recommenders in a Domain dataset group, you can get only real-time recommendations. 

 The following topics explain how and when to use each recommendation type. With both batch and real-time recommendations, you can filter results. For more information see [Filtering recommendations and user segments](filter.md). 

**Topics**
+ [Recommendation scores](#how-scores-work)
+ [Real-time item recommendations in Amazon Personalize](recommendations.md)
+ [Real-time action recommendations in Amazon Personalize](get-action-recommendations.md)
+ [Getting a personalized ranking (custom resources)](rankings.md)
+ [Increasing recommendation relevance with contextual metadata](contextual-metadata.md)
+ [Getting batch item recommendations with custom resources](getting-batch-recommendations.md)
+ [Getting batch user segments with custom resources](getting-user-segments.md)

## Recommendation scores
<a name="how-scores-work"></a>

 With custom solutions created with the User-Personalization-v2, User-Personalization, Personalized-Ranking-v2, Personalized-Ranking, and PERSONALIZED\$1ACTIONS recipes, Amazon Personalize includes a score for each item in recommendations. These scores represent the relative certainty that Amazon Personalize has about which item or action the user will select next. Higher scores represent greater certainty. 
+ For information about scores for User-Personalization-v2 and User-Personalization, see [How recommendation scoring works (custom resources)](recommendations.md#how-recommendation-scoring-works). 
+ For information about scores for PERSONALIZED\$1ACTIONS recipes, see [How action recommendation scoring works](get-action-recommendations.md#how-action-recommendation-scoring-works). 
+  For information on scores for Personalized-Ranking-v2 and Personalized-Ranking recommendations, see [How personalized ranking scoring works](rankings.md#how-ranking-scoring-works).

 For batch inference jobs, item scores are calculated just as described in [How recommendation scoring works (custom resources)](recommendations.md#how-recommendation-scoring-works) and [How personalized ranking scoring works](rankings.md#how-ranking-scoring-works). You can view scores in the batch inference job's output JSON file. 

# Real-time item recommendations in Amazon Personalize
<a name="recommendations"></a>

 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)
<a name="how-recommendation-scoring-works"></a>

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
<a name="recommendation-reasons"></a>

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
<a name="getting-real-time-item-recommendations"></a>

 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)
<a name="get-real-time-recommendations-console"></a>

 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)
<a name="get-item-rec-cli"></a>

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)
<a name="get-item-rec-sdk"></a>

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
<a name="getting-recommendations-with-metadata"></a>

 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)
<a name="getting-recommendations-with-metadata-cli"></a>

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)
<a name="getting-recommendations-with-metadata-sdk"></a>

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
<a name="promoting-items"></a>

 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
<a name="promotion-use-case-recipes"></a>

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
<a name="promotion-filters"></a>

 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
<a name="promoting-new-items"></a>

 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)
<a name="promoting-items-console"></a>

 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)
<a name="promoting-items-cli"></a>

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)
<a name="promoting-items-sdk"></a>

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
      },
      .....
 ]
```

# Real-time action recommendations in Amazon Personalize
<a name="get-action-recommendations"></a>

 If you use a PERSONALIZED\$1ACTIONS recipe, you can get action recommendations from your campaign in real time. You can get action recommendations with the Amazon Personalize console, AWS Command Line Interface (AWS CLI), or AWS SDKs. 

**Topics**
+ [How action recommendation scoring works](#how-action-recommendation-scoring-works)
+ [Getting action recommendations (console)](#get-action-recommendations-console)
+ [Getting action recommendations (AWS CLI)](#get-action-recommendations-cli-example)
+ [Getting action recommendations (AWS SDKs)](#get-action-recommendations-sdk-example)

## How action recommendation scoring works
<a name="how-action-recommendation-scoring-works"></a>

With the Next-Best-Action recipe, Amazon Personalize generates scores for actions based on the likelihood that the user will interact with the action. Scores can be between 0 – 1.0. The closer to 1.0, the more likely it is that the user will interact with the action.

 If you haven't imported any action interaction data, all recommended actions will have a score of 0.0. If Amazon Personalize recommends an action as part of *exploration*, the item will have a score of 0.0. Amazon Personalize uses exploration to recommend actions without action interaction data. For more information about exploration, see [Exploration](use-case-recipe-features.md#about-exploration).

## Getting action recommendations (console)
<a name="get-action-recommendations-console"></a>

 To get action recommendations with the Amazon Personalize console, you provide the request information on the details page of your custom campaign.

**To get action 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 you're using.

1. In the navigation pane, under **Custom resources**, choose **Campaigns**.

1. Choose the target campaign.

1. Under **Test campaign results**, enter your recommendation request details.

    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. Choose **Get recommendations**. A table containing the user’s top 5 recommended actions appears. 

## Getting action recommendations (AWS CLI)
<a name="get-action-recommendations-cli-example"></a>

Use the following code to get action recommendations from a campaign. Specify the ID of the user that you want to get recommendations for and the Amazon Resource Name (ARN) of your campaign.

To change the number of recommended actions, change the value for `numResults`. The default is 5 actions. The maximum is 100 actions. 

To filter actions recommendations by custom criteria, you can create a filter and apply it to the `get-action-recommendations` operation. For more information, see [Filtering recommendations and user segments](filter.md).

 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-action-recommendations \
--campaign-arn campaign arn \
--user-id User ID \
--num-results 10
```

## Getting action recommendations (AWS SDKs)
<a name="get-action-recommendations-sdk-example"></a>

The following code shows how to get Amazon Personalize recommendations for a user from a campaign. Specify the ID of the user you want to get recommendations for, and the Amazon Resource Name (ARN) of your campaign. 

To change the number of recommended actions, change the value for `numResults`. The default is 5 actions. The maximum is 100 actions.

To filter actions recommendations by custom criteria, you can create a filter and apply it to the [GetActionRecommendations](API_RS_GetActionRecommendations.md) API request. For more information, see [Filtering recommendations and user segments](filter.md).

 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). 

```
import boto3

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

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

print("Recommended actions")
for item in response['actionList']:
    print (item['actionId'])
```

# Getting a personalized ranking (custom resources)
<a name="rankings"></a>

A personalized ranking is a list of recommended items that are re-ranked for a specific user. To get personalized rankings, call the [GetPersonalizedRanking](API_RS_GetPersonalizedRanking.md) API operation or get recommendations from a campaign in the console.

**Note**  
The solution backing the campaign must have been created using a recipe of type PERSONALIZED\$1RANKING. For more information, see [Choosing a recipe](working-with-predefined-recipes.md).

**Topics**
+ [How personalized ranking scoring works](#how-ranking-scoring-works)
+ [Getting a personalized ranking (console)](get-ranking-recommendations-console.md)
+ [Getting a personalized ranking (AWS CLI)](get-personalized-rankings-cli.md)
+ [Getting a personalized ranking (AWS SDKs)](get-personalized-rankings-sdk.md)
+ [Personalized-Ranking sample notebook](#real-time-recommendations-personalized-ranking-example)

## How personalized ranking scoring works
<a name="how-ranking-scoring-works"></a>

Like the scores returned by the `GetRecommendations` operation for solutions created with the User-Personalization-v2 and User-Personalization recipes, `GetPersonalizedRanking` scores sum to 1, but only the input items receive scores and recommendation scores tend to be higher. If an item wasn't present during the latest training, it receives a score of 0.

Mathematically, the scoring function for GetPersonalizedRanking is identical to `GetRecommendations`, except that it only considers the input items. This means that scores closer to 1 become more likely, as there are fewer other choices to divide up the score:

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


# Getting a personalized ranking (console)
<a name="get-ranking-recommendations-console"></a>

To get a personalized ranking for a user from the Amazon Personalize console, choose the campaign that you are using and then provide their user ID, specify the list of items you want ranked for the user, optionally choose a filter, and optionally provide any context data. 

**To get a personalized ranking for a user**

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 you are using.

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

1. On the **Campaigns** page, choose the target campaign.

1.  Under **Test campaign results**, enter the **User ID** of the user that you want to get recommendations for. 

1. For **Item IDs**, enter the list of items to be ranked for the user.

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

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

1. If your campaign uses contextual metadata (for requirements see [Increasing recommendation relevance with contextual metadata](contextual-metadata.md)) optionally provide context data. 

   For each context, for the **Key**, enter the metadata field, and for the **Value**, enter the context data. 

1. Choose **Get personalized item rankings**. A table containing the items ranked in order of predicted interest for the user appears. 

# Getting a personalized ranking (AWS CLI)
<a name="get-personalized-rankings-cli"></a>

The following code samples show how different variations of how to get a personalized ranking with the AWS CLI.

**Topics**
+ [Getting a personalized ranking](#personalized-ranking-cli-sample)
+ [Including item metadata in a personalized ranking](#getting-personalized-ranking-with-metadata-cli)

## Getting a personalized ranking
<a name="personalized-ranking-cli-sample"></a>

 Use the following `get-personalized-ranking` command to get a personalized ranking with the AWS CLI. Specify the Amazon Resource Name (ARN) for your campaign, the User ID for the user, and provide a list of item IDs for the items to be ranked for the user (each separated by a space). The items to be ranked must be in the data that you used to train the solution version. A list of ranked recommendations displays. Amazon Personalize considers the first item in the list of most interest to the user. 

```
aws personalize-runtime get-personalized-ranking \
--campaign-arn Campaign ARN \
--user-id 12 \
--input-list 3 4 10 8 12 7
```

## Including item metadata in a personalized ranking
<a name="getting-personalized-ranking-with-metadata-cli"></a>

If you enabled metadata in recommendations for your campaign, you can specify the Items dataset metadata columns to include in the response. For information about enabling metadata, see [Item metadata in recommendations](campaigns.md#create-campaign-return-metadata).

The following code sample shows how to specify the metadata columns as part of your request for a personalized ranking.

```
aws personalize-runtime get-personalized-ranking \
--campaign-arn Campaign ARN \
--user-id 12 \
--input-list 3 4 10 8 12 7
--metadata-columns "{\"ITEMS\": ["\"columnNameA"\","\"columnNameB"\"]}"
```

# Getting a personalized ranking (AWS SDKs)
<a name="get-personalized-rankings-sdk"></a>

The following code samples show how different variations of how to get a personalized ranking with the AWS SDKs.

**Topics**
+ [Getting a personalized ranking](#personalized-ranking-sdk-sample)
+ [Including item metadata in a personalized ranking](#getting-personalized-ranking-with-metadata-sdk)
+ [Getting a personalized ranking using contextual metadata](#personalized-ranking-contextual-metadata-example)

## Getting a personalized ranking
<a name="personalized-ranking-sdk-sample"></a>

The following code shows how to get a personalized ranking for a user. Specify the user's ID and a list of item IDs to be ranked for the user. The item IDs must be in the data that you used to train the solution version. A list of ranked recommendations is returned. Amazon Personalize considers the first item in the list of most interest to the user.

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

```
import boto3

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

response = personalizeRt.get_personalized_ranking(
    campaignArn = "Campaign arn",
    userId = "UserID",
    inputList = ['ItemID1','ItemID2']
)

print("Personalized Ranking")
for item in response['personalizedRanking']:
    print (item['itemId'])
```

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

```
public static List<PredictedItem> getRankedRecs(PersonalizeRuntimeClient personalizeRuntimeClient,
                                                String campaignArn,
                                                String userId,
                                                ArrayList<String> items) {

    try {
        GetPersonalizedRankingRequest rankingRecommendationsRequest = GetPersonalizedRankingRequest.builder()
                .campaignArn(campaignArn)
                .userId(userId)
                .inputList(items)
                .build();
  
        GetPersonalizedRankingResponse recommendationsResponse =
                personalizeRuntimeClient.getPersonalizedRanking(rankingRecommendationsRequest);
        List<PredictedItem> rankedItems = recommendationsResponse.personalizedRanking();
        int rank = 1;
        for (PredictedItem item : rankedItems) {
            System.out.println("Item ranked at position " + rank + " details");
            System.out.println("Item Id is : " + item.itemId());
            System.out.println("Item score is : " + item.score());
            System.out.println("---------------------------------------------");
            rank++;
        }
        return rankedItems;
    } catch (PersonalizeRuntimeException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    return null;
}
```

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

```
// Get service clients module and commands using ES6 syntax.
import { GetPersonalizedRankingCommand } 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 ranking request parameters.
export const getPersonalizedRankingParam = {
  campaignArn: "CAMPAIGN_ARN" /* required */,
  userId: "USER_ID" /* required */,
  inputList: ["ITEM_ID_1", "ITEM_ID_2", "ITEM_ID_3", "ITEM_ID_4"],
};

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

------

## Including item metadata in a personalized ranking
<a name="getting-personalized-ranking-with-metadata-sdk"></a>

If you enabled metadata in recommendations for your campaign, you can specify the Items dataset metadata columns to include in the response. For information about enabling metadata, see [Item metadata in recommendations](campaigns.md#create-campaign-return-metadata).

The following code sample shows how to specify the metadata columns as part of your request for a personalized ranking.

```
import boto3

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

response = personalizeRt.get_personalized_ranking(
    campaignArn = "Campaign arn",
    userId = "UserID",
    inputList = ['ItemID1','ItemID2'],
    metadataColumns = {
      "ITEMS": ['columnNameA','columnNameB']
    }
)

print("Personalized Ranking")
for item in response['personalizedRanking']:
    print (item['itemId'])
    print (item['metadata'])
```

## Getting a personalized ranking using contextual metadata
<a name="personalized-ranking-contextual-metadata-example"></a>

Use the following code to get a personalized ranking based on contextual metadata. For `context`, for each key-value pair, provide the metadata field as the key and the context data as the value. In the following sample code, the key is `DEVICE` and the value is `mobile phone`. Replace these values and the `Campaign ARN` and `User ID` with your own. Also change `inputList` to a list of item IDs that are in the data that you used to train the solution. Amazon Personalize considers the first item in the list of most interest to the user.

```
import boto3

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

response = personalizeRt.get_personalized_ranking(
    campaignArn = "Campaign ARN",
    userId = "User ID",
    inputList = ['ItemID1', 'ItemID2'],
    context = {
      'DEVICE': 'mobile phone'
    }
)

print("Personalized Ranking")
for item in response['personalizedRanking']:
  print(item['itemId'])
```

## Personalized-Ranking sample notebook
<a name="real-time-recommendations-personalized-ranking-example"></a>

 For a sample Jupyter notebook that shows how to use the Personalized-Ranking recipe see [Personalize Ranking Example](https://github.com/aws-samples/amazon-personalize-samples/blob/master/next_steps/core_use_cases/personalized_ranking/personalize_ranking_example.ipynb). 

# Increasing recommendation relevance with contextual metadata
<a name="contextual-metadata"></a>

To increase recommendation relevance, include contextual metadata for a user, such as their device type or the time of day, when you get item recommendations or get a personalized ranking. 

To use contextual metadata, the schema of the Item interactions dataset must have  metadata fields for the contextual data. For example, a DEVICE field (see [Creating schema JSON files for Amazon Personalize schemas](how-it-works-dataset-schema.md)). When considering fields to use for contextual metadata, select fields where the values are available for historical data in the Item interactions dataset, and when you get item recommendations or get a personalized ranking of items.

For Domain dataset groups, the following recommender use cases can use contextual metadata:
+ [Recommended for you](ECOMMERCE-use-cases.md#recommended-for-you-use-case) (ECOMMERCE domain)
+ [Top picks for you](VIDEO_ON_DEMAND-use-cases.md#top-picks-use-case) (VIDEO\$1ON\$1DEMAND domain)

 For custom resources, recipes that use contextual metadata include the following:
+  [User-Personalization-v2](native-recipe-user-personalization-v2.md) and [User-Personalization](native-recipe-new-item-USER_PERSONALIZATION.md) 
+  [Personalized-Ranking-v2](native-recipe-personalized-ranking-v2.md) and [Personalized-Ranking](native-recipe-search.md)

 For more information on contextual information, see the following AWS Machine Learning Blog post: [ Increasing the relevance of your Amazon Personalize recommendations by leveraging contextual information](https://aws.amazon.com/blogs/machine-learning/increasing-the-relevance-of-your-amazon-personalize-recommendations-by-leveraging-contextual-information/). 

You can get recommendations with contextual metadata with the Amazon Personalize console, AWS Command Line Interface (AWS CLI), or AWS SDKs.

## Getting recommendations using contextual metadata (AWS Python SDK)
<a name="get-recommendations-metadata-sdk-example"></a>

To increase recommendation relevance, include contextual metadata for a user, such as their device type or the time of day, when you get item recommendations or get a personalized ranking. 

Use the following code to get a recommendation based on contextual metadata. For `context`, for each key-value pair, provide the metadata field as the key and the context data as the value. In the following sample code, the key is `DEVICE` and the value is `mobile phone`. Replace these values and the `Campaign ARN` and `User ID` with your own. If you created a recommender, replace `campaignArn` with `recommenderArn`. A list of recommended items for the user displays. 

```
import boto3

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

response = personalizeRt.get_recommendations(
    campaignArn = 'Campaign ARN',
    userId = 'User ID',
    context = {
      'DEVICE': 'mobile phone'
    }
)

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

# Getting batch item recommendations with custom resources
<a name="getting-batch-recommendations"></a>

 With custom resources, you can get item recommendations with an asynchronous batch flow. For example, you might get product recommendations for all users on an email list or [item-to-item similarities](native-recipe-similar-items.md) across an inventory. 

 To get batch recommendations for items, you use a batch inference job. A *batch inference job* is a tool that imports your batch input data from an Amazon S3 bucket, uses your custom solution version to generate *item recommendations*, and then exports the item recommendations to an Amazon S3 bucket. Depending on the recipe, your input data is a list of users, or items, or a list of users each with a collection of items.

 If your solution uses the Similar Items recipe and you have an Items dataset with textual data and item title data, you can generate batch recommendations with themes for each group of items. For more information, see [Batch recommendations with themes from Content Generator](themed-batch-recommendations.md). 

 After you create a custom solution version, how new data influences batch item recommendations depends on its type, the method of import, and the custom recipe you use. For information about how new data influences batch recommendations, see [How new data influences batch recommendations (custom resources)](how-new-data-influences-batch-recommendations.md).

**Topics**
+ [Batch workflow](#batch-worfklow-steps)
+ [Guidelines and requirements](#batch-permissions-req)
+ [Batch workflow scoring](#batch-scoring)
+ [Batch recommendations with themes from Content Generator](themed-batch-recommendations.md)
+ [Preparing input data for batch recommendations](batch-data-upload.md)
+ [Creating a batch inference job](creating-batch-inference-job.md)
+ [Batch inference job output examples](batch-inference-job-output-examples.md)

## Batch workflow
<a name="batch-worfklow-steps"></a>

The batch workflow is as follows:

1.  Prepare and upload your input data in JSON format to an Amazon S3 bucket. The format of your input data depends on the recipe you use. See [Preparing input data for batch recommendations](batch-data-upload.md). 

1.  Create a separate location for your output data, either a folder or a different Amazon S3 bucket. 

1.  Create a batch inference job. See [Creating a batch inference job](creating-batch-inference-job.md). 

1.  When the batch inference is complete, retrieve the item recommendations from your output location in Amazon S3. 

## Guidelines and requirements
<a name="batch-permissions-req"></a>

The following are guidelines and requirements for getting batch recommendations:
+ Your Amazon Personalize IAM service role must have permission to read and add files to your Amazon S3 buckets. For information on granting permissions, see [Service role policy for batch workflows](granting-personalize-s3-access.md#role-policy-for-batch-workflows). For more information on bucket permissions, see [User policy examples](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-policies-s3.html) in the *Amazon Simple Storage Service Developer Guide*. If you use AWS Key Management Service (AWS KMS) for encryption, you must grant Amazon Personalize and your Amazon Personalize IAM service role permission to use your key. For more information, see [Giving Amazon Personalize permission to use your AWS KMS key](granting-personalize-key-access.md).
+  You must create a custom solution and solution version before you create a batch inference job. However, you don't need to create an Amazon Personalize campaign. If you created a Domain dataset group, you can still create custom resources. 
+  To generate themes with recommendations, you must use the Similar-Items recipe. And you must have an Items dataset with textual data and item title data. For more information about themed recommendations, see [Batch recommendations with themes from Content Generator](themed-batch-recommendations.md). 
+  Your input data must be formatted as described in [Preparing input data for user segments](prepare-input-data-user-segment.md). 
+ You can't get batch recommendations with the Trending-Now or Next-Best-Action recipes.
+ If you use a filter with placeholder parameters, you must include the values for the parameters in your input data in a `filterValues` object. For more information, see [Providing filter values in your input JSON](filter-batch.md#providing-filter-values). 
+ We recommend that you use a different location for your output data (either a folder or a different Amazon S3 bucket) than your input data. 
+  Batch recommendations might not be exactly the same as real-time recommendations. This is because batch inference jobs take longer to complete and only consider data available 15 minutes before the start of the job. 

## Batch workflow scoring
<a name="batch-scoring"></a>

Batch recommendations include scores as follows:
+ With User-Personalization and Personalized-Ranking recipes, Amazon Personalize calculates batch inference job recommendation scores as described in [How recommendation scoring works (custom resources)](recommendations.md#how-recommendation-scoring-works) and [How personalized ranking scoring works](rankings.md#how-ranking-scoring-works). You can view scores in the batch inference job's output JSON file.
+  With the Similar-Items recipe, if you get themed batch recommendations, Amazon Personalize ranks each set of related items based on how relevant the theme is for each item. Each item includes a score from 0 to 1. The higher the score, the more closely related the item is to the theme. For more information about recommendations with themes, see [Batch recommendations with themes from Content Generator](themed-batch-recommendations.md). 

# Batch recommendations with themes from Content Generator
<a name="themed-batch-recommendations"></a>

**Important**  
When you get batch recommendations with themes, you incur additional costs. For more information, see [Amazon Personalize pricing](https://aws.amazon.com/personalize/pricing/).

If you use the [Similar-Items recipe](native-recipe-similar-items.md), Amazon Personalize Content Generator can add descriptive themes to batch recommendations. *Content Generator* is a generative artificial intelligence (generative AI) capability managed by Amazon Personalize.

 When you get batch recommendations with themes, Amazon Personalize Content Generator adds a descriptive theme for each set of similar items. The theme is based on the item description and item name data in your Items dataset. Amazon Personalize includes the themes in the output of the batch inference job. You can use the themes to make the text in your application or marketing messages more compelling.

For example, if you get related items recommendations for a breakfast food item, Amazon Personalize might generate a theme like *Rise and shine* or *Morning essentials*. You might use the theme to replace a generic carousel title, like *Frequently bought together*. Or you might incorporate the theme in a promotional email or marketing campaign for new menu options. 

 AWS doesn't monitor themes from Content Generator. To confirm the theme quality, you can use the scores produced for each recommended item. For more information, see [Ranking and scoring for batch recommendations with themes](#themed-batch-rec-scoring). 

**Topics**
+ [Supported regions](#themes-regions)
+ [Guidelines and requirements](#themed-batch-requirements)
+ [Ranking and scoring for batch recommendations with themes](#themed-batch-rec-scoring)
+ [Generating batch recommendations with themes](#getting-themed-batch-rec)

## Supported regions
<a name="themes-regions"></a>

Amazon Personalize Content Generator is only available in the following AWS Regions: 
+ US East (N. Virginia)
+ US West (Oregon)
+ Asia Pacific (Tokyo)

## Guidelines and requirements
<a name="themed-batch-requirements"></a>

The following are guidelines and requirements for generating recommendations with themes:
+ Your input file can have up to 100 items. For information about input data for batch recommendations, see [Preparing input data for batch recommendations](batch-data-upload.md).
+ Your solution must use the [Similar-Items recipe](native-recipe-similar-items.md).
+ You must have an Items dataset with the following data. This data can help generate more relevant themes.
  +  It must have a textual field, such as a DESCRIPTION field. For information about textual data, see [Unstructured text metadata](items-datasets.md#text-data).
  +  It must have a string column with item name data, such as a TITLE field. 

   If your Items dataset doesn't have this data, you can add it. For information about updating existing data, see [Updating data in datasets after training](updating-datasets.md). 

## Ranking and scoring for batch recommendations with themes
<a name="themed-batch-rec-scoring"></a>

When you get batch recommendations with themes, Amazon Personalize ranks each set of items based on how relevant the theme is for each item. Each item includes a score in a rough range of -0.1 and 0.6. The higher the score, the more closely related the item is to the theme. You might use the scores to set a threshold to show only items that are strongly related to the theme. 

 For example, Amazon Personalize might return a theme of `For your sweet tooth`, and the related items and their scores might be: hard candy (score 0.19884521), chocolate (score .17664525), apple (score .08994528), popsicle (score .14294521), sweet potato (score .07794527), and carrot (score .04994523). In your application, you might add a rule to include only items with a score of `.10` or greater, eliminating the fruits and vegetables. 

 The following example shows the format of the output of a batch inference job that generates movie recommendations with themes. 

```
{"input":{"itemId":"40"},"output":{"recommendedItems":["36","50","44","22","21","29","3","1","2","39"],"theme":"Movies with a strong female lead","itemsThemeRelevanceScores":[0.19994527,0.183059963,0.17478035,0.1618133,0.1574806,0.15468733,0.1499242,0.14353688,0.13531424,0.10291852]}}
{"input":{"itemId":"43"},"output":{"recommendedItems":["50","21","36","3","17","2","39","1","10","5"],"theme":"The best movies of 1995","itemsThemeRelevanceScores":[0.184988,0.1795761,0.11143453,0.0989443,0.08258403,0.07952615,0.07115086,0.0621634,-0.138913,-0.188913]}}
...
```

## Generating batch recommendations with themes
<a name="getting-themed-batch-rec"></a>

To generate batch recommendations with themes, you complete the batch workflow as described in [Batch workflow](getting-batch-recommendations.md#batch-worfklow-steps). You prepare your input data in the same way you would for a `RELATED_ITEMS` recipe. For an example, see [RELATED\$1ITEMS recipes](batch-data-upload.md#batch-input-related-items).

 When you create the batch inference job, you enable theme generation and specify the item title column of your Items dataset.
+ For information about using the Amazon Personalize console to create a batch inference job that generates themes, see [Creating a batch inference job](creating-batch-inference-job.md). 
+ For a code sample that shows how to use the SDK for Python (Boto3) to create a batch inference job that generates themes, see [Creating a batch inference job that generates themes](creating-batch-inference-job.md#batch-sdk-themes). 

# Preparing input data for batch recommendations
<a name="batch-data-upload"></a>

 A batch inference job imports your batch input JSON data from an Amazon S3 bucket, uses your custom solution version to generate recommendations, and then exports the item recommendations to an Amazon S3 bucket. Before you can get batch recommendations, you must prepare and upload your JSON file to an Amazon S3 bucket. We recommend that you create an output folder in your Amazon S3 bucket or use a separate output Amazon S3 bucket. You can then run multiple batch inference jobs using the same input data location. 

 If you use a filter with placeholder parameters, such as `$GENRE`, you must provide the values for the parameters in a `filterValues` object in your input JSON. For more information, see [Providing filter values in your input JSON](filter-batch.md#providing-filter-values). 

**To prepare and import data**

1. Format your batch input data depending on your recipe. You can't get batch recommendations with the Trending-Now recipe.
   + For USER\$1PERSONALIZATION recipes and the Popularity-Count recipe, your input data is a JSON file with a list of userIds
   + For RELATED\$1ITEMS recipes, your input data is a list of itemIds
   + For PERSONALIZED\$1RANKING recipes, your input data is a list of userIds, each paired with a collection of itemIds

   Separate each row with a new line. For input data examples, see [Batch inference job input and output JSON examples](#batch-inference-job-json-examples).

1.  Upload your input JSON to an input folder in your Amazon S3 bucket. For more information, see [Uploading files and folders by using drag and drop](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/upload-objects.html) in the *Amazon Simple Storage Service User Guide* 

1.  Create a separate location for your output data, either a folder or a different Amazon S3 bucket. By creating a separate location for the output JSON, you can run multiple batch inference jobs with the same input data location.

1.  Create a batch inference job. Amazon Personalize outputs the recommendations from your solution version to your output data location. 

## Batch inference job input and output JSON examples
<a name="batch-inference-job-json-examples"></a>

How you format your input data the recipe you use. If you use a filter with placeholder parameters, such as `$GENRE`, you must provide the values for the parameters in a `filterValues` object in your input JSON. For more information, see [Providing filter values in your input JSON](filter-batch.md#providing-filter-values). 

 The following sections list correctly formatted JSON input and output examples for batch inference jobs. You can't get batch recommendations with the Trending-Now recipe.

**Topics**
+ [USER\$1PERSONALIZATION recipes](#batch-input-user-personalization)
+ [POPULAR\$1ITEMS recipes (Popularity-Count only)](#batch-input-popular-items)
+ [PERSONALIZED\$1RANKING recipes](#batch-input-ranking)
+ [RELATED\$1ITEMS recipes](#batch-input-related-items)

### USER\$1PERSONALIZATION recipes
<a name="batch-input-user-personalization"></a>

 The following shows correctly formatted JSON input and output examples for the USER\$1PERSONALIZATION recipes. If you use User-Personalization-v2, each recommended item includes a list of reasons for why the item was included in recommendations. This list can be empty. For information about possible reasons, see [Recommendation reasons with User-Personalization-v2](recommendations.md#recommendation-reasons). 

------
#### [ Input ]

Separate each `userId` with a new line as follows.

```
{"userId": "4638"}
{"userId": "663"}
{"userId": "3384"}
...
```

------
#### [ Output ]

```
{"input":{"userId":"4638"},"output":{"recommendedItems":["63992","115149","110102","148626","148888","31685","102445","69526","92535","143355","62374","7451","56171","122882","66097","91542","142488","139385","40583","71530","39292","111360","34048","47099","135137"],"scores":[0.0152238,0.0069081,0.0068222,0.006394,0.0059746,0.0055851,0.0049357,0.0044644,0.0042968,0.004015,0.0038805,0.0037476,0.0036563,0.0036178,0.00341,0.0033467,0.0033258,0.0032454,0.0032076,0.0031996,0.0029558,0.0029021,0.0029007,0.0028837,0.0028316]},"error":null}
{"input":{"userId":"663"},"output":{"recommendedItems":["368","377","25","780","1610","648","1270","6","165","1196","1097","300","1183","608","104","474","736","293","141","2987","1265","2716","223","733","2028"],"scores":[0.0406197,0.0372557,0.0254077,0.0151975,0.014991,0.0127175,0.0124547,0.0116712,0.0091098,0.0085492,0.0079035,0.0078995,0.0075598,0.0074876,0.0072006,0.0071775,0.0068923,0.0066552,0.0066232,0.0062504,0.0062386,0.0061121,0.0060942,0.0060781,0.0059263]},"error":null}
{"input":{"userId":"3384"},"output":{"recommendedItems":["597","21","223","2144","208","2424","594","595","920","104","520","367","2081","39","1035","2054","160","1370","48","1092","158","2671","500","474","1907"],"scores":[0.0241061,0.0119394,0.0118012,0.010662,0.0086972,0.0079428,0.0073218,0.0071438,0.0069602,0.0056961,0.0055999,0.005577,0.0054387,0.0051787,0.0051412,0.0050493,0.0047126,0.0045393,0.0042159,0.0042098,0.004205,0.0042029,0.0040778,0.0038897,0.0038809]},"error":null}
...
```

------

### POPULAR\$1ITEMS recipes (Popularity-Count only)
<a name="batch-input-popular-items"></a>

 The following shows correctly formatted JSON input and output examples for the Popularity-Count recipe. You can't get batch recommendations with the Trending-Now recipe. 

------
#### [ Input ]

Separate each `userId` with a new line as follows.

```
{"userId": "12"}
{"userId": "105"}
{"userId": "41"}
...
```

------
#### [ Output ]

```
{"input": {"userId": "12"}, "output": {"recommendedItems": ["105", "106", "441"]}}
{"input": {"userId": "105"}, "output": {"recommendedItems": ["105", "106", "441"]}}
{"input": {"userId": "41"}, "output": {"recommendedItems": ["105", "106", "441"]}}
...
```

------

### PERSONALIZED\$1RANKING recipes
<a name="batch-input-ranking"></a>

 The following shows correctly formatted JSON input and output examples for PERSONALIZED\$1RANKING recipes. 

------
#### [ Input ]

Separate each `userId` and list of `itemIds` to be ranked with a new line as follows.

```
{"userId": "891", "itemList": ["27", "886", "101"]}
{"userId": "445", "itemList": ["527", "55", "901"]}
{"userId": "71", "itemList": ["27", "351", "101"]}
...
```

------
#### [ Output ]

```
{"input":{"userId":"891","itemList":["27","886","101"]},"output":{"recommendedItems":["27","101","886"],"scores":[0.48421,0.28133,0.23446]}}
{"input":{"userId":"445","itemList":["527","55","901"]},"output":{"recommendedItems":["901","527","55"],"scores":[0.46972,0.31011,0.22017]}}
{"input":{"userId":"71","itemList":["29","351","199"]},"output":{"recommendedItems":["351","29","199"],"scores":[0.68937,0.24829,0.06232]}}
...
```

------

### RELATED\$1ITEMS recipes
<a name="batch-input-related-items"></a>

 The following shows correctly formatted JSON input and output examples for RELATED\$1ITEMS recipes. 

------
#### [ Input ]

Separate each `itemId` with a new line as follows.

```
{"itemId": "105"}
{"itemId": "106"}
{"itemId": "441"}
...
```

------
#### [ Output ]

```
{"input": {"itemId": "105"}, "output": {"recommendedItems": ["106", "107", "49"]}}
{"input": {"itemId": "106"}, "output": {"recommendedItems": ["105", "107", "49"]}}
{"input": {"itemId": "441"}, "output": {"recommendedItems": ["2", "442", "435"]}}
...
```

------

The following shows correctly formatted JSON input and output examples for the Similar-Items recipe with themes. 

------
#### [ Input ]

Separate each `itemId` with a new line as follows.

```
{"itemId": "40"}
{"itemId": "43"}
...
```

------
#### [ Output ]

```
{"input":{"itemId":"40"},"output":{"recommendedItems":["36","50","44","22","21","29","3","1","2","39"],"theme":"Movies with a strong female lead","itemsThemeRelevanceScores":[0.19994527,0.183059963,0.17478035,0.1618133,0.1574806,0.15468733,0.1499242,0.14353688,0.13531424,0.10291852]}}
{"input":{"itemId":"43"},"output":{"recommendedItems":["50","21","36","3","17","2","39","1","10","5"],"theme":"The best movies of 1995","itemsThemeRelevanceScores":[0.184988,0.1795761,0.11143453,0.0989443,0.08258403,0.07952615,0.07115086,0.0621634,-0.138913,-0.188913]}}
...
```

------

# Creating a batch inference job
<a name="creating-batch-inference-job"></a>

 Create a batch inference job to get batch item recommendations for users based on input data from Amazon S3. The input data can be a list of users or items (or both) in JSON format. You can create a batch inference job with the Amazon Personalize console, the AWS Command Line Interface (AWS CLI), or AWS SDKs. 

 When you create a batch inference job, you specify the Amazon S3 paths to your input and output locations. Amazon S3 is prefix based. If you provide a prefix for the input data location, Amazon Personalize uses all files matching that prefix as input data. For example, if you provide `s3://amzn-s3-demo-bucket/folderName` and your bucket also has a folder with a path of `s3://amzn-s3-demo-bucket/folderName_test`, Amazon Personalize uses all files in both folders as input data. To use only the files within a specific folder as input data, end the Amazon S3 path with a prefix delimiter, such as `/`: `s3://amzn-s3-demo-bucket/folderName/` For more information about how Amazon S3 organizes objects, see [Organizing, listing, and working with your objects](https://docs.aws.amazon.com/AmazonS3/latest/userguide/organizing-objects.html). 

 For more information about the batch workflow in Amazon Personalize, including permissions requirements, recommendation scoring, and preparing and importing input data, see [Getting batch item recommendations with custom resources](getting-batch-recommendations.md). 

**Topics**
+ [Creating a batch inference job (console)](#batch-console)
+ [Creating a batch inference job (AWS CLI)](#batch-cli)
+ [Creating a batch inference job (AWS SDKs)](#batch-sdk)

## Creating a batch inference job (console)
<a name="batch-console"></a>

 After you have completed [Preparing input data for batch recommendations](batch-data-upload.md), you are ready to create a batch inference job. This procedure assumes that you have already created a solution and a solution version (trained model). 

**To create a batch inference job (console)**

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

1. On the **Dataset groups** page, choose your dataset group.

1. From the navigation pane, under **Custom resources**, choose **Batch inference jobs**.

1. Choose **Create batch inference job**.

1.  Choose the batch inference job type. 
   + To generate item recommendations without themes, choose **Item recommendations**.
   +  If you use the Similar-Items recipe and want to add descriptive themes to groups of similar items, choose **Themed recommendations with Content Generator**. To generate themes, you must have an Items dataset with item name data and textual data. For more information, see [Batch recommendations with themes from Content Generator](themed-batch-recommendations.md). 

1. In **Batch inference job details**, in **Batch inference job name**, specify a name for your batch inference job.

1. For **Solution**, choose the solution and then choose the **Solution version ID** that you want to use to generate the recommendations. 

1. For **Number of results**, optionally specify the number of recommendations for each line of input data. The default is 25.

1.  If your batch job generates recommendations with themes, in **Themed recommendations details**, choose the column containing names or titles for the items in your Items dataset. This data can help generate more relevant themes. For more information, see [Batch recommendations with themes from Content Generator](themed-batch-recommendations.md). 

1.  In **Input source**, specify the Amazon S3 path to your input file. 

   Use the following syntax: **s3://amzn-s3-demo-bucket/<folder name>/<input JSON file name>.json**

    Your input data must be in the correct format for the recipe your solution uses. For input data examples see [Batch inference job input and output JSON examples](batch-data-upload.md#batch-inference-job-json-examples). 

1. For **Decryption key**, if you use your own AWS KMS key for bucket encryption, specify the Amazon Resource Name (ARN) of your key. Amazon Personalize must have permission to use your key. For information about granting permissions, see [Giving Amazon Personalize permission to use your AWS KMS key](granting-personalize-key-access.md). 

1. In **Output destination**, specify the path to your output location. We recommend using a different location for your output data (either a folder or a different Amazon S3 bucket).

    Use the following syntax: **s3://amzn-s3-demo-bucket/<output folder name>/** 

1. For **Encryption key**, if you use your own AWS KMS key for encryption, specify the ARN of your key. Amazon Personalize must have permission to use your key. For information about granting permissions, see [Giving Amazon Personalize permission to use your AWS KMS key](granting-personalize-key-access.md). 

1. For **IAM service role**, choose the IAM service role you created for Amazon Personalize during set up. This role must have read and write access to your input and output Amazon S3 buckets respectively.

1.  In **Filters** optionally choose a filter to apply a filter to the batch recommendations. If your filter uses placeholder parameters, make sure the values for the parameters are included in your input JSON. For more information, see [Providing filter values in your input JSON](filter-batch.md#providing-filter-values). 

1. For **Tags**, optionally add any tags. For more information about tagging Amazon Personalize resources, see [Tagging Amazon Personalize resources](tagging-resources.md).

1.  Choose **Create batch inference job**. Batch inference job creation starts and the **Batch inference jobs** page appears with the **Batch inference job detail** section displayed.

    When the batch inference job's status changes to **Active**, you can retrieve the job's output from the designated output Amazon S3 bucket. The output file's name will be of the format `input-name.out`. 

## Creating a batch inference job (AWS CLI)
<a name="batch-cli"></a>

After you have completed [Preparing input data for batch recommendations](batch-data-upload.md), you are ready to create a batch inference job with the [CreateBatchInferenceJob](API_CreateBatchInferenceJob.md) operation. 

**Topics**
+ [Creating a batch inference job](#batch-cli-code-sample)
+ [Creating a batch inference job that generates themes](#batch-cli-themes)

### Creating a batch inference job
<a name="batch-cli-code-sample"></a>

 You can use the `create-batch-inference-job` command to create a batch inference job. Specify a job name, replace `Solution version ARN` with the Amazon Resource Name (ARN) of your solution version, and replace the `IAM service role ARN` with the ARN of the IAM service role you created for Amazon Personalize during set up. This role must have read and write access to your input and output Amazon S3 buckets respectively. Optionally provide a filter ARN to filter recommendations. If your filter uses placeholder parameters, make sure the values for the parameters are included in your input JSON. For more information, see [Filtering batch recommendations and user segments (custom resources)](filter-batch.md). 

Replace `S3 input path` and `S3 output path` with the Amazon S3 path to your input file and output locations. We recommend using a different location for your output data (either a folder or a different Amazon S3 bucket). Use the following syntax for input and output locations: **s3://amzn-s3-demo-bucket/<folder name>/<input JSON file name>.json** and **s3://amzn-s3-demo-bucket/<output folder name>/**. 

The example includes optional User-Personalization recipe specific `itemExplorationConfig` hyperparameters: `explorationWeight` and `explorationItemAgeCutOff`. Optionally include `explorationWeight` and `explorationItemAgeCutOff` values to configure exploration. For more information, see [User-Personalization recipe](native-recipe-new-item-USER_PERSONALIZATION.md). 

```
aws personalize create-batch-inference-job \
--job-name Batch job name \
--solution-version-arn Solution version ARN \
--filter-arn Filter ARN \
--job-input s3DataSource={path=s3://S3 input path} \
--job-output s3DataDestination={path=s3://S3 output path} \
--role-arn IAM service role ARN \
--batch-inference-job-config "{\"itemExplorationConfig\":{\"explorationWeight\":\"0.3\",\"explorationItemAgeCutOff\":\"30\"}}"
```

### Creating a batch inference job that generates themes
<a name="batch-cli-themes"></a>

To generate themes for similar items, you must use the Similar-Items recipe and your Items dataset must have a textual field and a column of item name data. For more information about recommendations with themes, see [Batch recommendations with themes from Content Generator](themed-batch-recommendations.md).

The following code creates a batch inference job that generates recommendations with themes. Leave the `batch-inference-job-mode` set to `THEME_GENERATION`. Replace `COLUMN_NAME` with the name of the column that stores your item name data. 

```
aws personalize create-batch-inference-job \
--job-name Themed batch job name \
--solution-version-arn Solution version ARN \
--filter-arn Filter ARN \
--job-input s3DataSource={path=s3://S3 input path} \
--job-output s3DataDestination={path=s3://S3 output path} \
--role-arn IAM service role ARN \
--batch-inference-job-mode THEME_GENERATION \
--theme-generation-config "{\"fieldsForThemeGeneration\": {\"itemName\":\"COLUMN_NAME\"}}"
```

## Creating a batch inference job (AWS SDKs)
<a name="batch-sdk"></a>

After you have completed [Preparing input data for batch recommendations](batch-data-upload.md), you are ready to create a batch inference job with the [CreateBatchInferenceJob](API_CreateBatchInferenceJob.md) operation. 

**Topics**
+ [Creating a batch inference job](#batch-sdk-code-sample)
+ [Creating a batch inference job that generates themes](#batch-sdk-themes)

### Creating a batch inference job
<a name="batch-sdk-code-sample"></a>

 You can use the following code to create a batch inference job. Specify a job name, the Amazon Resource Name (ARN) of your solution version, and the ARN of the IAM service role you created for Amazon Personalize during set up. This role must have read and write access to your input and output Amazon S3 buckets.

We recommend using a different location for your output data (either a folder or a different Amazon S3 bucket). Use the following syntax for input and output locations: **s3:/amzn-s3-demo-bucket/<folder name>/<input JSON file name>.json** and **s3://amzn-s3-demo-bucket/<output folder name>/**.

 For `numResults`, specify the number of items you want Amazon Personalize to predict for each line of input data. Optionally provide a filter ARN to filter recommendations. If your filter uses placeholder parameters, make sure the values for the parameters are included in your input JSON. For more information, see [Filtering batch recommendations and user segments (custom resources)](filter-batch.md).

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

The example includes optional User-Personalization recipe specific `itemExplorationConfig` hyperparameters: `explorationWeight` and `explorationItemAgeCutOff`. Optionally include `explorationWeight` and `explorationItemAgeCutOff` values to configure exploration. For more information, see [User-Personalization recipe](native-recipe-new-item-USER_PERSONALIZATION.md). 

```
import boto3

personalize_rec = boto3.client(service_name='personalize')

personalize_rec.create_batch_inference_job (
    solutionVersionArn = "Solution version ARN",
    jobName = "Batch job name",
    roleArn = "IAM service role ARN",
    filterArn = "Filter ARN",
    batchInferenceJobConfig = {
        # optional USER_PERSONALIZATION recipe hyperparameters
        "itemExplorationConfig": {      
            "explorationWeight": "0.3",
            "explorationItemAgeCutOff": "30"
        }
    },
    jobInput = 
       {"s3DataSource": {"path": "s3://amzn-s3-demo-bucket/<folder name>/<input JSON file name>.json"}},
    jobOutput = 
       {"s3DataDestination": {"path": "s3:/amzn-s3-demo-bucket/<output folder name>/"}}
)
```

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

The example includes optional User-Personalization recipe specific `itemExplorationConfig` fields: `explorationWeight` and `explorationItemAgeCutOff`. Optionally include `explorationWeight` and `explorationItemAgeCutOff` values to configure exploration. For more information, see [User-Personalization recipe](native-recipe-new-item-USER_PERSONALIZATION.md). 

```
public static String createPersonalizeBatchInferenceJob(PersonalizeClient personalizeClient,
                                                        String solutionVersionArn,
                                                        String jobName,
                                                        String filterArn,
                                                        String s3InputDataSourcePath,
                                                        String s3DataDestinationPath,
                                                        String roleArn,
                                                        String explorationWeight,
                                                        String explorationItemAgeCutOff) {

  long waitInMilliseconds = 60 * 1000;
  String status;
  String batchInferenceJobArn;

  try {
      // Set up data input and output parameters.
      S3DataConfig inputSource = S3DataConfig.builder()
              .path(s3InputDataSourcePath)
              .build();
      S3DataConfig outputDestination = S3DataConfig.builder()
              .path(s3DataDestinationPath)
              .build();

      BatchInferenceJobInput jobInput = BatchInferenceJobInput.builder()
              .s3DataSource(inputSource)
              .build();
      BatchInferenceJobOutput jobOutputLocation = BatchInferenceJobOutput.builder()
              .s3DataDestination(outputDestination)
              .build();

      // Optional code to build the User-Personalization specific item exploration config.
      HashMap<String, String> explorationConfig = new HashMap<>();

      explorationConfig.put("explorationWeight", explorationWeight);
      explorationConfig.put("explorationItemAgeCutOff", explorationItemAgeCutOff);

      BatchInferenceJobConfig jobConfig = BatchInferenceJobConfig.builder()
              .itemExplorationConfig(explorationConfig)
              .build();
      // End optional User-Personalization recipe specific code.

      CreateBatchInferenceJobRequest createBatchInferenceJobRequest = CreateBatchInferenceJobRequest.builder()
              .solutionVersionArn(solutionVersionArn)
              .jobInput(jobInput)
              .jobOutput(jobOutputLocation)
              .jobName(jobName)
              .filterArn(filterArn)
              .roleArn(roleArn)
              .batchInferenceJobConfig(jobConfig)   // Optional
              .build();

      batchInferenceJobArn = personalizeClient.createBatchInferenceJob(createBatchInferenceJobRequest)
              .batchInferenceJobArn();
      DescribeBatchInferenceJobRequest describeBatchInferenceJobRequest = DescribeBatchInferenceJobRequest.builder()
              .batchInferenceJobArn(batchInferenceJobArn)
              .build();

      long maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60;

      // wait until the batch inference job is complete.
      while (Instant.now().getEpochSecond() < maxTime) {

          BatchInferenceJob batchInferenceJob = personalizeClient
                  .describeBatchInferenceJob(describeBatchInferenceJobRequest)
                  .batchInferenceJob();

          status = batchInferenceJob.status();
          System.out.println("Batch inference job status: " + status);

          if (status.equals("ACTIVE") || status.equals("CREATE FAILED")) {
              break;
          }
          try {
              Thread.sleep(waitInMilliseconds);
          } catch (InterruptedException e) {
              System.out.println(e.getMessage());
          }
      }
      return batchInferenceJobArn;

  } catch (PersonalizeException e) {
      System.out.println(e.awsErrorDetails().errorMessage());
  }
  return "";
}
```

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

```
// Get service clients module and commands using ES6 syntax.
import { CreateBatchInferenceJobCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the batch inference job's parameters.

export const createBatchInferenceJobParam = {
  jobName: "JOB_NAME",
  jobInput: {
    s3DataSource: {
      path: "INPUT_PATH",
    },
  },
  jobOutput: {
    s3DataDestination: {
      path: "OUTPUT_PATH",
    },
  },
  roleArn: "ROLE_ARN",
  solutionVersionArn: "SOLUTION_VERSION_ARN",
  numResults: 20,
};

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

------

Processing the batch job might take a while to complete. You can check a job's status by calling [DescribeBatchInferenceJob](API_DescribeBatchInferenceJob.md) and passing a `batchRecommendationsJobArn` as the input parameter. You can also list all Amazon Personalize batch inference jobs in your AWS environment by calling [ListBatchInferenceJobs](API_ListBatchInferenceJobs.md).

### Creating a batch inference job that generates themes
<a name="batch-sdk-themes"></a>

To generate themes for similar items, you must use the Similar-Items recipe and your Items dataset must have a textual field and a column of item name data. For more information about recommendations with themes, see [Batch recommendations with themes from Content Generator](themed-batch-recommendations.md).

The following code creates a batch inference job that generates recommendations with themes. Leave the `batchInferenceJobMode` set to `"THEME_GENERATION"`. Replace `COLUMNN_NAME` with the name of the column that stores your item name data. 

```
import boto3

personalize_rec = boto3.client(service_name='personalize')

personalize_rec.create_batch_inference_job (
    solutionVersionArn = "Solution version ARN",
    jobName = "Batch job name",
    roleArn = "IAM service role ARN",
    filterArn = "Filter ARN",
    batchInferenceJobMode = "THEME_GENERATION",
    themeGenerationConfig = {
      "fieldsForThemeGeneration": {
          "itemName": "COLUMN_NAME"
      }
    },
    jobInput = 
       {"s3DataSource": {"path": "s3://amzn-s3-demo-bucket/<folder name>/<input JSON file name>.json"}},
    jobOutput = 
       {"s3DataDestination": {"path": "s3://amzn-s3-demo-bucket/<output folder name>/"}}
)
```

# Batch inference job output examples
<a name="batch-inference-job-output-examples"></a>

When you create a batch inference job, the job imports your batch input data from an Amazon S3 bucket, uses your solution version to generate *item recommendations*, and exports the recommendations to an Amazon S3 bucket in JSON format. 

The following sections list output file examples for batch inference jobs by recipe type. You can't get batch recommendations with the Trending-Now or Next-Best-Action recipes.

**Topics**
+ [USER\$1PERSONALIZATION recipes](#batch-inference-output-user-personalization)
+ [POPULAR\$1ITEMS recipes](#batch-inference-output-popular-items)
+ [PERSONALIZED\$1RANKING recipes](#batch-inference-output-personalized-ranking)
+ [RELATED\$1ITEMS recipes](#batch-inference-output-related-items)

## USER\$1PERSONALIZATION recipes
<a name="batch-inference-output-user-personalization"></a>

 The following is an example of the output JSON file for a USER\$1PERSONALIZATION recipe. 

```
{"input":{"userId":"4638"},"output":{"recommendedItems":["63992","115149","110102","148626","148888","31685","102445","69526","92535","143355","62374","7451","56171","122882","66097","91542","142488","139385","40583","71530","39292","111360","34048","47099","135137"],"scores":[0.0152238,0.0069081,0.0068222,0.006394,0.0059746,0.0055851,0.0049357,0.0044644,0.0042968,0.004015,0.0038805,0.0037476,0.0036563,0.0036178,0.00341,0.0033467,0.0033258,0.0032454,0.0032076,0.0031996,0.0029558,0.0029021,0.0029007,0.0028837,0.0028316]},"error":null}
{"input":{"userId":"663"},"output":{"recommendedItems":["368","377","25","780","1610","648","1270","6","165","1196","1097","300","1183","608","104","474","736","293","141","2987","1265","2716","223","733","2028"],"scores":[0.0406197,0.0372557,0.0254077,0.0151975,0.014991,0.0127175,0.0124547,0.0116712,0.0091098,0.0085492,0.0079035,0.0078995,0.0075598,0.0074876,0.0072006,0.0071775,0.0068923,0.0066552,0.0066232,0.0062504,0.0062386,0.0061121,0.0060942,0.0060781,0.0059263]},"error":null}
{"input":{"userId":"3384"},"output":{"recommendedItems":["597","21","223","2144","208","2424","594","595","920","104","520","367","2081","39","1035","2054","160","1370","48","1092","158","2671","500","474","1907"],"scores":[0.0241061,0.0119394,0.0118012,0.010662,0.0086972,0.0079428,0.0073218,0.0071438,0.0069602,0.0056961,0.0055999,0.005577,0.0054387,0.0051787,0.0051412,0.0050493,0.0047126,0.0045393,0.0042159,0.0042098,0.004205,0.0042029,0.0040778,0.0038897,0.0038809]},"error":null}
...
```

## POPULAR\$1ITEMS recipes
<a name="batch-inference-output-popular-items"></a>

 The following example shows the format of the output JSON file for the Popularity-Count recipe. You can't get batch recommendations with the Trending-Now recipe. 

```
{"input": {"userId": "12"}, "output": {"recommendedItems": ["105", "106", "441"]}}
{"input": {"userId": "105"}, "output": {"recommendedItems": ["105", "106", "441"]}}
{"input": {"userId": "41"}, "output": {"recommendedItems": ["105", "106", "441"]}}
...
```

## PERSONALIZED\$1RANKING recipes
<a name="batch-inference-output-personalized-ranking"></a>

 The following example shows the format of the output JSON file for a PERSONALIZED\$1RANKING recipe. 

```
{"input":{"userId":"891","itemList":["27","886","101"]},"output":{"recommendedItems":["27","101","886"],"scores":[0.48421,0.28133,0.23446]}}
{"input":{"userId":"445","itemList":["527","55","901"]},"output":{"recommendedItems":["901","527","55"],"scores":[0.46972,0.31011,0.22017]}}
{"input":{"userId":"71","itemList":["29","351","199"]},"output":{"recommendedItems":["351","29","199"],"scores":[0.68937,0.24829,0.06232]}}
...
```

## RELATED\$1ITEMS recipes
<a name="batch-inference-output-related-items"></a>

 The following example shows the format of the output JSON file for a RELATED\$1ITEMS recipe. 

```
{"input": {"itemId": "105"}, "output": {"recommendedItems": ["106", "107", "49"]}}
{"input": {"itemId": "106"}, "output": {"recommendedItems": ["105", "107", "49"]}}
{"input": {"itemId": "441"}, "output": {"recommendedItems": ["2", "442", "435"]}}
...
```

 The following example shows the format of the output JSON file for the Similar-Items recipe with themes. For more information about recommendations with themes, see [Batch recommendations with themes from Content Generator](themed-batch-recommendations.md). 

```
{"input":{"itemId":"40"},"output":{"recommendedItems":["36","50","44","22","21","29","3","1","2","39"],"theme":"Movies with a strong female lead","itemsThemeRelevanceScores":[0.19994527,0.183059963,0.17478035,0.1618133,0.1574806,0.15468733,0.1499242,0.14353688,0.13531424,0.10291852]}}
{"input":{"itemId":"43"},"output":{"recommendedItems":["50","21","36","3","17","2","39","1","10","5"],"theme":"The best movies of 1995","itemsThemeRelevanceScores":[0.184988,0.1795761,0.11143453,0.0989443,0.08258403,0.07952615,0.07115086,0.0621634,-0.138913,-0.188913]}}
...
```

# Getting batch user segments with custom resources
<a name="getting-user-segments"></a>

 To get *user segments*, you use a batch segment job. A *batch segment job* is a tool that imports your batch input data from an Amazon S3 bucket and uses your solution version trained with a USER\$1SEGMENTATION recipe to generate * user segments* for each row of input data.

Depending on the recipe, the input data is a list of items or item metadata attributes in JSON format. For item attributes, your input data can include expressions to create user segments based on multiple metadata attributes. A batch segment job exports user segments to an output Amazon S3 bucket. Each user segment is sorted in descending order based on the probability that each user will interact with the item in your input data. 

When generating user segments, Amazon Personalize considers data in datasets from bulk and individual imports:
+ For bulk data, Amazon Personalize generates segments using only the bulk data present at the last full solution version training. And it uses only bulk data that you imported with an import mode of FULL (replacing existing data).
+ For data from individual data import operations, Amazon Personalize generates user segments using the data present at the last full solution version training. To have newer records impact user segments, create a new solution version and then create a batch segment job.

Generating user segments works as follows:

1.  Prepare and upload your input data in JSON format to an Amazon S3 bucket. The format of your input data depends on the recipe you use and the job you are creating. See [Preparing input data for user segments](prepare-input-data-user-segment.md). 

1.  Create a separate location for your output data, either a different folder or a different Amazon S3 bucket. 

1.  Create a batch segment job. See [Getting user segments with a batch segment job](creating-batch-seg-job.md). 

1.  When the batch segment job is complete, retrieve the user segments from your output location in Amazon S3. 

**Topics**
+ [Guidelines and requirements for getting user segments](#batch-seg-permissions-req)
+ [Preparing input data for user segments](prepare-input-data-user-segment.md)
+ [Getting user segments with a batch segment job](creating-batch-seg-job.md)
+ [Batch segment job output format examples](batch-segment-job-output-examples.md)

## Guidelines and requirements for getting user segments
<a name="batch-seg-permissions-req"></a>

The following are guidelines and requirements for batch getting batch segments:
+  You must use a USER\$1SEGMENTATION recipe. 
+ Your Amazon Personalize IAM service role needs permission to read and add files to your Amazon S3 buckets. For information on granting permissions, see [Service role policy for batch workflows](granting-personalize-s3-access.md#role-policy-for-batch-workflows). For more information on bucket permissions, see [User policy examples](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-policies-s3.html) in the *Amazon Simple Storage Service Developer Guide*. 

   If you use AWS Key Management Service (AWS KMS) for encryption, you must grant Amazon Personalize and your Amazon Personalize IAM service role permission to use your key. For more information, see [Giving Amazon Personalize permission to use your AWS KMS key](granting-personalize-key-access.md).
+  You must create a custom solution and solution version before you create a batch inference job. However, you don't need to create an Amazon Personalize campaign. If you created a Domain dataset group, you can still create custom resources. 
+  Your input data must be formatted as described in [Preparing input data for user segments](prepare-input-data-user-segment.md). 
+  If you use the Item-Attribute-Affinity recipe, the attributes in your input data can't include unstructured textual item metadata, such as a product description. 
+ If you use a filter with placeholder parameters, you must include the values for the parameters in your input data in a `filterValues` object. For more information, see [Providing filter values in your input JSON](filter-batch.md#providing-filter-values). 
+ We recommend that you use a different location for your output data (either a folder or a different Amazon S3 bucket) than your input data. 

# Preparing input data for user segments
<a name="prepare-input-data-user-segment"></a>

Batch segment jobs use a solution version to make user segments based on data that you provide in an input JSON file. Before you can get user segments, you must prepare and upload your JSON file to an Amazon S3 bucket. We recommend that you create an output folder in your Amazon S3 bucket or use a separate output Amazon S3 bucket. You can then run multiple batch inference jobs using the same input data location. 

 If you use a filter with placeholder parameters, such as `$GENRE`, you must provide the values for the parameters in a `filterValues` object in your input JSON. For more information, see [Providing filter values in your input JSON](filter-batch.md#providing-filter-values). 

**To prepare and import data**

1. Format your batch input data depending on the recipe your solution uses. Separate input data element with a new line. Your input data is either a list of itemIds (Item-Affinity) or item attributes (Item-Attribute-Affinity).
   + For item attributes, input data can include logical expressions with the `AND` operator to get users for multiple items or attributes per query. For more information, see [Specifying item attributes for the Item-Attribute-Affinity recipe](#specifying-item-attributes). 
   +  For item attributes, use the `\` character to escape any special characters and single or double quotes in your input data. 
   + For input data examples for both recipes, see [Batch segment job input and output JSON examples](#batch-segment-job-json-examples).

1.  Upload your input JSON to an input folder in your Amazon S3 bucket. For more information, see [Uploading files and folders by using drag and drop](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/upload-objects.html) in the *Amazon Simple Storage Service User Guide* 

1.  Create a separate location for your output data, either a folder or a different Amazon S3 bucket. By creating a separate location for the output JSON, you can run multiple batch segment jobs with the same input data location.

 After you have prepared your input data and uploaded it to an Amazon S3 bucket, you are ready to generate user segments with a batch segment job. For more information, see [Getting user segments with a batch segment job](creating-batch-seg-job.md). 

**Topics**
+ [Specifying item attributes for the Item-Attribute-Affinity recipe](#specifying-item-attributes)
+ [Batch segment job input and output JSON examples](#batch-segment-job-json-examples)

## Specifying item attributes for the Item-Attribute-Affinity recipe
<a name="specifying-item-attributes"></a>

If you use the Item-Attribute-Affinity recipe, your input data is a list of item attributes. You can mix different columns of metadata. For example one row might be a numerical column and the next might be a categorical column. You can't use unstructured textual item metadata as an item attribute. 

Your input item metadata can include logical expressions with the `AND` operator to get a user segment for multiple attributes. For example, a line of your input data might be `{"itemAttributes": "ITEMS.genres = \"Comedy\" AND ITEMS.genres = \"Action\""}` or `{"itemAttributes": "ITEMS.genres = "\Comedy\" AND ITEMS.audience = "\teen\""}`.

When you combine two attributes with the `AND` operator, you create a user segment with users who are more likely to interact with items that have both attributes based on the users interactions history. Unlike filter expressions (which use the `IN` operator for string equality), batch segment input expressions support only the `=` symbol for equality for string matching. 

## Batch segment job input and output JSON examples
<a name="batch-segment-job-json-examples"></a>

For a batch segment job, your input data must be either a list of itemIds (Item-Affinity recipe) or item attributes (Item-Attribute-Affinity). Each line of input data is a separate inference query. Each user segment is sorted in descending order based on the probability that each user will interact with items in your inventory.

 If you use a filter with placeholder parameters, such as `$GENRE`, you must provide the values for the parameters in a `filterValues` object in your input JSON. For more information, see [Providing filter values in your input JSON](filter-batch.md#providing-filter-values). 

The following are correctly formatted JSON input and output examples for batch segment jobs organized by recipe.

**Item-Affinity**

------
#### [ Input ]

Your input data can have a maximum of 500 items. Separate each `itemId` with a new line as follows.

```
{"itemId": "105"}
{"itemId": "106"}
{"itemId": "441"}
...
```

------
#### [ Output ]

```
{"input": {"itemId": "105"}, "output": {"recommendedUsers": ["106", "107", "49"]}}
{"input": {"itemId": "106"}, "output": {"recommendedUsers": ["105", "107", "49"]}}
{"input": {"itemId": "441"}, "output": {"recommendedUsers": ["2", "442", "435"]}}
...
```

------

**Item-Attribute-Affinity**

------
#### [ Input ]

Your input data can have a maximum of 10 queries, where each query is one or more non-textual item attributes. Separate each attribute or attribute expression with a new line as follows.

```
{"itemAttributes": "ITEMS.genres = \"Comedy\" AND ITEMS.genres = \"Action\""}
{"itemAttributes": "ITEMS.genres = \"Comedy\""}
{"itemAttributes": "ITEMS.genres = \"Horror\" AND ITEMS.genres = \"Action\""}
...
```

------
#### [ Output ]

```
{"itemAttributes": "ITEMS.genres = \"Comedy\" AND ITEMS.genres = \"Action\"", "output": {"recommendedUsers": ["25", "78", "108"]}}
{"itemAttributes": "ITEMS.genres = \"Adventure\"", "output": {"recommendedUsers": ["87", "31", "129"]}}
{"itemAttributes": "ITEMS.genres = \"Horror\" AND ITEMS.genres = \"Action\"", "output": {"recommendedUsers": ["8", "442", "435"]}}
...
```

------

# Getting user segments with a batch segment job
<a name="creating-batch-seg-job"></a>

 If you used a USER\$1SEGMENTATION recipe, you can create batch segment jobs to get user segments with your solution version. Each user segment is sorted in descending order based on the probability that each user will interact with items in your inventory. Depending on the recipe, your input data must be a list of items ([Item-Affinity recipe](item-affinity-recipe.md)) or item attributes ([Item-Attribute-Affinity recipe](item-attribute-affinity-recipe.md)) in JSON format. You can create a batch segment job with the Amazon Personalize console, the AWS Command Line Interface (AWS CLI), or AWS SDKs. 

 When you create a batch segment job, you specify the Amazon S3 paths to your input and output locations. Amazon S3 is prefix based. If you provide a prefix for the input data location, Amazon Personalize uses all files matching that prefix as input data. For example, if you provide `s3://amzn-s3-demo-bucket/folderName` and your bucket also has a folder with a path of `s3://amzn-s3-demo-bucket/folderName_test`, Amazon Personalize uses all files in both folders as input data. To use only the files within a specific folder as input data, end the Amazon S3 path with a prefix delimiter, such as `/`: `s3://amzn-s3-demo-bucket/folderName/` For more information about how Amazon S3 organizes objects, see [Organizing, listing, and working with your objects](https://docs.aws.amazon.com/AmazonS3/latest/userguide/organizing-objects.html). 

**Topics**
+ [Creating a batch segment job (console)](#batch-segment-console)
+ [Creating a batch segment job (AWS CLI)](#batch-segment-cli)
+ [Creating a batch segment job (AWS SDKs)](#batch-segment-sdk)

## Creating a batch segment job (console)
<a name="batch-segment-console"></a>

 After you have completed [Preparing input data for batch recommendations](batch-data-upload.md), you are ready to create a batch segment job. This procedure assumes that you have already created a solution and a solution version (trained model) with a USER\$1SEGEMENTATION recipe.

**To get create a batch segment job (console)**

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

1. On the **Datasets group** page, choose your dataset group.

1. Choose **batch segment jobs** in the navigation pane, then choose **Create batch segment job**.

1. In **batch segment job details**, for **Batch segment job name**, specify a name for your batch segment job.

1. For **Solution**, choose the solution and then choose the **Solution version ID** that you want to use to generate the recommendations. You can create batch segment jobs only if you used a USER\$1SEGEMENTATION recipe. 

1. For **Number of users**, optionally specify the number of users Amazon Personalize generates for each user segment. The default is 25. The maximum is 5 million.

1.  For **Input source**, specify the Amazon S3 path to your input file or use the **Browse S3** to choose your Amazon S3 bucket.

   Use the following syntax: **s3://amzn-s3-demo-bucket/<folder name>/<input JSON file name>.json**

    Your input data must be in the correct format for the recipe your solution uses. For input data examples see [Batch segment job input and output JSON examples](prepare-input-data-user-segment.md#batch-segment-job-json-examples). 

1. For **Output destination**, specify the path to your output location or use the **Browse S3** to choose your Amazon S3 bucket. We recommend using a different location for your output data (either a folder or a different Amazon S3 bucket).

    Use the following syntax: **s3://amzn-s3-demo-bucket/<output folder name>/** 

1. For **IAM role**, choose one of the following:
   +  Choose **Create and use new service role** and enter the **Service role name** to create a new role, or
   +  If you've already created a role with the correct permissions, choose **Use an existing service role** and choose the IAM role. 

    The role you use must have read and write access to your input and output Amazon S3 buckets respectively.

1.  For **Filter configuration** optionally choose a filter to apply a filter to the user segments. If your filter uses placeholder parameters, make sure the values for the parameters are included in your input JSON. For more information, see [Providing filter values in your input JSON](filter-batch.md#providing-filter-values). 

1. For **Tags**, optionally add any tags. For more information about tagging Amazon Personalize resources, see [Tagging Amazon Personalize resources](tagging-resources.md).

1.  Choose **Create batch segment job**. Batch segment job creation starts and the **Batch segment jobs** page appears with the **Batch segment job detail** section displayed.

1.  When the batch segment job's status changes to **Active**, you can retrieve the job's output from the designated output Amazon S3 bucket. The output file's name will be of the format `input-name.out`. 

## Creating a batch segment job (AWS CLI)
<a name="batch-segment-cli"></a>

After you have completed [Preparing input data for batch recommendations](batch-data-upload.md), you are ready to create a batch segment job using the following `create-batch-segment-job` code. Specify a job name, replace `Solution version ARN` with the Amazon Resource Name (ARN) of your solution version, and replace the `IAM service role ARN` with the ARN of the IAM service role you created for Amazon Personalize during set up. This role must have read and write access to your input and output Amazon S3 buckets respectively. For `num-results` specify the number of users you want Amazon Personalize to predict for each line of input data. The default is 25. The maximum is 5 million. Optionally provide a `filter-arn` to filter user segments. If your filter uses placeholder parameters, make sure the values for the parameters are included in your input JSON. For more information, see [Filtering batch recommendations and user segments (custom resources)](filter-batch.md). 

Replace `S3 input path` and `S3 output path` with the Amazon S3 path to your input file and output locations. We recommend using a different location for your output data (either a folder or a different Amazon S3 bucket). Use the following syntax for input and output locations: **s3://amzn-s3-demo-bucket/<folder name>/<input JSON file name>.json** and **s3://amzn-s3-demo-bucket/<output folder name>/**. 

```
aws personalize create-batch-segment-job \
                --job-name Job name \
                --solution-version-arn Solution version ARN \
                --num-results The number of predicted users \
                --filter-arn Filter ARN \
                --job-input s3DataSource={path=s3://S3 input path} \
                --job-output s3DataDestination={path=s3://S3 output path} \
                --role-arn IAM service role ARN
{
   "batchSegmentJobArn": "arn:aws:personalize:us-west-2:acct-id:batch-segment-job/batchSegmentJobName"
}
```

## Creating a batch segment job (AWS SDKs)
<a name="batch-segment-sdk"></a>

After you have completed [Preparing input data for batch recommendations](batch-data-upload.md), you are ready to create a batch segment job with the `CreateBatchSegmentJob` operation. The following code shows how to create a batch segment job. Give the job a name, specify the Amazon Resource Name (ARN) of the solution version to use, specify the ARN for your Amazon Personalize IAM role, and specify the Amazon S3 path to your input file and output locations. Your IAM service role must have read and write access to your input and output Amazon S3 buckets respectively. 

We recommend using a different location for your output data (either a folder or a different Amazon S3 bucket). Use the following syntax for input and output locations: **s3://amzn-s3-demo-bucket/<folder name>/<input JSON file name>.json** and **s3://amzn-s3-demo-bucket/<output folder name>/**. 

 For `numResults`, specify the number of users you want Amazon Personalize to predict for each line of input data. The default is 25. The maximum is 5 million. Optionally provide a `filterArn` to filter user segments. If your filter uses placeholder parameters, make sure the values for the parameters are included in your input JSON. For more information, see [Filtering batch recommendations and user segments (custom resources)](filter-batch.md). 

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

```
import boto3

personalize_rec = boto3.client(service_name='personalize')

personalize_rec.create_batch_segment_job (
    solutionVersionArn = "Solution version ARN",
    jobName = "Job name",
    numResults = 25,
    filterArn = "Filter ARN",
    roleArn = "IAM service role ARN",
    jobInput = 
       {"s3DataSource": {"path": "s3://amzn-s3-demo-bucket/<folder name>/<input JSON file name>.json"}},
    jobOutput = 
       {"s3DataDestination": {"path": "s3://amzn-s3-demo-bucket/<output folder name>/"}}
)
```

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

```
public static String createBatchSegmentJob(PersonalizeClient personalizeClient,
                                                        String solutionVersionArn,
                                                        String jobName,
                                                        String filterArn,
                                                        int numResults,
                                                        String s3InputDataSourcePath,
                                                        String s3DataDestinationPath,
                                                        String roleArn,
                                                        String explorationWeight,
                                                        String explorationItemAgeCutOff) {

  long waitInMilliseconds = 60 * 1000;
  String status;
  String batchSegmentJobArn;

  try {
      // Set up data input and output parameters.
      S3DataConfig inputSource = S3DataConfig.builder()
              .path(s3InputDataSourcePath)
              .build();
      S3DataConfig outputDestination = S3DataConfig.builder()
              .path(s3DataDestinationPath)
              .build();

      BatchSegmentJobInput jobInput = BatchSegmentJobInput.builder()
              .s3DataSource(inputSource)
              .build();
      BatchSegmentJobOutput jobOutputLocation = BatchSegmentJobOutput.builder()
              .s3DataDestination(outputDestination)
              .build();


      CreateBatchSegmentJobRequest createBatchSegmentJobRequest = CreateBatchSegmentJobRequest.builder()
              .solutionVersionArn(solutionVersionArn)
              .filterArn(filterArn)
              .jobInput(jobInput)
              .jobOutput(jobOutputLocation)
              .jobName(jobName)
              .numResults(numResults)
              .roleArn(roleArn)
              .build();

      batchSegmentJobArn = personalizeClient.createBatchSegmentJob(createBatchSegmentJobRequest)
              .batchSegmentJobArn();
      DescribeBatchSegmentJobRequest describeBatchSegmentJobRequest = DescribeBatchSegmentJobRequest.builder()
              .batchSegmentJobArn(batchSegmentJobArn)
              .build();

      long maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60;

      // wait until the batch segment job is complete.
      while (Instant.now().getEpochSecond() < maxTime) {

          BatchSegmentJob batchSegmentJob = personalizeClient
                  .describeBatchSegmentJob(describeBatchSegmentJobRequest)
                  .batchSegmentJob();

          status = batchSegmentJob.status();
          System.out.println("batch segment job status: " + status);

          if (status.equals("ACTIVE") || status.equals("CREATE FAILED")) {
              break;
          }
          try {
              Thread.sleep(waitInMilliseconds);
          } catch (InterruptedException e) {
              System.out.println(e.getMessage());
          }
      }
      return batchSegmentJobArn;

  } catch (PersonalizeException e) {
      System.out.println(e.awsErrorDetails().errorMessage());
  }
  return "";
}
```

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

```
// Get service clients module and commands using ES6 syntax.
import { CreateBatchSegmentJobCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the batch segment job's parameters.

export const createBatchSegmentJobParam = {
  jobName: "NAME",
  jobInput: {
    s3DataSource: {
      path: "INPUT_PATH",
    },
  },
  jobOutput: {
    s3DataDestination: {
      path: "OUTPUT_PATH",
    },
  },
  roleArn: "ROLE_ARN",
  solutionVersionArn: "SOLUTION_VERSION_ARN",
  numResults: 20,
};

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

------

Processing the batch job might take a while to complete. You can check a job's status by calling [DescribeBatchSegmentJob](API_DescribeBatchSegmentJob.md) and passing a `batchSegmentJobArn` as the input parameter. You can also list all Amazon Personalize batch segment jobs in your AWS environment by calling [ListBatchSegmentJobs](API_ListBatchSegmentJobs.md). 

# Batch segment job output format examples
<a name="batch-segment-job-output-examples"></a>

A batch segment job imports your batch input data from an Amazon S3 bucket, uses your solution version trained with a USER\$1SEGMENTATION recipe to generate *user segments*, and exports the segments to an Amazon S3 bucket.

The following sections list JSON output examples for batch segment jobs by recipe.

**Topics**
+ [Item-Affinity](#batch-segment-output-item-affinity)
+ [Item-Attribute-Affinity](#batch-segment-output-item-attribute-affinity)

## Item-Affinity
<a name="batch-segment-output-item-affinity"></a>

 The following example shows the format of the output JSON file for the Item-Affinity recipe. 

```
{"input": {"itemId": "105"}, "output": {"recommendedUsers": ["106", "107", "49"]}}
{"input": {"itemId": "106"}, "output": {"recommendedUsers": ["105", "107", "49"]}}
{"input": {"itemId": "441"}, "output": {"recommendedUsers": ["2", "442", "435"]}}
...
```

## Item-Attribute-Affinity
<a name="batch-segment-output-item-attribute-affinity"></a>

 The following example shows the format of the output JSON file for the Item-Attribute-Affinity recipe. 

```
{"itemAttributes": "ITEMS.genres = \"Comedy\" AND ITEMS.genres = \"Action\"", "output": {"recommendedUsers": ["25", "78", "108"]}}
{"itemAttributes": "ITEMS.genres = \"Adventure\"", "output": {"recommendedUsers": ["87", "31", "129"]}}
{"itemAttributes": "ITEMS.genres = \"Horror\" AND ITEMS.genres = \"Action\"", "output": {"recommendedUsers": ["8", "442", "435"]}}
...
```