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

# Add filters based on the query

> Applying a custom filter for a specific query

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>;

Sometimes, specific terms can act as cues that you can use to filter search results.
You can use positive, negative, or numerical filters:

* [**Positive filters**](#positive-filters) include a specific subset of matching records in the results. For example, if a user types "diet" on a restaurant website, return every record that has "low-carb" or "low-fat".
* [**Negative filters**](#negative-filters) exclude matching records from results. For example, if a user types "gluten-free" on a restaurant website, you could filter out any gluten-containing meal.
* [**Numerical filters**](#numerical-filters) convert text queries into a numerical range. For example, if a user types "cheap" on a website for kitchen appliances, you could filter out anything costing more than \$50.

## Positive filters

If you want to filter out every non-diet-friendly meal whenever user's search queries contain the term "diet",
you could use the [`_tags`](/doc/guides/managing-results/refine-results/filtering/how-to/filter-by-attributes#filter-by-tags) attribute to categorize meals depending on their individual qualities:

```json JSON icon=braces theme={"system"}
[
  {
    "name": "Chicken Stuffed Baked Avocados",
    "restaurant": "The Hive",
    "_tags": ["low-carb"]
  },
  {
    "name": "Spinach Quiche",
    "restaurant": "Bert's Inn",
    "_tags": ["low-carb", "vegetarian"]
  },
  {
    "name": "Pizza Chicken Bake",
    "restaurant": "Millbrook Deli",
    "_tags": ["cheese"]
  },
  {
    "name": "Strawberry Sorbet",
    "restaurant": "The Hive",
    "_tags": ["low-fat", "vegetarian", "vegan"]
  }
]
```

When users include the term "diet" in their search, you want to automatically return every record that has "low-carb" or "low-fat" in their `_tags` attribute. Because `_tags` is already optimized for filtering, you don't have to set it as an attribute for faceting. You can directly create a new Rule that detects the term "diet" in a query and applies a positive filter on tags "low-carb" and "low-fat".

<Tip>
  To use the term "diet" only for filtering and not as a search term,
  add a consequence in your rule to remove the word from your query.
</Tip>

### Using the API

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

To add a rule, use the [`saveRule`](/doc/libraries/sdk/v1/methods/save-rule) method.
When creating a rule, you must define a condition and a consequence.

<CodeGroup>
  ```cs C# theme={"system"}
  var response = await client.SaveRuleAsync(
    "INDEX_NAME",
    "diet-rule",
    new Rule
    {
      ObjectID = "diet-rule",
      Conditions = new List<Condition>
      {
        new Condition { Pattern = "diet", Anchoring = Enum.Parse<Anchoring>("Contains") },
      },
      Consequence = new Consequence
      {
        Params = new ConsequenceParams
        {
          Filters = "'low-carb' OR 'low-fat'",
          Query = new ConsequenceQuery(
            new ConsequenceQueryObject
            {
              Edits = new List<Edit>
              {
                new Edit { Type = Enum.Parse<EditType>("Remove"), Delete = "diet" },
              },
            }
          ),
        },
      },
    }
  );
  ```

  ```dart Dart theme={"system"}
  final response = await client.saveRule(
    indexName: "INDEX_NAME",
    objectID: "diet-rule",
    rule: Rule(
      objectID: "diet-rule",
      conditions: [
        Condition(
          pattern: "diet",
          anchoring: Anchoring.fromJson("contains"),
        ),
      ],
      consequence: Consequence(
        params: ConsequenceParams(
          filters: "'low-carb' OR 'low-fat'",
          query: ConsequenceQueryObject(
            edits: [
              Edit(
                type: EditType.fromJson("remove"),
                delete: "diet",
              ),
            ],
          ),
        ),
      ),
    ),
  );
  ```

  ```go Go theme={"system"}
  response, err := client.SaveRule(client.NewApiSaveRuleRequest(
    "INDEX_NAME", "diet-rule",
    search.NewEmptyRule().SetObjectID("diet-rule").SetConditions(
      []search.Condition{*search.NewEmptyCondition().SetPattern("diet").SetAnchoring(search.Anchoring("contains"))}).SetConsequence(
      search.NewEmptyConsequence().SetParams(
        search.NewEmptyConsequenceParams().SetFilters("'low-carb' OR 'low-fat'").SetQuery(search.ConsequenceQueryObjectAsConsequenceQuery(
          search.NewEmptyConsequenceQueryObject().SetEdits(
            []search.Edit{*search.NewEmptyEdit().SetType(search.EditType("remove")).SetDelete("diet")})))))))
  if err != nil {
    // handle the eventual error
    panic(err)
  }
  ```

  ```java Java theme={"system"}
  UpdatedAtResponse response = client.saveRule(
    "INDEX_NAME",
    "diet-rule",
    new Rule()
      .setObjectID("diet-rule")
      .setConditions(Arrays.asList(new Condition().setPattern("diet").setAnchoring(Anchoring.CONTAINS)))
      .setConsequence(
        new Consequence().setParams(
          new ConsequenceParams()
            .setFilters("'low-carb' OR 'low-fat'")
            .setQuery(new ConsequenceQueryObject().setEdits(Arrays.asList(new Edit().setType(EditType.REMOVE).setDelete("diet"))))
        )
      )
  );
  ```

  ```js JavaScript theme={"system"}
  const response = await client.saveRule({
    indexName: 'indexName',
    objectID: 'diet-rule',
    rule: {
      objectID: 'diet-rule',
      conditions: [{ pattern: 'diet', anchoring: 'contains' }],
      consequence: {
        params: { filters: "'low-carb' OR 'low-fat'", query: { edits: [{ type: 'remove', delete: 'diet' }] } },
      },
    },
  });
  ```

  ```kotlin Kotlin theme={"system"}
  var response =
    client.saveRule(
      indexName = "INDEX_NAME",
      objectID = "diet-rule",
      rule =
        Rule(
          objectID = "diet-rule",
          conditions =
            listOf(
              Condition(
                pattern = "diet",
                anchoring = Anchoring.entries.first { it.value == "contains" },
              )
            ),
          consequence =
            Consequence(
              params =
                ConsequenceParams(
                  filters = "'low-carb' OR 'low-fat'",
                  query =
                    ConsequenceQueryObject(
                      edits =
                        listOf(
                          Edit(
                            type = EditType.entries.first { it.value == "remove" },
                            delete = "diet",
                          )
                        )
                    ),
                )
            ),
        ),
    )
  ```

  ```php PHP theme={"system"}
  $response = $client->saveRule(
      'INDEX_NAME',
      'diet-rule',
      ['objectID' => 'diet-rule',
          'conditions' => [
              ['pattern' => 'diet',
                  'anchoring' => 'contains',
              ],
          ],
          'consequence' => ['params' => ['filters' => "'low-carb' OR 'low-fat'",
              'query' => ['edits' => [
                  ['type' => 'remove',
                      'delete' => 'diet',
                  ],
              ],
              ],
          ],
          ],
      ],
  );
  ```

  ```python Python theme={"system"}
  response = client.save_rule(
      index_name="INDEX_NAME",
      object_id="diet-rule",
      rule={
          "objectID": "diet-rule",
          "conditions": [
              {
                  "pattern": "diet",
                  "anchoring": "contains",
              },
          ],
          "consequence": {
              "params": {
                  "filters": "'low-carb' OR 'low-fat'",
                  "query": {
                      "edits": [
                          {
                              "type": "remove",
                              "delete": "diet",
                          },
                      ],
                  },
              },
          },
      },
  )
  ```

  ```ruby Ruby theme={"system"}
  response = client.save_rule(
    "INDEX_NAME",
    "diet-rule",
    Algolia::Search::Rule.new(
      algolia_object_id: "diet-rule",
      conditions: [Algolia::Search::Condition.new(pattern: "diet", anchoring: "contains")],
      consequence: Algolia::Search::Consequence.new(
        params: Algolia::Search::ConsequenceParams.new(
          filters: "'low-carb' OR 'low-fat'",
          query: Algolia::Search::ConsequenceQueryObject.new(
            edits: [Algolia::Search::Edit.new(type: "remove", delete: "diet")]
          )
        )
      )
    )
  )
  ```

  ```scala Scala theme={"system"}
  val response = Await.result(
    client.saveRule(
      indexName = "INDEX_NAME",
      objectID = "diet-rule",
      rule = Rule(
        objectID = "diet-rule",
        conditions = Some(
          Seq(
            Condition(
              pattern = Some("diet"),
              anchoring = Some(Anchoring.withName("contains"))
            )
          )
        ),
        consequence = Consequence(
          params = Some(
            ConsequenceParams(
              filters = Some("'low-carb' OR 'low-fat'"),
              query = Some(
                ConsequenceQueryObject(
                  edits = Some(
                    Seq(
                      Edit(
                        `type` = Some(EditType.withName("remove")),
                        delete = Some("diet")
                      )
                    )
                  )
                )
              )
            )
          )
        )
      )
    ),
    Duration(100, "sec")
  )
  ```

  ```swift Swift theme={"system"}
  let response = try await client.saveRule(
      indexName: "INDEX_NAME",
      objectID: "diet-rule",
      rule: Rule(
          objectID: "diet-rule",
          conditions: [SearchCondition(pattern: "diet", anchoring: SearchAnchoring.contains)],
          consequence: SearchConsequence(params: SearchConsequenceParams(
              filters: "'low-carb' OR 'low-fat'",
              query: SearchConsequenceQuery
                  .searchConsequenceQueryObject(SearchConsequenceQueryObject(edits: [SearchEdit(
                      type: SearchEditType.remove,
                      delete: "diet"
                  )]))
          ))
      )
  )
  ```
</CodeGroup>

### Using the dashboard

You can add rules from the Algolia 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.

4. On the [**Rules**](https://dashboard.algolia.com/rules) page,
   click **Create your first rule** or **New rule** and select **Manual Editor**.

5. In the **Condition(s)** sections, keep **Query contains** and enter "diet" in the input.

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

   1. Click the **Add consequence** button and select **Add Query Parameter**.
   2. In the input, enter the JSON search parameter you want to add. For example: `{ "filters": "'low-carb' OR 'low-fat'" }`.
   3. Click the **Add consequence** button again and select **Remove Word**.
   4. Type or select "diet" in the input field.

7. Save your changes.

## Negative filters

To exclude gluten-containing foods from the search results when a user searches for gluten-free meals, do the following:

1. Create an `allergens` attribute (with "gluten" as one of the potential values).
2. Create a rule that filters out records with "gluten" in that attribute.

### Example records

```json JSON icon=braces theme={"system"}
[
  {
    "name": "Pasta Bolognese",
    "restaurant": "Millbrook Deli",
    "allergens": ["eggs", "lactose"]
  },
  {
    "name": "Breakfast Waffles",
    "restaurant": "The Hive",
    "allergens": ["gluten", "lactose"]
  }
]
```

### Using the API

Set `allergens` as an [`attributesForFaceting`](/doc/api-reference/api-parameters/attributesForFaceting) in your index:

<CodeGroup>
  ```cs C# theme={"system"}
  var response = await client.SetSettingsAsync(
    "INDEX_NAME",
    new IndexSettings { AttributesForFaceting = new List<string> { "allergens" } }
  );
  ```

  ```dart Dart theme={"system"}
  final response = await client.setSettings(
    indexName: "INDEX_NAME",
    indexSettings: IndexSettings(
      attributesForFaceting: [
        "allergens",
      ],
    ),
  );
  ```

  ```go Go theme={"system"}
  response, err := client.SetSettings(client.NewApiSetSettingsRequest(
    "INDEX_NAME",
    search.NewEmptyIndexSettings().SetAttributesForFaceting(
      []string{"allergens"})))
  if err != nil {
    // handle the eventual error
    panic(err)
  }
  ```

  ```java Java theme={"system"}
  UpdatedAtResponse response = client.setSettings(
    "INDEX_NAME",
    new IndexSettings().setAttributesForFaceting(Arrays.asList("allergens"))
  );
  ```

  ```js JavaScript theme={"system"}
  const response = await client.setSettings({
    indexName: 'INDEX_NAME',
    indexSettings: { attributesForFaceting: ['allergens'] },
  });
  ```

  ```kotlin Kotlin theme={"system"}
  var response =
    client.setSettings(
      indexName = "INDEX_NAME",
      indexSettings = IndexSettings(attributesForFaceting = listOf("allergens")),
    )
  ```

  ```php PHP theme={"system"}
  $response = $client->setSettings(
      'INDEX_NAME',
      ['attributesForFaceting' => [
          'allergens',
      ],
      ],
  );
  ```

  ```python Python theme={"system"}
  response = client.set_settings(
      index_name="INDEX_NAME",
      index_settings={
          "attributesForFaceting": [
              "allergens",
          ],
      },
  )
  ```

  ```ruby Ruby theme={"system"}
  response = client.set_settings(
    "INDEX_NAME",
    Algolia::Search::IndexSettings.new(attributes_for_faceting: ["allergens"])
  )
  ```

  ```scala Scala theme={"system"}
  val response = Await.result(
    client.setSettings(
      indexName = "INDEX_NAME",
      indexSettings = IndexSettings(
        attributesForFaceting = Some(Seq("allergens"))
      )
    ),
    Duration(100, "sec")
  )
  ```

  ```swift Swift theme={"system"}
  let response = try await client.setSettings(
      indexName: "INDEX_NAME",
      indexSettings: IndexSettings(attributesForFaceting: ["allergens"])
  )
  ```
</CodeGroup>

* Use the [`saveRule`](/doc/libraries/sdk/v1/methods/save-rule) method to create a rule that detects the term "gluten-free" in a query and applies a negative filter on facet value `allergens:gluten`.
* Add a consequence in your rule to remove the word "gluten-free" from your query. This way, it won't be used as a search term, only for filtering purposes.

<CodeGroup>
  ```cs C# theme={"system"}
  var response = await client.SaveRuleAsync(
    "INDEX_NAME",
    "gluten-free-rule",
    new Rule
    {
      ObjectID = "gluten-free-rule",
      Conditions = new List<Condition>
      {
        new Condition { Pattern = "gluten-free", Anchoring = Enum.Parse<Anchoring>("Contains") },
      },
      Consequence = new Consequence
      {
        Params = new ConsequenceParams
        {
          Filters = "NOT allergens:gluten",
          Query = new ConsequenceQuery(
            new ConsequenceQueryObject
            {
              Edits = new List<Edit>
              {
                new Edit { Type = Enum.Parse<EditType>("Remove"), Delete = "gluten-free" },
              },
            }
          ),
        },
      },
    }
  );
  ```

  ```dart Dart theme={"system"}
  final response = await client.saveRule(
    indexName: "INDEX_NAME",
    objectID: "gluten-free-rule",
    rule: Rule(
      objectID: "gluten-free-rule",
      conditions: [
        Condition(
          pattern: "gluten-free",
          anchoring: Anchoring.fromJson("contains"),
        ),
      ],
      consequence: Consequence(
        params: ConsequenceParams(
          filters: "NOT allergens:gluten",
          query: ConsequenceQueryObject(
            edits: [
              Edit(
                type: EditType.fromJson("remove"),
                delete: "gluten-free",
              ),
            ],
          ),
        ),
      ),
    ),
  );
  ```

  ```go Go theme={"system"}
  response, err := client.SaveRule(client.NewApiSaveRuleRequest(
    "INDEX_NAME", "gluten-free-rule",
    search.NewEmptyRule().SetObjectID("gluten-free-rule").SetConditions(
      []search.Condition{*search.NewEmptyCondition().SetPattern("gluten-free").SetAnchoring(search.Anchoring("contains"))}).SetConsequence(
      search.NewEmptyConsequence().SetParams(
        search.NewEmptyConsequenceParams().SetFilters("NOT allergens:gluten").SetQuery(search.ConsequenceQueryObjectAsConsequenceQuery(
          search.NewEmptyConsequenceQueryObject().SetEdits(
            []search.Edit{*search.NewEmptyEdit().SetType(search.EditType("remove")).SetDelete("gluten-free")})))))))
  if err != nil {
    // handle the eventual error
    panic(err)
  }
  ```

  ```java Java theme={"system"}
  UpdatedAtResponse response = client.saveRule(
    "INDEX_NAME",
    "gluten-free-rule",
    new Rule()
      .setObjectID("gluten-free-rule")
      .setConditions(Arrays.asList(new Condition().setPattern("gluten-free").setAnchoring(Anchoring.CONTAINS)))
      .setConsequence(
        new Consequence().setParams(
          new ConsequenceParams()
            .setFilters("NOT allergens:gluten")
            .setQuery(new ConsequenceQueryObject().setEdits(Arrays.asList(new Edit().setType(EditType.REMOVE).setDelete("gluten-free"))))
        )
      )
  );
  ```

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

  ```kotlin Kotlin theme={"system"}
  var response =
    client.saveRule(
      indexName = "INDEX_NAME",
      objectID = "gluten-free-rule",
      rule =
        Rule(
          objectID = "gluten-free-rule",
          conditions =
            listOf(
              Condition(
                pattern = "gluten-free",
                anchoring = Anchoring.entries.first { it.value == "contains" },
              )
            ),
          consequence =
            Consequence(
              params =
                ConsequenceParams(
                  filters = "NOT allergens:gluten",
                  query =
                    ConsequenceQueryObject(
                      edits =
                        listOf(
                          Edit(
                            type = EditType.entries.first { it.value == "remove" },
                            delete = "gluten-free",
                          )
                        )
                    ),
                )
            ),
        ),
    )
  ```

  ```php PHP theme={"system"}
  $response = $client->saveRule(
      'INDEX_NAME',
      'gluten-free-rule',
      ['objectID' => 'gluten-free-rule',
          'conditions' => [
              ['pattern' => 'gluten-free',
                  'anchoring' => 'contains',
              ],
          ],
          'consequence' => ['params' => ['filters' => 'NOT allergens:gluten',
              'query' => ['edits' => [
                  ['type' => 'remove',
                      'delete' => 'gluten-free',
                  ],
              ],
              ],
          ],
          ],
      ],
  );
  ```

  ```python Python theme={"system"}
  response = client.save_rule(
      index_name="INDEX_NAME",
      object_id="gluten-free-rule",
      rule={
          "objectID": "gluten-free-rule",
          "conditions": [
              {
                  "pattern": "gluten-free",
                  "anchoring": "contains",
              },
          ],
          "consequence": {
              "params": {
                  "filters": "NOT allergens:gluten",
                  "query": {
                      "edits": [
                          {
                              "type": "remove",
                              "delete": "gluten-free",
                          },
                      ],
                  },
              },
          },
      },
  )
  ```

  ```ruby Ruby theme={"system"}
  response = client.save_rule(
    "INDEX_NAME",
    "gluten-free-rule",
    Algolia::Search::Rule.new(
      algolia_object_id: "gluten-free-rule",
      conditions: [Algolia::Search::Condition.new(pattern: "gluten-free", anchoring: "contains")],
      consequence: Algolia::Search::Consequence.new(
        params: Algolia::Search::ConsequenceParams.new(
          filters: "NOT allergens:gluten",
          query: Algolia::Search::ConsequenceQueryObject.new(
            edits: [Algolia::Search::Edit.new(type: "remove", delete: "gluten-free")]
          )
        )
      )
    )
  )
  ```

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

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

### Using the dashboard

You can also add rules from the Algolia 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 open the **Configuration** tab.

4. On the **Filtering and Faceting > Facets** page, click **Add an attribute** and select the `allergens` attribute.

5. On the **Rules** tab, click **Create your first rule** or **New rule** and select **Manual Editor**.

6. In the **Condition(s)** section, keep **Query** toggled on, select **Contains**, and enter `gluten-free` in the input.

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

   1. Click the **Add consequence** button and select **Add Query Parameter**.
   2. In the input field that appears, enter the JSON search parameter you want to add. For example: `{ "filters": "NOT allergens:gluten" }`
   3. Click the **Add consequence** button again and select **Remove Word**.
   4. Enter `gluten-free` in the input.

8. Save your changes.

## Numerical filters

Consider the query "cheap toaster 800w".
You can use Rules to filter the results by "toaster" and "prices between 0 and 25" so that the only textual search is the remaining term,
"800w", which could further be used to limit the results with that wattage.

### Rule

If `query = "cheap toaster"` then `price < 10` and `type=toaster`.

<Note>
  This requires two rules.
</Note>

### Using the API

<CodeGroup>
  ```cs C# theme={"system"}
  var response = await client.SaveRuleAsync(
    "INDEX_NAME",
    "cheap",
    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 < 10",
        },
      },
    }
  );
  ```

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

  ```go Go theme={"system"}
  response, err := client.SaveRule(client.NewApiSaveRuleRequest(
    "INDEX_NAME", "cheap",
    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 < 10")))))
  if err != nil {
    // handle the eventual error
    panic(err)
  }
  ```

  ```java Java theme={"system"}
  UpdatedAtResponse response = client.saveRule(
    "INDEX_NAME",
    "cheap",
    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 < 10")
        )
      )
  );
  ```

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

  ```kotlin Kotlin theme={"system"}
  var response =
    client.saveRule(
      indexName = "INDEX_NAME",
      objectID = "cheap",
      rule =
        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 < 10",
                )
            ),
        ),
    )
  ```

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

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

  ```ruby Ruby theme={"system"}
  response = client.save_rule(
    "INDEX_NAME",
    "cheap",
    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 < 10"
        )
      )
    )
  )
  ```

  ```scala Scala theme={"system"}
  val response = Await.result(
    client.saveRule(
      indexName = "INDEX_NAME",
      objectID = "cheap",
      rule = 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 < 10")
            )
          )
        )
      )
    ),
    Duration(100, "sec")
  )
  ```

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

### Using the dashboard

Since there are two rules, you must set up both separately.

#### Preparation

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 open the **Configuration** tab.
4. On the **Filtering and Facets** page,
   click **Add an attribute** and select the `product_type` attribute.

#### For the first rule

1. Go to the **[Rules](https://dashboard.algolia.com/rules)** in the Algolia dashboard.

2. Select **Create your first rule** or **New rule** and select **Manual Editor**.

3. In the **Condition(s)** section, keep **Query** toggled on, select **Contains**, and enter `toaster` in the input.

4. 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": "product_type:toaster" }`
   3. Click **Add consequence** again and select **Remove Word**.
   4. Enter "toaster" in the input.

5. Save your changes.

#### For the second rule

1. On the **Rules** page, click **New rule** and select **Manual Editor**.

2. In the **Condition(s)** section, keep **Query** toggled on, select **Contains**, and enter `cheap` in the input.

3. 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": "price<10" }`
   3. Click **Add consequence** again and select **Remove Word**.
   4. Enter `cheap` in the input.

4. Save your changes.

## See also

* [Faceting](/doc/guides/managing-results/refine-results/faceting)
* [Filtering](/doc/guides/managing-results/refine-results/filtering)
* [Merchandising](/doc/guides/managing-results/rules/merchandising-and-promoting)
