> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Personalizing search facets

> Learn how to personalize search facets with Advanced Personalization and InstantSearch

export const Filter = () => <Tooltip tip="A filter is a condition that limits which records Algolia returns. Filters often use one or more facet-value pairs, such as brand:Apple AND color:red. You can also filter by numeric values, dates, tags, booleans, or geographic constraints." cta="Filtering" href="/doc/guides/managing-results/refine-results/faceting">
    filter
  </Tooltip>;

export const FacetValuePair = () => <Tooltip tip="A constraint that combines a facet name and one of its values, written as facetName:facetValue. For example, brand:Apple or color:red.">
    facet-value pair
  </Tooltip>;

export const Affinity = () => <Tooltip tip="Affinity is a preference score that Algolia calculates for each user based on their behavior. It reflects how likely a user is to prefer a specific facet-value pair and helps personalize their search results." cta="Affinity" href="/doc/guides/personalization/advanced-personalization/configure/prerequisites/consider-requirements-limits#affinities">
    affinity
  </Tooltip>;

[Facets](/doc/guides/managing-results/refine-results/faceting#whats-a-facet) let your users narrow down search results by using a specific category or <Filter />.
Using Advanced Personalization, you can personalize search facets to suit each user's preferences.
This approach lets users refine their search,
focusing on results that align closely with their interests.

This guide shows how to use the [Advanced Personalization](/doc/guides/personalization/advanced-personalization/what-is-advanced-personalization/in-depth/how-does-advanced-personalization-work) feature and [InstantSearch](/doc/guides/building-search-ui/what-is-instantsearch/react) to personalize search facets.

<Callout icon="credit-card" color="#c084fc">
  This feature isn't available on every plan.
  Refer to your [pricing plan](https://www.algolia.com/pricing) to see if it's included.
</Callout>

## Before you begin

This guide assumes that you're familiar with [React InstantSearch](/doc/guides/building-search-ui/getting-started/react) and [fetching a user profile](/doc/guides/personalization/advanced-personalization/implement/guides/fetching-a-user-profile#fetch-a-user-profile).

It also assumes that you've [configured Advanced Personalization](/doc/guides/personalization/advanced-personalization/configure#set-up-personalization).

## Retrieve facet values matching the user profile

Start by creating the `usePersonalizedItems` function.
This function helps extract a list of facets from the search response that are most relevant to the user.

```js JavaScript icon=code theme={"system"}
import { usePersonalizationProfile } from "./PersonalizationProfileContext";

function usePersonalizedItems(attribute) {
  const { affinities } = usePersonalizationProfile();
  const affinitiesMatchingAttribute = affinities.filter(
    (affinity) => affinity.name === attribute
  );
  const affinityScoreByValue = affinitiesMatchingAttribute.reduce(
    (acc, affinity) => {
      acc[affinity.value] = affinity.score;
      return acc;
    },
    {}
  );

  return {
    getPersonalizedItems: (items) => {
      return items
        .filter((item) => Boolean(affinityScoreByValue[item.value]))
        .map((item) => ({
          ...item,
          affinityScore: affinityScoreByValue[item.value],
        }))
        .sort((a, b) => b.affinityScore - a.affinityScore);
    },
  };
}
```

Here's how this works:

1. **Retrieve the user's affinities.** The function gets the user's <Affinity /> from the [personalization context](/doc/guides/personalization/advanced-personalization/implement/guides/fetching-a-user-profile#fetch-a-user-profile).
2. **Filter affinities.** It keeps only affinities that match the specified attribute.
3. **Create affinity scores.** It builds a mapping of the scores for the filtered affinities.
4. **Personalize facets.** It exposes a function which filters, scores and sorts facets by their affinity scores in descending order.

Then, you can use the `usePersonalizedItems` function in your app.

## Choose a display approach

When personalizing search facets, you can either **prioritize relevant facets** or
**show only the most relevant facets**.
The choice depends on your user experience goals and the complexity of your facet structure.

### Prioritize relevant facets

The most flexible approach is to sort refinement list items based on user preferences while maintaining access to all search facets
This method subtly guides users towards relevant facets while preserving the complete capability of your search interface.

Use this approach when:

* You want to maintain access to each <FacetValuePair />
* You need to preserve existing refinement list capability
* You want to subtly guide users while keeping all facet values available

#### Preview

<Frame caption="Storefront displaying personalized search facets through sorting">
  <img src="https://mintcdn.com/algolia/aN8Lr52w2iijNnTe/images/guides/advanced-personalization/personalize-search-facets-sorting.png?fit=max&auto=format&n=aN8Lr52w2iijNnTe&q=85&s=6da43632e2a518315454102da51c9ac5" alt="Storefront displaying personalized search facets through sorting" width="1900" height="1137" data-path="images/guides/advanced-personalization/personalize-search-facets-sorting.png" />
</Frame>

In this example, Sony appears first despite having fewer results than other brands, reflecting the user's affinity for this brand.

#### Implementation

```jsx React icon=code theme={"system"}
import { RefinementList } from 'react-instantsearch';

function PersonalizedSortingRefinementList(props) {
  const { getPersonalizedItems } = usePersonalizedItems(props.attribute);
  const transformItems = props.transformItems || ((items) => items);

  return (
    <RefinementList
      {...props}
      transformItems={(items, ...args) => {
        const itemsInUserAffinity = getPersonalizedItems(items);
        const affinityScores = new Map(
          itemsInUserAffinity.map((item) => [
            item.value,
            item.affinityScore || 0,
          ])
        );
        const transformedItems = [...items].sort(
          (a, b) =>
            (affinityScores.get(b.value) || 0) -
            (affinityScores.get(a.value) || 0)
        );

        return transformItems(transformedItems, ...args);
      }}
    />
  );
}
```

This implementation:

* Preserves all existing functionalities of a refinement list
* Sorts items based on user affinity scores while keeping all facet values accessible
* Combines personalization with any custom transformations

### Show only the most relevant facets

For a focused approach, you can create a dedicated refinement list that displays only the facets most relevant to the user.
This creates a streamlined experience by filtering out less relevant facets.
You can combine this with a regular non-personalized refinement list.

Use this approach when:

* Your facet list is long and needs significant filtering
* User experience benefits from a focused, shorter list of options
* You want to reduce cognitive load for users

#### Preview

<Frame caption="Storefront displaying personalized search facets through filtering">
  <img src="https://mintcdn.com/algolia/aN8Lr52w2iijNnTe/images/guides/advanced-personalization/personalize-search-facets.png?fit=max&auto=format&n=aN8Lr52w2iijNnTe&q=85&s=1d641468b7720c0950f4879c9728666d" alt="Storefront displaying personalized search facets through filtering" width="1316" height="878" data-path="images/guides/advanced-personalization/personalize-search-facets.png" />
</Frame>

#### Implementation

```jsx React icon=code theme={"system"}
import { RefinementList } from "react-instantsearch";

function PersonalizedRefinementList({ attribute }) {
  const { getPersonalizedItems } = usePersonalizedItems(attribute);

  return (
    <RefinementList
      limit={500}
      transformItems={(items) => {
        return getPersonalizedItems(items);
      }}
    />
  );
}
```

This implementation:

* Over-fetches items to ensure a good pool of potential matches
* Filters and sorts items based on user affinities
* Creates a focused list of the most relevant facet values

## Next steps

You can also use these strategies to personalize search facets with the [`Menu`](/doc/api-reference/widgets/menu/react) widget.
