Guides / Managing results / Refine results / Sorting results

Sort an Index Alphabetically

Having constantly seen data sorted alphabetically, you may find yourself wanting to follow suit. However, while sorting alphabetically makes sense for a database, it doesn’t for a search engine and we strongly discourage it. This isn’t to say your use case is invalid; rather, we want to encourage caution and due consideration.

When you sort your data alphabetically, you don’t only devalue Algolia’s tie-breaking algorithm: you essentially disable it. If you sort alphabetically first, then the only objects requiring tie-breaking are those with the exact same name: there will likely be few objects that fit this criterea.

Alphabetically structured results lead users to search through data by hand, while a search engine, like Algolia, should ensure that they don’t need to.

Since sorting your data alphabetically disables Algolia’s tie-breaking, it’s best to give users this type of sort as an option and not as the default experience. To provide different sorting options, you should use replica indices.

Warnings aside, it’s still possible to sort alphabetically by using the customRanking parameter with the attribute you want to sort on. If you are sorting alphabetically on a non-replica index, the method is the same as for a standard replica.

Using the API

Standard replicas

To sort a standard replica or non-replica index alphabetically, you need to change its custom ranking, and set custom as the index’s first ranking criterion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$index->setSettings([
   'customRanking' => [
     'asc(textual_attribute)'
   ],
   'ranking' => [
      'custom',
      'typo',
      'geo',
      'words',
      'filters',
      'proximity',
      'attribute',
      'exact'
    ]
]);

Virtual replicas

If you would like to use virtual replicas for a strict alphabetical sort where other relevancy factors aren’t taken into account, you must set relevancyStrictness to 0. You must also set the replica’s custom ranking with the attributes you’d like to sort on.

1
2
3
4
5
6
$index->setSettings([
   'customRanking' => [
     'asc(textual_attribute)'
   ],
   'relevancyStrictness' => 0
]);

Caveats

Algolia isn’t locale-aware. Strings are ordered by the lexicographical order of their first 50 Unicode characters. That may be acceptable for English text, less so for other languages (especially those with diacritics).

Did you find this page helpful?