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

# Search-based groups

> How to set up search-based Smart Groups to automatically promote items matching specific criteria.

export const SearchQuery = () => <Tooltip tip="The text users enter into a search box. In the Search API, this corresponds to the query parameter. A search query is often used with filters, facets, and other parameters, but these aren't part of the query text itself.">
    search query
  </Tooltip>;

export const Records = () => <Tooltip tip="A record is a searchable object in an Algolia index. Each record consists of named attributes." cta="Algolia records" href="/doc/guides/sending-and-managing-data/prepare-your-data#algolia-records">
    records
  </Tooltip>;

export const organicResultsDefinition = "These are the search results ranked by relevance and your configuration without compositions.";

export const OrganicResults = () => <Tooltip tip={organicResultsDefinition} cta="Smart Groups" href="/doc/guides/compositions/smart-groups/smart-groups">
    organic results
  </Tooltip>;

export const Index = () => <Tooltip tip="An Algolia index is a searchable dataset that consists of records and configuration settings. These settings define how the records are searched and ranked.">
    index
  </Tooltip>;

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 ApplicationID = () => <Tooltip tip="A unique alphanumeric string that identifies an Algolia application." cta="Application ID (dashboard)" href="https://dashboard.algolia.com/account/api-keys">
    application ID
  </Tooltip>;

export const APIKey = () => <Tooltip tip="An alphanumeric string that controls access to the Algolia APIs. It defines what actions are allowed, such as searching an index or adding new records." cta="API key" href="/doc/guides/security/api-keys">
    API key
  </Tooltip>;

export const Feed = () => <Tooltip tip="Group of items used in a composition. Sources can be search results, recommendations, or external data." href="/doc/guides/compositions/multifeed-compositions" cta="Multifeed compositions">
    feed
  </Tooltip>;

Search-based groups let you automatically promote items that match specific criteria, like brand, category, or custom attributes.
You define **what** to promote (with filters), and Algolia determines **which** items match, applying its AI-powered ranking to ensure the most relevant results appear.

For sponsored listings powered by retail media platforms or external recommendation engines, see [external source groups](/doc/guides/compositions/smart-groups/external-source-groups).

Before you begin, review the [Composition API prerequisites](/doc/guides/compositions#before-you-begin-using-the-compositions-api).

## Create your groups in Merchandising Studio

Create and manage compositions and composition rules in Merchandising Studio.
The HTTP APIs, API clients, and Algolia dashboard don't support these tasks.

Creating groups involves two procedures: creating a composition and creating its rules.

### Create a composition

Compositions help you compose dynamic result feeds with more control.

<Steps>
  <Step title="Open the composition creator">
    Go to the Merchandising Studio and open the **Merch tools** page.
    Select the **Search all compositions and indices** menu and click **+ Create Composition**.

    <img src="https://mintcdn.com/algolia/u8QjGPGZbKOqOFEr/images/guides/smart-groups/create-composition.png?fit=max&auto=format&n=u8QjGPGZbKOqOFEr&q=85&s=924c9704e1364452628e5b11a5dca5ec" alt="Merchandising Studio with index selector menu and a button that lets you create a new composition" width="1600" height="936" data-path="images/guides/smart-groups/create-composition.png" />
  </Step>

  <Step title="Configure the composition">
    In the **New Composition** menu, enter a name for this dynamic results <Feed />, and an optional description.
    Select which main <Index /> should be associated with this results feed.

    <img src="https://mintcdn.com/algolia/u8QjGPGZbKOqOFEr/images/guides/smart-groups/new-composition-form.png?fit=max&auto=format&n=u8QjGPGZbKOqOFEr&q=85&s=4331bb16c6b76cc072487bb57e806b25" alt="New compositions menu with name, description, and main index fields" width="1312" height="1024" data-path="images/guides/smart-groups/new-composition-form.png" />

    Create one composition per index.
    If you have different sites, for example, for different geographical regions, create one composition per site and index, such as "Product results feed - US".
    Each composition can have rules for the insertion of groups.
    If you have five sites and one product index each, you need five compositions.
    Give each composition a short, descriptive, and unique name, and select its main source index.

    After creating your first composition, you can find it in the **Search all compositions and indices** menu.
    To list all your compositions and create new ones, go to the **Compositions** section in the sidebar and click **All Compositions**.
  </Step>
</Steps>

### Create composition rules

To insert a curated group of results for a specific query, [category page](/doc/guides/solutions/ecommerce/browse/tutorials/category-pages), or [collection](/doc/guides/solutions/ecommerce/browse/tutorials/collections), define a composition rule and publish it.

<Steps>
  <Step title="Open Composition Rules">
    Use the **Index and Compositions** selector to select the relevant composition.
    Go to the Merchandising Studio's **Merch tools > Compositions > Composition Rules** page.

    <Info>
      Besides **Merch tools**, you can use Merchandising Studio's Visual Merchandiser to manage both composition and index rules in a single visual workflow.
      Go to **Visual Merchandiser**, select the relevant composition, <SearchQuery />, category, or collection, then click **Actions**.
    </Info>
  </Step>

  <Step title="Create a composition rule">
    Click **New Composition Rule**.
  </Step>

  <Step title="Configure group placement">
    In the compositions rules editor, configure where to insert your groups given specific conditions, and based on which filters match the group results.
  </Step>

  <Step title="Specify the trigger conditions">
    Specify the conditions for triggering your composition rule, for example, search queries, categories, collections, and contexts.

    <img src="https://mintcdn.com/algolia/u8QjGPGZbKOqOFEr/images/guides/smart-groups/rule-add-category-condition.png?fit=max&auto=format&n=u8QjGPGZbKOqOFEr&q=85&s=83d07400a20f21692c0689b11917cfac" alt="In the Composition Rule Editor, add a Category Condition" width="1804" height="1374" data-path="images/guides/smart-groups/rule-add-category-condition.png" />

    You can select several queries, categories, and collections if you want to inject the same groups for them.
  </Step>

  <Step title="Add groups">
    Add the groups you would like to create.
    Select **Algolia Index** as the data source, then use filters with 'and' as well as 'or' operations to curate the items that should appear in the group.
    Specify the group's starting position in the results, as well as the number of matching <Records /> to include.

    <img src="https://mintcdn.com/algolia/u8QjGPGZbKOqOFEr/images/guides/smart-groups/rule-add-group.png?fit=max&auto=format&n=u8QjGPGZbKOqOFEr&q=85&s=55b75a1856514dcfe155b808001287b6" alt="Screenshot of the 'Add group' panel with fields for 'Group name', 'Position', 'Quantity', and 'Source Index', and filters for 'brand is Samsung'." width="1800" height="2232" data-path="images/guides/smart-groups/rule-add-group.png" />

    To add a group from a collection, <Filter /> on the `_collections` attribute.
  </Step>

  <Step title="Save the composition rule">
    Save the group and then the composition rule to apply it.

    If not enough records match the filter criteria, a group might have fewer items than you specified.
    The included records can vary at query-time, based on their real-time attribute values as well as applied ranking criteria and index-level rules.
  </Step>
</Steps>

## Curate groups

You can curate groups further, that is, change the behavior of the query used to retrieve and rank the group's items, by applying Index Rules to it (for example, for a group with promoted Adidas items, the group's sub-query might be query="shoes" and filter: "brand"="Adidas").

