Filtering real-time recommendations - Amazon Personalize

Filtering real-time recommendations

You can filter real-time recommendations with the Amazon Personalize console, AWS Command Line Interface (AWS CLI), or the AWS SDKs.

When you get personalized item recommendations or similar items, you can specify a promotion in your request. A promotion uses a filter to define additional business rules that apply to a configurable subset of recommended items. For more information, see Promoting items in real-time recommendations.

Filtering real-time recommendations (console)

To filter real-time recommendations using the console, create a filter and then apply it to a recommendation request.

Note

To filter recommendations using a filter with parameters and a campaign deployed before November 10, 2020, you must redeploy the campaign by using the UpdateCampaign operation or create a new campaign.

Creating a filter (console)

To create a filter in the console, choose the dataset group that contains the campaign or recommender you want to use to get filtered recommendations. Then provide a filter name and a filter expression.

To create a filter (console)
  1. Open the Amazon Personalize console at https://console.aws.amazon.com/personalize/home and sign into your account.

  2. Choose the dataset group that contains the campaign or recommender that you want to use to get filtered recommendations.

  3. In the navigation pane, choose Filters and then choose Create new filter. The Create filter page displays.

    Depicts the create filter page with filter name and expression fields.
  4. For Filter name, enter a name for your filter. You will choose the filter by this name when you apply it to a recommendation request.

  5. For Expression, choose either Build expression or Add expression manually and build or insert your expression:

    • To use the expression builder, choose Build expression. The expression builder provides structure, fields, and guidelines for building correctly formatted filter expressions. For more information, see Using the filter expression builder.

    • To input your own expression, choose Add expression manually. For more information, see Filter expression elements.

  6. Choose Finish. The filter's overview page shows the filter’s Amazon Resource Name (ARN), status, and full filter expression. To delete the filter, choose Delete. For information about finding and deleting filters after you have left the overview page, see Deleting a filter (console).

    Depicts the filter details page with the filter's ARN and expression.

Applying a filter (console)

To apply a filter, in Test recommender (for recommenders) or Test campaign results (for custom campaigns), choose the filter and enter any filter parameter values. Then get recommendations for a user.

Important

For filter expressions that use an INCLUDE element, you must provide values for all parameters that are defined in the expression. For filters with expressions that use an EXCLUDE element, you can omit the filter-values. In this case, Amazon Personalize doesn't use that portion of the expression to filter recommendations.

To apply a filter (console)
  1. Open the Amazon Personalize console at https://console.aws.amazon.com/personalize/home and sign into your account.

  2. Choose the dataset group that contains the campaign or recommender that you want to use to get filtered recommendations.

  3. Depending on your dataset group type or resource type, do either of the following:

    1. For a Domain dataset group, in the navigation pane choose Recommenders.

    2. For a Custom dataset group or custom resources, in the navigation pane choose Custom resources then Campaigns.

  4. On the Recommenders or Campaigns page, choose the target recommender or campaign.

  5. For comparison, start by getting recommendations without applying a filter. Under Test recommender / Test campaign results, enter the ID of a user that you want to get recommendations for, or the ID of the item for related items, and choose Get recommendations. A table containing the top recommendations appears.

    Depicts recommendation results without applying a filter.
  6. From the Filter name menu, choose the filter that you created. If your filter has any placeholder parameters, the associated fields for each parameter appear.

  7. If you're using 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.

  8. Using the same User ID or Item ID as in the earlier step, choose Get recommendations. The recommendations table appears.

    Depicts recommendation results with a filter applied.

    For example, if the user already bought a recommended item, the filter removes it from the recommendation list. In this example, items 2657, 2985 were replaced by the most suitable items that the user didn't buy (items 2641 and 1573).

Using the filter expression builder

The Expression builder on the Create filter page provides structure, fields, and guidelines for building correctly formatted filter.

Depicts the fields of the expression builder on the create filter page.

To build a filter expression:

  • Use the Type, Action, Property, Operator, and Value fields to create an expression.

    For the Value, enter a fixed value or, to set filter criteria when you get recommendations, enter $ + a parameter name. For example, $GENRES. When you get recommendations, you'll supply the value or values to filter by. In this example, you would provide a genre or list of genres when you get recommendations.

    Separate multiple non-parameter values with a comma. You cannot add comma-separated parameters to a filter.

    Note

    After you choose a Property (in dataset.field format), the Property value for any succeeding rows chained by AND or OR conditions must use the same dataset.

  • Use the + and X buttons to add or delete a row from your expression. You can't delete the first row.

  • For new rows, use the AND, IF, or OR operators on the AND menu to create a chain of conditions.

    For IF conditions:

    • Each expression can contain only one IF item. If you remove an IF condition, the Expression builder removes any AND conditions following it.

    • You can use IF conditions only for expressions that filter by the CurrentUser.

  • Choose the Add expression button to add an additional filter expression for more precise filtering. Each expression is first evaluated independently and the result is a union of the two results.

    Note

    To create a filter that uses both Item and Item interaction datasets, or Action and Action interactions datasets, you must use multiple expressions.

