Guides / Building Search UI / UI & UX patterns

Redirects in InstantSearch iOS

Introduction

When you create specific landing pages to display search results, it’s handy to be able to redirect users to those dedicated pages, in the situation where the search query matches one of them.

In this tutorial, we’ll see two methods for setting up redirects in an Algolia index: using Rules and using dedicated indices.

Using Rules

The best way to set up redirects is through Rules. You can add redirect information as custom data to any Rule. The Rule returns this data when a search activates it. You also need to add a custom QueryRuleCustomData widget that handles the Rule and redirects your user.

Configuring the Rule

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 the example below, we want to redirect whenever the query matches “star wars” exactly. If the query is “star wars lightsaber” or “books star wars”, we don’t want to redirect.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$rule = array(
  'objectID' => 'a-rule-id',
  'conditions' => array(array(
    'pattern' => 'star wars',
    'anchoring' => 'is'
  )),
  'consequence' => array(
    'userData' => array(
      'redirect' => 'https://www.google.com/#q=star+wars'
    )
  )
);

$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 and then select your index.
  2. Click the Rules tab.
  3. Select Create your first rule or New rule. In the dropdown, click on the Manual Editor option.
  4. In the Condition(s) section, keep Query toggled on, select Is in the dropdown and enter “star wars” in the input field.
  5. In the Consequence(s) section:
    • Click the Add consequence button and select Return Custom Data.
    • In the input field that appears, add the data to return when the user query matches the Rule: { "redirect": "https://www.google.com/#q=star+wars" }
  6. Don’t forget to save your changes.

Configuring the queryRuleCustomData widget

Now that everything is set up, you can use the QueryRuleCustomData widget to update the page location anytime userData contains a redirect.

1
2
3
4
5
6
7
8
9
10
11
let searcher HitsSearcher(appID: "YourApplicationID",
                          apiKey: "YourSearchOnlyAPIKey",
                          indexName: "YourIndexName")
    
let queryRuleCustomDataConnector = QueryRuleCustomDataConnector<Redirect>(searcher: searcher)

queryRuleCustomDataConnector.interactor.onItemChanged.subscribe(with: self) { (_, redirect) in
  if let redirectURL = redirect?.url {
    /// perform redirect with URL
  }
}
Did you find this page helpful?