Search isn’t only about retrieving results. Sometimes, depending on what the user searches for, you may want to display custom data in your UI, like ads or promotional banners.

For example, imagine you sell books online, and you have a special discount that you want to show people who are looking for Harry Potter books. By leveraging Algolia’s Rules, you can return custom data whenever a user sends a specific query, and use it to display a banner on your website.

Creating a Rule

Let’s say we want to motivate customers to buy Harry Potter books, by displaying a special promotion whenever their search query contains “harry potter”. On top of the search results, we want to display a banner that says “20% OFF on all Harry Potter books!”.

For this, we first need to set a Rule that returns the custom data we want to display. Then, we need to display this data whenever it comes up.

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.

In our case, we want to show the banner whenever the query contains “harry potter”. We don’t want it to be exact. If the query is “harry potter azkaban” or “books harry potter”, we still want to display the promotion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$rule = array(
  'objectID' => 'harry-potter-rule',
  'condition' => array(
    'pattern'   => 'harry potter',
    'anchoring' => 'contains',
  ),
  'consequence' => array(
    'userData' => array(
      'promo_content' => '20% OFF on all Harry Potter books!'
    )
  )
);

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

Using the Dashboard

You can also add your Rules in your Algolia dashboard.

  • Go to your dashboard and select your index.
  • Click the Query Rules tab.
  • Click the New Rule button.
  • In the Condition section:
    • In the If the query… input field, set the anchoring to Contains.
    • Type “harry potter” in the input field and press Enter.
  • In the Consequences section:
    • Click the Add consequence button and select Return Custom Data.
    • In the Custom JSON Data panel that shows up, add the data to return when the user query matches the Rule: { "promo_content": "20% OFF on all Harry Potter books!" }
  • Click Save.

Retrieving the banner data in the Search UI

Now that your Rule is ready, you can add a banner in your search UI when the userData property is present in the API response. Here’s what it could look like with InstantSearch:

1
2
3
4
5
6
7
8
9
10
11
12
search.addWidgets([
  instantsearch.widgets.queryRuleCustomData({
    container: '#banner',
    templates: {
      default: `
        {{#items}}
          <p>{{promo_content}}</p>
        {{/items}}
      `,
    },
  })
]);

You can learn more about this widget in the InstantSearch API reference:

Applying Rules with context conditions

If you want to apply Rules based on filters, have a look at:

Did you find this page helpful?