Guides / Managing results / Rules / Detecting intent

Adding filters based on the query

Sometimes, specific terms can act as cues that you can use to filter down the hits that your users get.

Consider a restaurant’s website where users can search for meals and get them delivered to their home. If a user types “gluten-free”, you could use this term to filter out any meal that has “gluten” in its list of allergens.

To do this, you can use Algolia’s Rules and trigger custom filters based on what users search for.

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 attribute to categorize meals depending on their individual qualities:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[
  {
    "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”.

You also need to add a consequence in your rule to remove the word “diet” from your query. This way, it won’t be used as a search term, only for filtering.

Using the API

To add a Rule, you need to use the saveRule method. When setting a Rule, you need to define a condition and a consequence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$rule = [
  'objectID' => 'diet-rule',
  'conditions' => array(array(
    'pattern'   => 'diet',
    'anchoring' => 'contains',
  )),
  'consequence' => [
    'params' => [
      'filters' => '"low-carb" OR "low-fat"',
      'query' => [
        'edits' => [
          [
            'type' => 'remove',
            'delete' => 'diet'
          ]
        ]
      ]
    ]
  ]
];

$response = $index->saveRule($rule);

Using the dashboard

You can also add your Rules in your Algolia dashboard.

  1. Select the Search product icon on your dashboard.
  2. Select the Rules section from the left sidebar menu in the Algolia dashboard.
  3. Under the heading Rules, select the index to which you’re adding a Rule.
  4. Select Create your first rule or New rule. In the dropdown, click the Manual Editor option.
  5. In the Condition(s) sections, keep Query contains and enter “diet” in the input field.
  6. In the Consequence(s) section:
    • Click the Add consequence button and select Add Query Parameter.
    • In the input field that appears, enter the JSON search parameter you want to add. For example: { "filters": "'low-carb' OR 'low-fat'" }.
    • Click the Add consequence button again and select Remove Word.
    • Type or select “diet” in the input field.
  7. Don’t forget to save your changes.

Negative filters

Consider filtering out every meal that’s not gluten-free when the users’ search queries include the term “gluten-free”.

You could add “Gluten-free” in the title (for example, “Gluten-free Pasta Dough”), but this would force you to do it for every meal that doesn’t contain gluten, even those that don’t typically do (for example, “Leek Soup” or “Fruit Salad”). When a user is looking for “gluten-free” meals, it’s safer to assume they want everything that matches their search and doesn’t have gluten, not that they’re looking for meals with the words “Gluten-free” in the title.

You could maintain a list of tags (with the special _tags attribute), but you may want to separate allergens, especially if you don’t want to make them searchable.

Instead, a better approach is to create a more definitive list of all allergens:

1
2
3
4
5
6
7
8
9
10
11
12
[
  {
    "name": "Pasta Bolognese",
    "restaurant": "Millbrook Deli",
    "allergens": ["eggs", "lactose"]
  },
  {
    "name": "Breakfast Waffles",
    "restaurant": "The Hive",
    "allergens": ["gluten", "lactose"]
  }
]

When users add “gluten-free” in their search, you want to automatically filter out every record with “gluten” in its allergens attribute. To do so, you first need to set allergens in your list of attributes for faceting. Then, you can create a new Rule that filters out unwanted records based on the allergens facet values.

Using the API

First, you must set allergens as an attributesForFaceting in your index:.

1
2
3
4
5
$index->setSettings([
  'attributesForFaceting' => [
    "allergens"
  ]
]);

Then, you can set a Rule that detects the term “gluten-free” in a query and applies a negative filter on facet value allergens:gluten. For this, you need to use the saveRule method.

You must also 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$rule = [
  'objectID' => 'gluten-free-rule',
  'conditions' => array(array(
    'pattern'   => 'gluten-free',
    'anchoring' => 'contains',
  ))
  'consequence' => [
    'params' => [
      'filters' => 'NOT allergens:gluten',
      'query' => [
        'edits' => [
          'type' => 'remove',
          'delete' => 'gluten-free'
        ]
      ]
    ]
  ]
];

$response = $index->saveRule($rule['objectID'], $rule);

Using the dashboard

You can also add your Rules in your Algolia dashboard.

  1. Select the Search product icon on your dashboard and then select your index.
  2. Click the Configuration tab.
  3. In the Facets subsection of Filtering and Faceting, click the “Add an attribute” button and select the allergens attribute from the dropdown.
  4. Click the Rules tab.
  5. Select Create your first rule or New rule. In the dropdown, click the Manual Editor option.
  6. In the Condition(s) section, keep Query toggled on, select Contains in the dropdown, and enter “gluten-free” in the input field.
  7. In the Consequence(s) section:
    • Click the Add consequence button and select Add Query Parameter.
    • In the input field that appears, enter the JSON search parameter you want to add. For example: { "filters": "NOT allergens:gluten" }
    • Click the Add consequence button again and select Remove Word.
    • Type or select “gluten-free” in the input field.
  8. Save your changes.

Numerical filtering

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

This requires two rules.

Using the API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Turn JSON into an array
$rules = array(
  array(
    'objectID' => 'cheap',
    'condition' => array(
      'pattern' => 'cheap',
      'anchoring' => 'contains'
    ),
    'consequence' => array(
      'params' => array(
        'query' => array(
          'remove' => 'cheap'
        ),
        'filters' => 'price < 10'
      )
    )
  )
);

// Push Rule to index
$index->batchRules($rules);

Using the dashboard

Since there are two Rules, you’ll need to set up both separately.

Preparation

  1. Select the Search product icon on your dashboard and then select your index.
  2. Click the Configuration tab.
  3. In the Facets subsection of Filtering and Faceting, click the “Add an attribute” button and select the product_type attribute from the dropdown.

For the first rule

  1. Select the Rules section from the left sidebar menu in the Algolia dashboard.
  2. Under the heading Rules, select the index to which you’re adding a rule.
  3. Select Create your first rule or New rule. In the dropdown, click the Manual Editor option.
  4. In the Condition(s) section, keep Query toggled on, select Contains in the dropdown, and enter “toaster” in the input field.
  5. In the Consequence(s) section:
    • Click the Add consequence button and select Add Query Parameter.
    • In the input field that appears, add the JSON parameters you want to apply when the user’s query matches the Rule: { "filters": "product_type:toaster" }
    • Click the Add consequence button again and select Remove Word.
    • Type or select “toaster” in the input field.
  6. Save your changes.

For the second rule

  1. Go back to the Rules section.
  2. Select New rule. In the dropdown, click the Manual Editor option.
  3. In the Condition(s) section, keep Query toggled on, select Contains in the dropdown, and enter “cheap” in the input field.
  4. In the Consequence(s) section:
    • Click the Add consequence button and select Add Query Parameter.
    • In the input field that appears, add the JSON parameters you want to apply when the user’s query matches the Rule: { "filters": "price<10" }
    • Click the Add consequence button again and select Remove Word.
    • Type or select “cheap” in the input field.
  5. Save your changes.
Did you find this page helpful?