Expression builder example

The following example shows how to build a filter that excludes items with a genre that you specify when you get recommendations (note the $GENRES placeholder parameter). The filter also excludes items with a DOWNLOAD_COUNT of more than 200, but only if the current user's age is greater than 17.

Shows how to use expression builder to build an example filter expression.

Deleting a filter (console)

Deleting a filter removes the filter from the list of filters for a dataset group.

Important

You can't delete a filter while a batch inference job is in progress.

To delete a filter (console)
  1. Open the Amazon Personalize console at https://console.aws.amazon.com/personalize/home and sign into your account.

  2. From the Dataset groups list, choose the dataset group that contains the filter that you want to delete.

  3. In the navigation pane, choose Filters.

  4. From the list of filters, choose the filter that you want to delete and choose View Details. The filter details page appears.

  5. Choose Delete and confirm the deletion in the confirmation dialog box.

Filtering real-time recommendations (AWS CLI)

To filter recommendations using the AWS CLI, you create a filter and then apply it by specifying the filter ARN in a GetRecommendations or GetPersonalizedRanking request.

Important

To filter recommendations using a filter with parameters and a campaign you deployed before November 10, 2020, you must re-deploy the campaign by using the UpdateCampaign call or create a new campaign.

Creating a filter (AWS CLI)

Use the following create-filter operation to create a filter and specify the filter expression.

Replace the Filter name with the name of the filter, and the Dataset group ARN with the Amazon Resource Name (ARN) of the dataset group. Replace the sample filter-expression with your own filter expression.

aws personalize create-filter \ --name Filter name \ --dataset-group-arn dataset group arn \ --filter-expression "EXCLUDE ItemID WHERE Items.CATEGORY IN (\"$CATEGORY\")"

If successful, the filter ARN is displayed. Record it for later use. To verify that the filter is active, use the DescribeFilter operation before you use the filter.

For more information about the API, see CreateFilter. For more information about filter expressions, including examples, see Filter expression structure and elements.

Applying a filter (AWS CLI)

When you use the get-recommendations, get-action-recommendations or get-personalized-ranking operations, you apply a filter by passing the filter-arn and any filter values as parameters.

The following is an example of the get-recommendations operation. Replace Campaign ARN with the Amazon Resource Name (ARN) of your campaign User ID with the ID of the user that you are getting recommendations for, and Filter ARN with the ARN of your filter. If you're getting recommendations from a recommender instead of a campaign, use recommender-arn instead of --campaign-arn and provide the ARN for the recommender.

If your expression has any parameters, include the filter-values object. 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 "Comedy", as the value. Separate multiple values with a comma. For example, "\"comedy\",\"drama\",\"horror"\".

Important

For filter expressions that use an INCLUDE element to include items, you must provide values for all parameters that are defined in the expression. For filters with expressions that use an EXCLUDE element to exclude items, you can omit the filter-values. In this case, Amazon Personalize doesn't use that portion of the expression to filter recommendations.

aws personalize-runtime get-recommendations \ --campaign-arn Campaign ARN \ --user-id User ID \ --filter-arn Filter ARN \ --filter-values '{ "Parameter name": "\"value\"", "Parameter name": "\"value1\",\"value2\",\"value3\"" }'

Deleting a filter (AWS CLI)

Use the following delete-filter operation to delete a filter. Replace filter ARN with the ARN of the filter.

aws personalize delete-filter --filter-arn Filter ARN

Filtering real-time recommendations (AWS SDKs)

To filter recommendations using the AWS SDKs, you create a filter and then apply it by specifying the filter ARN in a GetRecommendations or GetPersonalizedRanking request.

Important

To filter recommendations using a filter with parameters and a campaign you deployed before November 10, 2020, you must re-deploy the campaign by using the UpdateCampaign call or create a new campaign.

Creating a filter (AWS SDKs)

Create a new filter with the CreateFilter operation. The following code shows how to create a filter. Specify the filter name, Amazon Resource Name (ARN) of your dataset group, and provide your filter expression.

