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

# Dynamic filtering with Rules

> Dynamic filtering with Rules search.

export const Application = () => <Tooltip tip="An Algolia application is a self-contained environment with its own indices, configuration, and API keys. Applications don't share data or settings with each other.">
    application
  </Tooltip>;

export const AlgoliaSearch = () => <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80" width="20" height="20" className="inline" fill="none" role="presentation" ariaLabel="Algolia Search">
    <circle cx="40" cy="32" r="28" fill="#5468FF"></circle>
    <rect x="30" y="22" width="20" height="20" rx="10" fill="#fff"></rect>
    <path d="M43 63.5 54.5 60l6 17h-12L43 63.5Z" fill="#36395A"></path>
  </svg>;

To help users find what they're looking for straight from the search box,
you can use Algolia Rules to automatically apply a filter to results if the query matches a facet value.

## How to create a dynamic filtering rule

In this example for a product catalog,
you create a rule that displays products with the "red" value in the `color` facet if the query contains the word "red".

Using the [example dataset](#example-dataset), this rule ensures that only records with "red" in the `color` attribute are returned. It ignores "red" in other attributes such as `brand`.

{/* vale Vale.Spelling = NO */}

| Query | Results                                                                                      |
| ----- | -------------------------------------------------------------------------------------------- |
| red   | FM, Clothing, LondonLook, Red, 21.99 <br /> The Mandal, Toaster, Black & Decker, Red, 149.99 |

{/* vale Algolia.Ampersand = YES */}

### Using the dashboard

1. Go to the [Algolia dashboard](https://dashboard.algolia.com/explorer/browse) and select your Algolia <Application />.

2. On the left sidebar, select <AlgoliaSearch /> **Search**.

3. Select your Algolia index and go to the [**Rules**](https://dashboard.algolia.com/rules) page.

4. Select **Create your first rule** or **New rule**.
   In the drop-down menu, select the **Manual Editor** option.

5. In the **Condition(s)** section, with **Query** toggled on, select **Contains** from the menu,
   and enter `red` in the input.

6. In the **Consequence(s)** section:

   1. Click **Add consequence** and select **Add Query Parameter**.
   2. In the input, add the JSON parameters you want to apply when the user's query matches the Rule: `{"filters":"color:red"}`
   3. Click **Add consequence** and select **Remove Word**.
   4. Enter `red` in the input.

   If you click **Optional** under **Consequence(s)**,
   this will display non-red products after the red ones.
   For more information, see [Optional filters](/doc/guides/managing-results/rules/merchandising-and-promoting/how-to/how-to-promote-with-optional-filters).

7. **Save** your changes.

### Using the API

To run the code examples on this page, [install the latest API client](/doc/libraries/sdk/install).

This example uses the [`filters`](/doc/api-reference/api-parameters/filters) parameter.
With this approach, you need one rule per filter value.
If you have 10 color options, you need 10 rules, one for each color.

<CodeGroup>
  ```cs C# theme={"system"}
  var response = await client.SaveRuleAsync(
    "INDEX_NAME",
    "red-color",
    new Rule
    {
      ObjectID = "red-color",
      Conditions = new List<Condition>
      {
        new Condition { Pattern = "red", Anchoring = Enum.Parse<Anchoring>("Contains") },
      },
      Consequence = new Consequence
      {
        Params = new ConsequenceParams
        {
          Query = new ConsequenceQuery(
            new ConsequenceQueryObject { Remove = new List<string> { "red" } }
          ),
          Filters = "color:red",
        },
      },
    }
  );
  ```

  ```dart Dart theme={"system"}
  final response = await client.saveRule(
    indexName: "INDEX_NAME",
    objectID: "red-color",
    rule: Rule(
      objectID: "red-color",
      conditions: [
        Condition(
          pattern: "red",
          anchoring: Anchoring.fromJson("contains"),
        ),
      ],
      consequence: Consequence(
        params: ConsequenceParams(
          query: ConsequenceQueryObject(
            remove: [
              "red",
            ],
          ),
          filters: "color:red",
        ),
      ),
    ),
  );
  ```

  ```go Go theme={"system"}
  response, err := client.SaveRule(client.NewApiSaveRuleRequest(
    "INDEX_NAME", "red-color",
    search.NewEmptyRule().SetObjectID("red-color").SetConditions(
      []search.Condition{*search.NewEmptyCondition().SetPattern("red").SetAnchoring(search.Anchoring("contains"))}).SetConsequence(
      search.NewEmptyConsequence().SetParams(
        search.NewEmptyConsequenceParams().SetQuery(search.ConsequenceQueryObjectAsConsequenceQuery(
          search.NewEmptyConsequenceQueryObject().SetRemove(
            []string{"red"}))).SetFilters("color:red")))))
  if err != nil {
    // handle the eventual error
    panic(err)
  }
  ```

  ```java Java theme={"system"}
  UpdatedAtResponse response = client.saveRule(
    "INDEX_NAME",
    "red-color",
    new Rule()
      .setObjectID("red-color")
      .setConditions(Arrays.asList(new Condition().setPattern("red").setAnchoring(Anchoring.CONTAINS)))
      .setConsequence(
        new Consequence().setParams(
          new ConsequenceParams().setQuery(new ConsequenceQueryObject().setRemove(Arrays.asList("red"))).setFilters("color:red")
        )
      )
  );
  ```

  ```js JavaScript theme={"system"}
  const response = await client.saveRule({
    indexName: 'indexName',
    objectID: 'red-color',
    rule: {
      objectID: 'red-color',
      conditions: [{ pattern: 'red', anchoring: 'contains' }],
      consequence: { params: { query: { remove: ['red'] }, filters: 'color:red' } },
    },
  });
  ```

  ```kotlin Kotlin theme={"system"}
  var response =
    client.saveRule(
      indexName = "INDEX_NAME",
      objectID = "red-color",
      rule =
        Rule(
          objectID = "red-color",
          conditions =
            listOf(
              Condition(
                pattern = "red",
                anchoring = Anchoring.entries.first { it.value == "contains" },
              )
            ),
          consequence =
            Consequence(
              params =
                ConsequenceParams(
                  query = ConsequenceQueryObject(remove = listOf("red")),
                  filters = "color:red",
                )
            ),
        ),
    )
  ```

  ```php PHP theme={"system"}
  $response = $client->saveRule(
      'INDEX_NAME',
      'red-color',
      ['objectID' => 'red-color',
          'conditions' => [
              ['pattern' => 'red',
                  'anchoring' => 'contains',
              ],
          ],
          'consequence' => ['params' => ['query' => ['remove' => [
              'red',
          ],
          ],
              'filters' => 'color:red',
          ],
          ],
      ],
  );
  ```

  ```python Python theme={"system"}
  response = client.save_rule(
      index_name="INDEX_NAME",
      object_id="red-color",
      rule={
          "objectID": "red-color",
          "conditions": [
              {
                  "pattern": "red",
                  "anchoring": "contains",
              },
          ],
          "consequence": {
              "params": {
                  "query": {
                      "remove": [
                          "red",
                      ],
                  },
                  "filters": "color:red",
              },
          },
      },
  )
  ```

  ```ruby Ruby theme={"system"}
  response = client.save_rule(
    "INDEX_NAME",
    "red-color",
    Algolia::Search::Rule.new(
      algolia_object_id: "red-color",
      conditions: [Algolia::Search::Condition.new(pattern: "red", anchoring: "contains")],
      consequence: Algolia::Search::Consequence.new(
        params: Algolia::Search::ConsequenceParams.new(
          query: Algolia::Search::ConsequenceQueryObject.new(remove: ["red"]),
          filters: "color:red"
        )
      )
    )
  )
  ```

  ```scala Scala theme={"system"}
  val response = Await.result(
    client.saveRule(
      indexName = "INDEX_NAME",
      objectID = "red-color",
      rule = Rule(
        objectID = "red-color",
        conditions = Some(
          Seq(
            Condition(
              pattern = Some("red"),
              anchoring = Some(Anchoring.withName("contains"))
            )
          )
        ),
        consequence = Consequence(
          params = Some(
            ConsequenceParams(
              query = Some(
                ConsequenceQueryObject(
                  remove = Some(Seq("red"))
                )
              ),
              filters = Some("color:red")
            )
          )
        )
      )
    ),
    Duration(100, "sec")
  )
  ```

  ```swift Swift theme={"system"}
  let response = try await client.saveRule(
      indexName: "INDEX_NAME",
      objectID: "red-color",
      rule: Rule(
          objectID: "red-color",
          conditions: [SearchCondition(pattern: "red", anchoring: SearchAnchoring.contains)],
          consequence: SearchConsequence(params: SearchConsequenceParams(
              filters: "color:red",
              query: SearchConsequenceQuery
                  .searchConsequenceQueryObject(SearchConsequenceQueryObject(remove: ["red"]))
          ))
      )
  )
  ```
</CodeGroup>

## Example: one rule per facet

Instead of creating one rule per facet value,
this approach uses one rule for the `color` facet.

Using the [example dataset](#example-dataset),
this single rule ensures that any record with any matching color value in the `color` attribute is returned.

| Query | Results                                             |
| ----- | --------------------------------------------------- |
| red   | FM, Clothing, LondonLook, Red, 21.99                |
|       | The Mandal, Toaster, Black & Decker, Red, 149.99    |
| black | Will Carpenter, T-shirt, Red or Dead, Black, 199.99 |

#### Using the dashboard

1. Create a new rule. See [how to create a dynamic filtering rule](#how-to-create-a-dynamic-filtering-rule).

2. In the Manual Editor's **Condition(s)** section, click the box next to **Query contains** and select the option **Add Facet "color"** from the drop-down menu.

3. In the **Consequence(s)** section:

   1. Click **Add consequence** and select **Filter/Boost Matching Attributes**.
   2. Click the **Filter** box and select the option **Add Facet "color"** from the drop-down menu.

4. **Save** your changes.

#### Using the API

<CodeGroup>
  ```cs C# theme={"system"}
  var response = await client.SaveRuleAsync(
    "INDEX_NAME",
    "color-facets",
    new Rule
    {
      ObjectID = "color-facets",
      Conditions = new List<Condition> { new Condition { Pattern = "{facet:color}" } },
      Consequence = new Consequence
      {
        Params = new ConsequenceParams
        {
          AutomaticFacetFilters = new AutomaticFacetFilters(
            new List<AutomaticFacetFilter> { new AutomaticFacetFilter { Facet = "color" } }
          ),
        },
      },
    }
  );
  ```

  ```dart Dart theme={"system"}
  final response = await client.saveRule(
    indexName: "INDEX_NAME",
    objectID: "color-facets",
    rule: Rule(
      objectID: "color-facets",
      conditions: [
        Condition(
          pattern: "{facet:color}",
        ),
      ],
      consequence: Consequence(
        params: ConsequenceParams(
          automaticFacetFilters: [
            AutomaticFacetFilter(
              facet: "color",
            ),
          ],
        ),
      ),
    ),
  );
  ```

  ```go Go theme={"system"}
  response, err := client.SaveRule(client.NewApiSaveRuleRequest(
    "INDEX_NAME", "color-facets",
    search.NewEmptyRule().SetObjectID("color-facets").SetConditions(
      []search.Condition{*search.NewEmptyCondition().SetPattern("{facet:color}")}).SetConsequence(
      search.NewEmptyConsequence().SetParams(
        search.NewEmptyConsequenceParams().SetAutomaticFacetFilters(search.ArrayOfAutomaticFacetFilterAsAutomaticFacetFilters(
          []search.AutomaticFacetFilter{*search.NewEmptyAutomaticFacetFilter().SetFacet("color")}))))))
  if err != nil {
    // handle the eventual error
    panic(err)
  }
  ```

  ```java Java theme={"system"}
  UpdatedAtResponse response = client.saveRule(
    "INDEX_NAME",
    "color-facets",
    new Rule()
      .setObjectID("color-facets")
      .setConditions(Arrays.asList(new Condition().setPattern("{facet:color}")))
      .setConsequence(
        new Consequence().setParams(
          new ConsequenceParams().setAutomaticFacetFilters(
            AutomaticFacetFilters.ofListOfAutomaticFacetFilter(Arrays.asList(new AutomaticFacetFilter().setFacet("color")))
          )
        )
      )
  );
  ```

  ```js JavaScript theme={"system"}
  const response = await client.saveRule({
    indexName: 'indexName',
    objectID: 'color-facets',
    rule: {
      objectID: 'color-facets',
      conditions: [{ pattern: '{facet:color}' }],
      consequence: { params: { automaticFacetFilters: [{ facet: 'color' }] } },
    },
  });
  ```

  ```kotlin Kotlin theme={"system"}
  var response =
    client.saveRule(
      indexName = "INDEX_NAME",
      objectID = "color-facets",
      rule =
        Rule(
          objectID = "color-facets",
          conditions = listOf(Condition(pattern = "{facet:color}")),
          consequence =
            Consequence(
              params =
                ConsequenceParams(
                  automaticFacetFilters =
                    AutomaticFacetFilters.ofListOfAutomaticFacetFilter(
                      listOf(AutomaticFacetFilter(facet = "color"))
                    )
                )
            ),
        ),
    )
  ```

  ```php PHP theme={"system"}
  $response = $client->saveRule(
      'INDEX_NAME',
      'color-facets',
      ['objectID' => 'color-facets',
          'conditions' => [
              ['pattern' => '{facet:color}',
              ],
          ],
          'consequence' => ['params' => ['automaticFacetFilters' => [
              ['facet' => 'color',
              ],
          ],
          ],
          ],
      ],
  );
  ```

  ```python Python theme={"system"}
  response = client.save_rule(
      index_name="INDEX_NAME",
      object_id="color-facets",
      rule={
          "objectID": "color-facets",
          "conditions": [
              {
                  "pattern": "{facet:color}",
              },
          ],
          "consequence": {
              "params": {
                  "automaticFacetFilters": [
                      {
                          "facet": "color",
                      },
                  ],
              },
          },
      },
  )
  ```

  ```ruby Ruby theme={"system"}
  response = client.save_rule(
    "INDEX_NAME",
    "color-facets",
    Algolia::Search::Rule.new(
      algolia_object_id: "color-facets",
      conditions: [Algolia::Search::Condition.new(pattern: "{facet:color}")],
      consequence: Algolia::Search::Consequence.new(
        params: Algolia::Search::ConsequenceParams.new(
          automatic_facet_filters: [Algolia::Search::AutomaticFacetFilter.new(facet: "color")]
        )
      )
    )
  )
  ```

  ```scala Scala theme={"system"}
  val response = Await.result(
    client.saveRule(
      indexName = "INDEX_NAME",
      objectID = "color-facets",
      rule = Rule(
        objectID = "color-facets",
        conditions = Some(
          Seq(
            Condition(
              pattern = Some("{facet:color}")
            )
          )
        ),
        consequence = Consequence(
          params = Some(
            ConsequenceParams(
              automaticFacetFilters = Some(
                AutomaticFacetFilters(
                  Seq(
                    AutomaticFacetFilter(
                      facet = "color"
                    )
                  )
                )
              )
            )
          )
        )
      )
    ),
    Duration(100, "sec")
  )
  ```

  ```swift Swift theme={"system"}
  let response = try await client.saveRule(
      indexName: "INDEX_NAME",
      objectID: "color-facets",
      rule: Rule(
          objectID: "color-facets",
          conditions: [SearchCondition(pattern: "{facet:color}")],
          consequence: SearchConsequence(
              params: SearchConsequenceParams(automaticFacetFilters: SearchAutomaticFacetFilters
                  .arrayOfSearchAutomaticFacetFilter([SearchAutomaticFacetFilter(facet: "color")]))
          )
      )
  )
  ```
</CodeGroup>

### Numerical dynamic filtering

Consider a user entering the query "cheap toaster 800w".
You can use two rules together to filter results by:

1. The product type: `"Toaster"`
2. "Cheapness". You determine that a cheap product is any product that costs less than \$15.

Using the [example dataset](#example-dataset),
these rules ensure that any product that costs less than \$15,
has the `product_type` "Toaster" and includes the phrase "800w" is returned.

| Query              | Results                                        |
| ------------------ | ---------------------------------------------- |
| cheap toaster 800w | Essentials 800w, Toaster, Daewoo, Black, 14.99 |

#### Using the dashboard

**Create the first rule:**

1. Create a new rule. See [How to create a dynamic filtering rule](#how-to-create-a-dynamic-filtering-rule).

2. In the Manual Editor's **Condition(s)** section, with **Query** toggled on, select **Contains** in the drop-down menu, and enter "toaster" in the input field.

3. In the **Consequence(s)** section:

   1. Click **Add consequence** and select **Add Query Parameter**.
   2. In the input field that appears, enter `{"filters":"product_type:toaster"}`
   3. Click **Add consequence** and select **Remove Word**.
   4. Type or select "toaster" in the input field.

4. **Save** your changes.

**Create the second rule:**

1. Create a new rule

2. In the Manual Editor's **Condition(s)**, with **Query** toggled on, select **Contains** in the drop-down menu, and enter "cheap" in the input field.

3. In the **Consequence(s)** section:

   1. Click **Add consequence** and select **Add Query Parameter**.
   2. In the input field that appears, enter `{"filters":"price < 10"}`
   3. Click **Add consequence** and select **Remove Word**.
   4. Type or select "cheap" in the input field.

4. **Save** your changes.

#### Using the API

<CodeGroup>
  ```cs C# theme={"system"}
  var response = await client.SaveRulesAsync(
    "INDEX_NAME",
    new List<Rule>
    {
      new Rule
      {
        ObjectID = "toaster",
        Conditions = new List<Condition>
        {
          new Condition { Pattern = "toaster", Anchoring = Enum.Parse<Anchoring>("Contains") },
        },
        Consequence = new Consequence
        {
          Params = new ConsequenceParams
          {
            Query = new ConsequenceQuery(
              new ConsequenceQueryObject { Remove = new List<string> { "toaster" } }
            ),
            Filters = "product_type:toaster",
          },
        },
      },
      new Rule
      {
        ObjectID = "cheap",
        Conditions = new List<Condition>
        {
          new Condition { Pattern = "cheap", Anchoring = Enum.Parse<Anchoring>("Contains") },
        },
        Consequence = new Consequence
        {
          Params = new ConsequenceParams
          {
            Query = new ConsequenceQuery(
              new ConsequenceQueryObject { Remove = new List<string> { "cheap" } }
            ),
            Filters = "price < 15",
          },
        },
      },
    }
  );
  ```

  ```dart Dart theme={"system"}
  final response = await client.saveRules(
    indexName: "INDEX_NAME",
    rules: [
      Rule(
        objectID: "toaster",
        conditions: [
          Condition(
            pattern: "toaster",
            anchoring: Anchoring.fromJson("contains"),
          ),
        ],
        consequence: Consequence(
          params: ConsequenceParams(
            query: ConsequenceQueryObject(
              remove: [
                "toaster",
              ],
            ),
            filters: "product_type:toaster",
          ),
        ),
      ),
      Rule(
        objectID: "cheap",
        conditions: [
          Condition(
            pattern: "cheap",
            anchoring: Anchoring.fromJson("contains"),
          ),
        ],
        consequence: Consequence(
          params: ConsequenceParams(
            query: ConsequenceQueryObject(
              remove: [
                "cheap",
              ],
            ),
            filters: "price < 15",
          ),
        ),
      ),
    ],
  );
  ```

  ```go Go theme={"system"}
  response, err := client.SaveRules(client.NewApiSaveRulesRequest(
    "INDEX_NAME",
    []search.Rule{*search.NewEmptyRule().SetObjectID("toaster").SetConditions(
      []search.Condition{*search.NewEmptyCondition().SetPattern("toaster").SetAnchoring(search.Anchoring("contains"))}).SetConsequence(
      search.NewEmptyConsequence().SetParams(
        search.NewEmptyConsequenceParams().SetQuery(search.ConsequenceQueryObjectAsConsequenceQuery(
          search.NewEmptyConsequenceQueryObject().SetRemove(
            []string{"toaster"}))).SetFilters("product_type:toaster"))), *search.NewEmptyRule().SetObjectID("cheap").SetConditions(
      []search.Condition{*search.NewEmptyCondition().SetPattern("cheap").SetAnchoring(search.Anchoring("contains"))}).SetConsequence(
      search.NewEmptyConsequence().SetParams(
        search.NewEmptyConsequenceParams().SetQuery(search.ConsequenceQueryObjectAsConsequenceQuery(
          search.NewEmptyConsequenceQueryObject().SetRemove(
            []string{"cheap"}))).SetFilters("price < 15")))}))
  if err != nil {
    // handle the eventual error
    panic(err)
  }
  ```

  ```java Java theme={"system"}
  UpdatedAtResponse response = client.saveRules(
    "INDEX_NAME",
    Arrays.asList(
      new Rule()
        .setObjectID("toaster")
        .setConditions(Arrays.asList(new Condition().setPattern("toaster").setAnchoring(Anchoring.CONTAINS)))
        .setConsequence(
          new Consequence().setParams(
            new ConsequenceParams()
              .setQuery(new ConsequenceQueryObject().setRemove(Arrays.asList("toaster")))
              .setFilters("product_type:toaster")
          )
        ),
      new Rule()
        .setObjectID("cheap")
        .setConditions(Arrays.asList(new Condition().setPattern("cheap").setAnchoring(Anchoring.CONTAINS)))
        .setConsequence(
          new Consequence().setParams(
            new ConsequenceParams().setQuery(new ConsequenceQueryObject().setRemove(Arrays.asList("cheap"))).setFilters("price < 15")
          )
        )
    )
  );
  ```

  ```js JavaScript theme={"system"}
  const response = await client.saveRules({
    indexName: 'INDEX_NAME',
    rules: [
      {
        objectID: 'toaster',
        conditions: [{ pattern: 'toaster', anchoring: 'contains' }],
        consequence: { params: { query: { remove: ['toaster'] }, filters: 'product_type:toaster' } },
      },
      {
        objectID: 'cheap',
        conditions: [{ pattern: 'cheap', anchoring: 'contains' }],
        consequence: { params: { query: { remove: ['cheap'] }, filters: 'price < 15' } },
      },
    ],
  });
  ```

  ```kotlin Kotlin theme={"system"}
  var response =
    client.saveRules(
      indexName = "INDEX_NAME",
      rules =
        listOf(
          Rule(
            objectID = "toaster",
            conditions =
              listOf(
                Condition(
                  pattern = "toaster",
                  anchoring = Anchoring.entries.first { it.value == "contains" },
                )
              ),
            consequence =
              Consequence(
                params =
                  ConsequenceParams(
                    query = ConsequenceQueryObject(remove = listOf("toaster")),
                    filters = "product_type:toaster",
                  )
              ),
          ),
          Rule(
            objectID = "cheap",
            conditions =
              listOf(
                Condition(
                  pattern = "cheap",
                  anchoring = Anchoring.entries.first { it.value == "contains" },
                )
              ),
            consequence =
              Consequence(
                params =
                  ConsequenceParams(
                    query = ConsequenceQueryObject(remove = listOf("cheap")),
                    filters = "price < 15",
                  )
              ),
          ),
        ),
    )
  ```

  ```php PHP theme={"system"}
  $response = $client->saveRules(
      'INDEX_NAME',
      [
          ['objectID' => 'toaster',
              'conditions' => [
                  ['pattern' => 'toaster',
                      'anchoring' => 'contains',
                  ],
              ],
              'consequence' => ['params' => ['query' => ['remove' => [
                  'toaster',
              ],
              ],
                  'filters' => 'product_type:toaster',
              ],
              ],
          ],

          ['objectID' => 'cheap',
              'conditions' => [
                  ['pattern' => 'cheap',
                      'anchoring' => 'contains',
                  ],
              ],
              'consequence' => ['params' => ['query' => ['remove' => [
                  'cheap',
              ],
              ],
                  'filters' => 'price < 15',
              ],
              ],
          ],
      ],
  );
  ```

  ```python Python theme={"system"}
  response = client.save_rules(
      index_name="INDEX_NAME",
      rules=[
          {
              "objectID": "toaster",
              "conditions": [
                  {
                      "pattern": "toaster",
                      "anchoring": "contains",
                  },
              ],
              "consequence": {
                  "params": {
                      "query": {
                          "remove": [
                              "toaster",
                          ],
                      },
                      "filters": "product_type:toaster",
                  },
              },
          },
          {
              "objectID": "cheap",
              "conditions": [
                  {
                      "pattern": "cheap",
                      "anchoring": "contains",
                  },
              ],
              "consequence": {
                  "params": {
                      "query": {
                          "remove": [
                              "cheap",
                          ],
                      },
                      "filters": "price < 15",
                  },
              },
          },
      ],
  )
  ```

  ```ruby Ruby theme={"system"}
  response = client.save_rules(
    "INDEX_NAME",
    [
      Algolia::Search::Rule.new(
        algolia_object_id: "toaster",
        conditions: [Algolia::Search::Condition.new(pattern: "toaster", anchoring: "contains")],
        consequence: Algolia::Search::Consequence.new(
          params: Algolia::Search::ConsequenceParams.new(
            query: Algolia::Search::ConsequenceQueryObject.new(remove: ["toaster"]),
            filters: "product_type:toaster"
          )
        )
      ),
      Algolia::Search::Rule.new(
        algolia_object_id: "cheap",
        conditions: [Algolia::Search::Condition.new(pattern: "cheap", anchoring: "contains")],
        consequence: Algolia::Search::Consequence.new(
          params: Algolia::Search::ConsequenceParams.new(
            query: Algolia::Search::ConsequenceQueryObject.new(remove: ["cheap"]),
            filters: "price < 15"
          )
        )
      )
    ]
  )
  ```

  ```scala Scala theme={"system"}
  val response = Await.result(
    client.saveRules(
      indexName = "INDEX_NAME",
      rules = Seq(
        Rule(
          objectID = "toaster",
          conditions = Some(
            Seq(
              Condition(
                pattern = Some("toaster"),
                anchoring = Some(Anchoring.withName("contains"))
              )
            )
          ),
          consequence = Consequence(
            params = Some(
              ConsequenceParams(
                query = Some(
                  ConsequenceQueryObject(
                    remove = Some(Seq("toaster"))
                  )
                ),
                filters = Some("product_type:toaster")
              )
            )
          )
        ),
        Rule(
          objectID = "cheap",
          conditions = Some(
            Seq(
              Condition(
                pattern = Some("cheap"),
                anchoring = Some(Anchoring.withName("contains"))
              )
            )
          ),
          consequence = Consequence(
            params = Some(
              ConsequenceParams(
                query = Some(
                  ConsequenceQueryObject(
                    remove = Some(Seq("cheap"))
                  )
                ),
                filters = Some("price < 15")
              )
            )
          )
        )
      )
    ),
    Duration(100, "sec")
  )
  ```

  ```swift Swift theme={"system"}
  let response = try await client.saveRules(
      indexName: "INDEX_NAME",
      rules: [
          Rule(objectID: "toaster", conditions: [SearchCondition(
              pattern: "toaster",
              anchoring: SearchAnchoring.contains
          )], consequence: SearchConsequence(params: SearchConsequenceParams(
              filters: "product_type:toaster",
              query: SearchConsequenceQuery
                  .searchConsequenceQueryObject(SearchConsequenceQueryObject(remove: ["toaster"]))
          ))),
          Rule(
              objectID: "cheap",
              conditions: [SearchCondition(pattern: "cheap", anchoring: SearchAnchoring.contains)],
              consequence: SearchConsequence(params: SearchConsequenceParams(
                  filters: "price < 15",
                  query: SearchConsequenceQuery
                      .searchConsequenceQueryObject(SearchConsequenceQueryObject(remove: ["cheap"]))
              ))
          ),
      ]
  )
  ```
</CodeGroup>

### Tagged filters

Consider a user who enters the query "apple headphones".
They would expect to search for results that match the term "headphones", but only where the `brand` attribute matches "apple".
You can find this behavior on sites such as GitHub.
It's a great alternative to filters for users who prefer to type rather than click.

This approach is similar to [one rule per facet](#example-one-rule-per-facet).

Using the [example dataset](#example-dataset), this rule ensures that any record containing the phrase "headphones" that also has "Apple" in the `brand` attribute will be returned. It won't return non-Apple brands, even if the phrase "Apple" appears in other attributes.

| Query            | Results                                      |
| ---------------- | -------------------------------------------- |
| apple headphones | Airpods Max, Headphones, Apple, Gray, 548.99 |

#### Using the dashboard

1. Create a new rule [as above](#how-to-create-a-dynamic-filtering-rule)

2. In the Manual Editor's **Condition(s)**, click the box next to **Query contains** and select the option **Add Facet "brand"** from the drop-down menu.

3. Clear the **Apply to plurals, synonyms and typos** checkbox to ensure precise matching of the brand name.

4. In the **Consequence(s)** section:

   1. Click **Add consequence** and select **Filter/Boost Matching Attributes**.
   2. Click the **Filter** box that appears and select the option **Add Facet "brand"** from the drop-down menu.
   3. Click **Add consequence** and select **Remove word**.
   4. In the input that appears, select **Remove `{facet:brand}`**.

5. **Save** your changes.

#### Using the API

<CodeGroup>
  ```cs C# theme={"system"}
  var response = await client.SaveRuleAsync(
    "INDEX_NAME",
    "tagged-brand-rule",
    new Rule
    {
      Conditions = new List<Condition>
      {
        new Condition
        {
          Pattern = "brand: {facet:brand}",
          Anchoring = Enum.Parse<Anchoring>("Contains"),
          Alternatives = false,
        },
      },
      Consequence = new Consequence
      {
        Params = new ConsequenceParams
        {
          AutomaticFacetFilters = new AutomaticFacetFilters(
            new List<AutomaticFacetFilter> { new AutomaticFacetFilter { Facet = "brand" } }
          ),
          Query = new ConsequenceQuery(
            new ConsequenceQueryObject
            {
              Remove = new List<string> { "brand:", "{facet:brand}" },
            }
          ),
        },
      },
      Description = "filter on brand: {brand}",
      ObjectID = "tagged-brand-rule",
    }
  );
  ```

  ```dart Dart theme={"system"}
  final response = await client.saveRule(
    indexName: "INDEX_NAME",
    objectID: "tagged-brand-rule",
    rule: Rule(
      conditions: [
        Condition(
          pattern: "brand: {facet:brand}",
          anchoring: Anchoring.fromJson("contains"),
          alternatives: false,
        ),
      ],
      consequence: Consequence(
        params: ConsequenceParams(
          automaticFacetFilters: [
            AutomaticFacetFilter(
              facet: "brand",
            ),
          ],
          query: ConsequenceQueryObject(
            remove: [
              "brand:",
              "{facet:brand}",
            ],
          ),
        ),
      ),
      description: "filter on brand: {brand}",
      objectID: "tagged-brand-rule",
    ),
  );
  ```

  ```go Go theme={"system"}
  response, err := client.SaveRule(client.NewApiSaveRuleRequest(
    "INDEX_NAME", "tagged-brand-rule",
    search.NewEmptyRule().SetConditions(
      []search.Condition{
        *search.NewEmptyCondition().SetPattern("brand: {facet:brand}").SetAnchoring(search.Anchoring("contains")).SetAlternatives(false),
      }).
      SetConsequence(
        search.NewEmptyConsequence().SetParams(
          search.NewEmptyConsequenceParams().SetAutomaticFacetFilters(search.ArrayOfAutomaticFacetFilterAsAutomaticFacetFilters(
            []search.AutomaticFacetFilter{
              *search.NewEmptyAutomaticFacetFilter().SetFacet("brand"),
            },
          )).SetQuery(search.ConsequenceQueryObjectAsConsequenceQuery(
            search.NewEmptyConsequenceQueryObject().SetRemove(
              []string{"brand:", "{facet:brand}"}))))).SetDescription("filter on brand: {brand}").SetObjectID("tagged-brand-rule")))
  if err != nil {
    // handle the eventual error
    panic(err)
  }
  ```

  ```java Java theme={"system"}
  UpdatedAtResponse response = client.saveRule(
    "INDEX_NAME",
    "tagged-brand-rule",
    new Rule()
      .setConditions(
        Arrays.asList(new Condition().setPattern("brand: {facet:brand}").setAnchoring(Anchoring.CONTAINS).setAlternatives(false))
      )
      .setConsequence(
        new Consequence().setParams(
          new ConsequenceParams()
            .setAutomaticFacetFilters(
              AutomaticFacetFilters.ofListOfAutomaticFacetFilter(Arrays.asList(new AutomaticFacetFilter().setFacet("brand")))
            )
            .setQuery(new ConsequenceQueryObject().setRemove(Arrays.asList("brand:", "{facet:brand}")))
        )
      )
      .setDescription("filter on brand: {brand}")
      .setObjectID("tagged-brand-rule")
  );
  ```

  ```js JavaScript theme={"system"}
  const response = await client.saveRule({
    indexName: 'indexName',
    objectID: 'tagged-brand-rule',
    rule: {
      conditions: [{ pattern: 'brand: {facet:brand}', anchoring: 'contains', alternatives: false }],
      consequence: {
        params: { automaticFacetFilters: [{ facet: 'brand' }], query: { remove: ['brand:', '{facet:brand}'] } },
      },
      description: 'filter on brand: {brand}',
      objectID: 'tagged-brand-rule',
    },
  });
  ```

  ```kotlin Kotlin theme={"system"}
  var response =
    client.saveRule(
      indexName = "INDEX_NAME",
      objectID = "tagged-brand-rule",
      rule =
        Rule(
          conditions =
            listOf(
              Condition(
                pattern = "brand: {facet:brand}",
                anchoring = Anchoring.entries.first { it.value == "contains" },
                alternatives = false,
              )
            ),
          consequence =
            Consequence(
              params =
                ConsequenceParams(
                  automaticFacetFilters =
                    AutomaticFacetFilters.ofListOfAutomaticFacetFilter(
                      listOf(AutomaticFacetFilter(facet = "brand"))
                    ),
                  query = ConsequenceQueryObject(remove = listOf("brand:", "{facet:brand}")),
                )
            ),
          description = "filter on brand: {brand}",
          objectID = "tagged-brand-rule",
        ),
    )
  ```

  ```php PHP theme={"system"}
  $response = $client->saveRule(
      'INDEX_NAME',
      'tagged-brand-rule',
      ['conditions' => [
          ['pattern' => 'brand: {facet:brand}',
              'anchoring' => 'contains',
              'alternatives' => false,
          ],
      ],
          'consequence' => ['params' => ['automaticFacetFilters' => [
              ['facet' => 'brand',
              ],
          ],
              'query' => ['remove' => [
                  'brand:',

                  '{facet:brand}',
              ],
              ],
          ],
          ],
          'description' => 'filter on brand: {brand}',
          'objectID' => 'tagged-brand-rule',
      ],
  );
  ```

  ```python Python theme={"system"}
  response = client.save_rule(
      index_name="INDEX_NAME",
      object_id="tagged-brand-rule",
      rule={
          "conditions": [
              {
                  "pattern": "brand: {facet:brand}",
                  "anchoring": "contains",
                  "alternatives": False,
              },
          ],
          "consequence": {
              "params": {
                  "automaticFacetFilters": [
                      {
                          "facet": "brand",
                      },
                  ],
                  "query": {
                      "remove": [
                          "brand:",
                          "{facet:brand}",
                      ],
                  },
              },
          },
          "description": "filter on brand: {brand}",
          "objectID": "tagged-brand-rule",
      },
  )
  ```

  ```ruby Ruby theme={"system"}
  response = client.save_rule(
    "INDEX_NAME",
    "tagged-brand-rule",
    Algolia::Search::Rule.new(
      conditions: [
        Algolia::Search::Condition.new(pattern: "brand: {facet:brand}", anchoring: "contains", alternatives: false)
      ],
      consequence: Algolia::Search::Consequence.new(
        params: Algolia::Search::ConsequenceParams.new(
          automatic_facet_filters: [Algolia::Search::AutomaticFacetFilter.new(facet: "brand")],
          query: Algolia::Search::ConsequenceQueryObject.new(remove: ["brand:", "{facet:brand}"])
        )
      ),
      description: "filter on brand: {brand}",
      algolia_object_id: "tagged-brand-rule"
    )
  )
  ```

  ```scala Scala theme={"system"}
  val response = Await.result(
    client.saveRule(
      indexName = "INDEX_NAME",
      objectID = "tagged-brand-rule",
      rule = Rule(
        conditions = Some(
          Seq(
            Condition(
              pattern = Some("brand: {facet:brand}"),
              anchoring = Some(Anchoring.withName("contains")),
              alternatives = Some(false)
            )
          )
        ),
        consequence = Consequence(
          params = Some(
            ConsequenceParams(
              automaticFacetFilters = Some(
                AutomaticFacetFilters(
                  Seq(
                    AutomaticFacetFilter(
                      facet = "brand"
                    )
                  )
                )
              ),
              query = Some(
                ConsequenceQueryObject(
                  remove = Some(Seq("brand:", "{facet:brand}"))
                )
              )
            )
          )
        ),
        description = Some("filter on brand: {brand}"),
        objectID = "tagged-brand-rule"
      )
    ),
    Duration(100, "sec")
  )
  ```

  ```swift Swift theme={"system"}
  let response = try await client.saveRule(
      indexName: "INDEX_NAME",
      objectID: "tagged-brand-rule",
      rule: Rule(
          objectID: "tagged-brand-rule",
          conditions: [SearchCondition(
              pattern: "brand: {facet:brand}",
              anchoring: SearchAnchoring.contains,
              alternatives: false
          )],
          consequence: SearchConsequence(params: SearchConsequenceParams(
              query: SearchConsequenceQuery.searchConsequenceQueryObject(SearchConsequenceQueryObject(remove: [
                  "brand:",
                  "{facet:brand}",
              ])),
              automaticFacetFilters: SearchAutomaticFacetFilters
                  .arrayOfSearchAutomaticFacetFilter([SearchAutomaticFacetFilter(facet: "brand")])
          )),
          description: "filter on brand: {brand}"
      )
  )
  ```
</CodeGroup>

## Example dataset

All the examples on this page use a product catalog index.
The appropriate attributes are set as [attributes for faceting](/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting-with-dashboard).
The index has records that look like this:

```json JSON icon=braces theme={"system"}
[
  {
    "product_name": "FM",
    "product_type": "T-shirt",
    "brand": "LondonLook",
    "color": "Red",
    "price": 21.99
  },
  {
    "product_name": "Caveman",
    "product_type": "T-shirt",
    "brand": "Red or Dead",
    "color": "Brown",
    "price": 9.99
  },
  {
    "product_name": "iPhone 13 Pro Max",
    "product_type": "Phone",
    "brand": "Apple",
    "color": "Blue",
    "price": 1824.61
  },
  {
    "product_name": "Will Carpenter",
    "product_type": "T-shirt",
    "brand": "Red or Dead",
    "color": "Black",
    "price": 199.99
  },
  {
    "product_name": "The Mandal 800w",
    "product_type": "Toaster",
    "brand": "Black & Decker",
    "color": "Red",
    "price": 149.99
  },
  {
    "product_name": "Essentials 800w",
    "product_type": "Toaster",
    "brand": "Daewoo",
    "color": "Black",
    "price": 14.99
  },
  {
    "product_name": "Airpods Max",
    "product_type": "Headphones",
    "brand": "Apple",
    "color": "Gray",
    "price": 548.99
  },
  {
    "product_name": "WH-CH520",
    "product_type": "Headphones",
    "brand": "Sony",
    "color": "Apple",
    "price": 39.99
  }
]
```

## See also

* [Adding filters based on the query](/doc/guides/managing-results/rules/detecting-intent/how-to/applying-a-custom-filter-for-a-specific-query)
* [Faceting](/doc/guides/managing-results/refine-results/faceting#conjunctive-and-disjunctive-faceting)
