Guides / Managing results / Refine results / Sorting results

Sort By Attribute

By design, Algolia provides one ranking formula per index: when you want to provide different rankings for the same data you need to use different indices for each ranking. These additional indices are called replicas.

If you want to set up sort by attribute it is important that you understand replica indices.

To sort by attribute, you will first need to create a replica index and then modify the ranking formula of the replica. This can be done through the Dashboard and the API.

This guide will help you set up the necessary back end for sorting by attribute, but you need to configure your front end (with widgets or custom logic) to make the option accessible to your users.

Attribute format

Attributes used for sorting must have boolean or numerical values. You cannot use a string attribute and dates must be represented as numbers.

Numerical values should be indexed as actual numbers, not strings.

Using the API

1. Creating a replica

To create replicas, you need to use the setSettings method on your primary index. You can add more than one replica at a time if you want to provide multiple alternative sorting strategies.

1
2
3
4
5
$index->setSettings([
  'replicas' => [
    'products_price_desc'
  ]
]);

2. Changing replica settings

To change a replica’s settings:

  1. Initialize the replica.
  2. Use setSettings to change the replica’s setting.

In the example below, the products_price_desc index is sorted by price, descending.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$replica_index = $client->initIndex('products_price_desc');

$replica_index->setSettings([
  'ranking' => [
    'desc(price)',
    'typo',
    'geo',
    'words',
    'filters',
    'proximity',
    'attribute',
    'exact',
    'custom'
  ]
]);

Using the Dashboard

1. Creating a replica

Creating a replica through the dashboard

  1. Go to your dashboard and select your index.
  2. Click the Replicas tab.
  3. Click the “Create Replica Index” button, type a name for your replica and press Enter.
  4. Repeat for all additional replicas you want to add.
  5. Don’t forget to save your changes.

2. Changing replica settings

Changing a replica's settings through the dashboard

  1. Select your replica index.
  2. Click the Ranking tab.
  3. In the Ranking Formula & Custom Ranking section, use the Sort-By function to add the attribute you want to sort by and select either DESC or ASC.
  4. Don’t forget to save your changes.

Did you find this page helpful?