Sometimes a recommendation returns multiple items with the same property. It can make the final output less useful.
For example, if your popular right now recommendation mostly returns items from the mobile phones category, customers may see too many similar results. Instead, you may want to show a more varied list with only one item per category.
You can use the same approach for other properties, too. For example, if a recommendation returns the same shoe model in multiple sizes, you can filter the output by a parent product ID and show the model only once.
Use Jinja post-filtering to keep only one occurrence of a selected item property.
Example
This example keeps only one item per category_level_1. To use a different property, replace the category_level_1 with the property you want to filter by.
{% set reco = recommendations('RecoID', 100) %}
{% set shown_values = [] %}
{% set items = [] %}
{% for item in reco %}
{% if item.category_level_1 not in shown_values %}
{%- append item.category_level_1 to shown_values -%}
{%- append item to items -%}
{% endif %}
{% endfor %}
{% for item in items %}
{{ item.title }} - {{ item.category_level_1 }}
{% endfor %}What this code does
The code:
Gets up to 100 items from the recommendation.
Loops through each item in the result.
- Checks whether the value of category_level_1 has already appeared.
Keeps the first item for each unique category.
Skips all later items with the same category.
Result
If the recommendation returns:
- 5 items from Mobile Phones
- 6 items from TVs
The filtered output keeps only:
- 1 item from Mobile Phones
- 1 item from TVs
This gives you a more diverse set of recommendations.
Use this with other properties
You can use the same logic with any item property that should appear only once in the final output, such as:
- category_level_1
- brand
- parent_id
any other custom item property