What are Rules?
Rules can be used to create a flexible Search that gives you control over the results that are displayed in different scenarios. Rules let you make precise, predetermined changes to your search results.
The Rule context provides an extra scope to your Rule condition. There are cases where 'Query is', 'Query contains', Filters, etc. are not enough to give the necessary scope to a Rule. Its in these situations that Rule contexts can provide an extra layer of scope, in a very flexible way.
More information in this documentation: Rules responding to user context
Using a Rule context requires the addition of code to your Algolia implementation, so may require the involvement of a front-end developer.
When to use Rule contexts
The use cases vary, but ultimately, you should normally use Rule context when you want to target a rule for specific situations. For example, based on the section of the website that the user is visiting, or the type of device they are using.
This feature allows you to scope the trigger of your Rule from your own code using your own logic. You can create logic to decide whether to pass a ruleContexts parameter or not.
How to implement Rule contexts
Follow the steps below to implement your Rule contexts:
1 - Setting a context on your Rule condition
You can use Rule contexts with both a visual editor Rule and a manual editor Rule. In the context section of the condition, add any string of your choice for your context:
Once the Rule has been created, with all the required conditions and consequences, you can trigger it by passing the context string you created to the
ruleContexts parameter in your Search requests (e.g.
example_string in this example)
2 - Passing the string value to the ruleContexts parameter
ruleContexts query parameter is just one of the many Search API parameters that you can add to your Search requests. Depending on your implementation, there are different ways to pass Search API parameters to your queries.
To illustrate with an example, this is how it would be implemented for InstantSearch.
configure widget, pass
If implemented correctly, you should be able to see this parameter on your Search request payload:
- To set a Rule Context, the first step is to add a string value in the 'Context' section of your Rule condition.
- This condition will be matched when you pass the exact same string value to the ruleContexts query parameter with your Search requests.