SDK for Python (Boto3)
import boto3 personalize = boto3.client('personalize') response = personalize.create_filter( name = 'Filter Name', datasetGroupArn = 'Dataset Group ARN', filterExpression = 'EXCLUDE ItemID WHERE Items.CATEGORY IN ($CATEGORY)' ) filter_arn = response["filterArn"] print("Filter ARN: " + filter_arn)
SDK for Java 2.x
public static String createFilter(PersonalizeClient personalizeClient, String filterName, String datasetGroupArn, String filterExpression) { try { CreateFilterRequest request = CreateFilterRequest.builder() .name(filterName) .datasetGroupArn(datasetGroupArn) .filterExpression(filterExpression) .build(); return personalizeClient.createFilter(request).filterArn(); } catch(PersonalizeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; }
SDK for JavaScript v3
// Get service clients module and commands using ES6 syntax. import { CreateFilterCommand } from "@aws-sdk/client-personalize"; import { personalizeClient } from "./libs/personalizeClients.js"; // Or, create the client here. // const personalizeClient = new PersonalizeClient({ region: "REGION"}); // Set the filter's parameters. export const createFilterParam = { datasetGroupArn: 'DATASET_GROUP_ARN', /* required */ name: 'NAME', /* required */ filterExpression: 'FILTER_EXPRESSION' /*required */ } export const run = async () => { try { const response = await personalizeClient.send(new CreateFilterCommand(createFilterParam)); console.log("Success", response); return response; // For unit tests. } catch (err) { console.log("Error", err); } }; run();

Record the filter ARN for later use. To verify that the filter is active, use the DescribeFilter operation before using the filter. For more information about the API, see CreateFilter. For more information about filter expressions, including examples, see Filter expression structure and elements.

Applying a filter (AWS SDKs)

When you use the GetRecommendations, GetActionRecommendations, or GetPersonalizedRanking operations, apply a filter by passing a filterArn and any filter values as parameters.

The following code shows how to get filtered Amazon Personalize item recommendations for a user. Specify the ID of the user you want to get recommendations for, the Amazon Resource Name (ARN) of your campaign, and the ARN of your filter. If you're getting recommendations from a recommender instead of a campaign, use recommenderArn instead of campaignArn and provide the ARN for the recommender.

For filterValues, for each optional parameter in your filter expression, provide the parameter name (case sensitive) and the value or values. For example, if your filter expression has a $GENRES parameter, provide "GENRES" as the key, and a genre or genres, such as "\"Comedy"\", as the value. For multiple values, separate each value with a comma. For example, "\"comedy\",\"drama\",\"horror\"".

Important

For filter expressions that use an INCLUDE element to include items, you must provide values for all parameters that are defined in the expression. For filters with expressions that use an EXCLUDE element to exclude items, you can omit the filter-values. In this case, Amazon Personalize doesn't use that portion of the expression to filter recommendations.

SDK for Python (Boto3)
import boto3 personalize_runtime = boto3.client("personalize-runtime") response = personalize_runtime.get_recommendations( campaignArn = "Campaign ARN", userId = "User ID", filterArn = "Filter ARN", filterValues = { "Parameter name": "\"value1\"", "Parameter name": "\"value1\",\"value2\",\"value3\"" .... } )
SDK for Java 2.x

The following example uses two parameters, one with two values and one with one value. Depending on your filter expression, modify the code to add or remove parameterName and parameterValue fields.

public static void getFilteredRecs(PersonalizeRuntimeClient personalizeRuntimeClient, String campaignArn, String userId, String filterArn, String parameter1Name, String parameter1Value1, String parameter1Value2, String parameter2Name, String parameter2Value){ try { Map<String, String> filterValues = new HashMap<>(); filterValues.put(parameter1Name, String.format("\"%1$s\",\"%2$s\"", parameter1Value1, parameter1Value2)); filterValues.put(parameter2Name, String.format("\"%1$s\"", parameter2Value)); GetRecommendationsRequest recommendationsRequest = GetRecommendationsRequest.builder() .campaignArn(campaignArn) .numResults(20) .userId(userId) .filterArn(filterArn) .filterValues(filterValues) .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 (PersonalizeRuntimeException 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 recommendation request parameters. export const getRecommendationsParam = { campaignArn: 'CAMPAIGN_ARN', /* required */ userId: 'USER_ID', /* required */ numResults: 15, /* optional */ filterArn: 'FILTER_ARN', /* required to filter recommendations */ filterValues: { "PROPERTY": "\"VALUE\"" /* Only required if your filter has a placeholder parameter */ } } 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();

Deleting a filter (AWS Python SDK)

Use the following delete_filter method to delete a filter. Replace filter ARN with the ARN of the filter.

import boto3 personalize = boto3.client("personalize") response = personalize.delete_filter( filterArn = "filter ARN" )