For more information, see [Composition rules and index rules](/doc/guides/compositions/smart-groups/smart-groups#composition-rules-and-index-rules).

For example, you can pin, hide, or boost items within the group:

1. Go to Merchandising Studio's Visual Merchandiser.
2. Select the corresponding Composition and Search query/Category/Collection where the group's Composition Rule is applied.
3. Click Actions > Curate “group name” (or find the group in the visual preview, click the three dots, then select “Curate group”).
4. The Index Rule Visual Editor will open, allowing you to define Consequences (for example pin or hide items) for the group's sub-query.
5. Publish the Index Rule.

The Index Rule is applied to all queries that trigger its conditions—both in the context of the group and in a direct query (in the preceding example other "shoes" queries with the Adidas filter).
The final results might be different to the ones shown in the Index Rules preview, due to the deduplication between the main query and groups.
For example, an item might already be part of a previous group and thus not show in the final results in a later group.
You may see more items than the ones shown in the final group, when there are more items that match the criteria than the quantity or length of the group is.

## Integrate compositions

Integrating compositions and smart groups involves these steps:

<Steps>
  <Step title="Copy your API credentials">
    In the [Algolia dashboard](https://dashboard.algolia.com/account/api-keys/), go to **Settings > API Keys** and copy your <ApplicationID /> and <APIKey />.
    The API key needs at least [search permissions](/doc/guides/security/api-keys#access-control-list-acl) for the index used in your composition.

    <Warning>
      [Client-generated **secured API keys**](/doc/guides/security/api-keys#secured-api-keys) aren't supported for the [Composition API](/doc/rest-api/composition).
    </Warning>
  </Step>

  <Step title="Copy the composition ID">
    In Merchandising Studio, go to **Merch tools > Compositions > Composition Rules** and select the composition from the **Composition or Index** selector.
    Copy the composition ID to your clipboard.

    <img src="https://mintcdn.com/algolia/u8QjGPGZbKOqOFEr/images/guides/smart-groups/get-composition-id.png?fit=max&auto=format&n=u8QjGPGZbKOqOFEr&q=85&s=367d761b9538891c2f7dad503f8bec3f" alt="Screenshot of a search box in the 'Composition Rules' section, showing a composition ID with a 'Copy composition ID to clipboard' tooltip." width="2582" height="538" data-path="images/guides/smart-groups/get-composition-id.png" />
  </Step>

  <Step title="Choose an integration method">
    Query the [Composition API](/doc/rest-api/composition/search) with [API clients](#integrate-compositions-with-api-clients) or [InstantSearch](#integrate-compositions-with-instantsearch) for web.
  </Step>
</Steps>

Indexing remains the same, with your previous indexing mechanism (for example, the Search API or indexing connectors).
You might need to add extra attributes for identifying groups if this information isn't already indexed.

### Integrate compositions with API clients

Use the [Composition API client](/doc/libraries/sdk/methods/composition) in one of the supported programming languages.

### Integrate compositions with InstantSearch

Start by replacing the Search API client with the [Composition API client](/doc/libraries/sdk/methods/composition).

Compositions require these versions of the InstantSearch libraries:

* [React InstantSearch](#react-instantsearch): version 7.15.5 or later
* [InstantSearch.js](/doc/guides/compositions/smart-groups/search-based-groups#instantsearch-js): version 4.78.1 or later
* [Vue InstantSearch](#vue-instantsearch): version 4.20.6 or later

Compositions have the following limitations:

* The Shopify, Magento, and BigCommerce frontend integrations and the default Salesforce B2C Commerce frontend integration aren't supported.
* You can't use the `index` widget.
* You can't combine Composition API calls with Search API or Recommend API calls on the same page.
* You can't show groups in autocomplete menus, but you can open a composition-based search results page from there.

<CodeGroup>
  ```jsx React theme={"system"}
  import React from "react";
  import { compositionClient } from "@algolia/composition";
  import { InstantSearch } from "react-instantsearch";

  const searchClient = compositionClient(
    "ALGOLIA_APPLICATION_ID",
    "ALGOLIA_SEARCH_API_KEY",
  );

  function App() {
    return (
      <InstantSearch compositionID="COMPOSITION_ID" searchClient={searchClient}>
        {/* Widgets */}
      </InstantSearch>
    );
  }
  ```

  ```js JavaScript theme={"system"}
  const search = instantsearch({
    compositionID: "COMPOSITION_ID",
    searchClient: compositionClient("APPID", "APIKEY"),
  });

  // Add widgets
  // ...

  search.start();
  ```

  ```vue Vue theme={"system"}
  <template>
    <ais-instant-search
      composition-id="COMPOSITION_ID"
      :search-client="searchClient"
    >
      <!-- Widgets -->
    </ais-instant-search>
  </template>

  <script>
    import { compositionClient } from '@algolia/composition';

    export default {
      data() {
        return {
          searchClient: compositionClient(
            'ALGOLIA_APPLICATION_ID',
            'ALGOLIA_SEARCH_API_KEY'
          ),
        };
      },
    };
  </script>
  ```
</CodeGroup>

### Facets (including disjunctive faceting)

Facets are [configured at the index level](/doc/guides/managing-results/refine-results/faceting) and honored by Composition API at runtime.

When querying the Composition API, add the `disjunctive()` modifier to any facet that should use OR logic when a user selects multiple values.
For example, users can filter the `brand` facet by `Nike` or `Adidas`to return accurate values and counts while that facet is filtered.<br />

For example:

```js JavaScript icon=code theme={"system"}
facets: ["disjunctive(attribute)"];
```

If you use InstantSearch, this will be handled automatically and you don't need to make any changes.

<Info>
  InstantSearch handles this automatically.
</Info>

Each request has a limit of 20 disjunctive facets.
Using [facet display](/doc/guides/building-search-ui/ui-and-ux-patterns/facet-display/js) in InstantSearch with more than 20 facets is also not supported.

### Events setup

When sending [click and conversion events](/doc/guides/sending-events), you still need to send the underlying index name as `indexName` attribute with your events, not the composition ID.
No further changes are needed.

<Info>
  InstantSearch's events tracking mechanism handles passing the underlying index name for you, if you're using the specified versions of the packages.
</Info>

## Next steps

<AccordionGroup>
  <Accordion title="Curate group results">
    Use [index rules](/doc/guides/managing-results/rules/rules-overview) with composition rules to curate group results.
    For details, see [Composition rules and index rules](/doc/guides/compositions/smart-groups/smart-groups#composition-rules-and-index-rules).
  </Accordion>

  <Accordion title="Dynamic Re-Ranking">
    When enabled on your index, [Dynamic Re-Ranking](/doc/guides/algolia-ai/re-ranking) re-ranks both main results and results in groups.
  </Accordion>

  <Accordion title="Groups and sorting">
    You can set up a composition for your replica index.
    Then, you can curate the replica feed like a standard results feed.
  </Accordion>

  <Accordion title="Place multiple groups">
    Each group needs a unique start position.
    If group ranges overlap, Algolia shifts the group with the higher start position to the next available positions.

    For example, group A has three products starting at position 1, and group B has three starting at position 2.
    The final order is A.1, A.2, A.3, B.1, B.2, B.3, followed by the main results at position 7.
  </Accordion>

  <Accordion title="Deduplication">
    Algolia removes duplicates across <OrganicResults /> and groups.
    By default, the `highestInjected` strategy keeps the item in its group position instead of in organic results.

    To choose different behavior, configure the [deduplication strategy](/doc/guides/compositions/smart-groups/deduplication-strategy) in the composition rule.
  </Accordion>
</AccordionGroup>
