Sort an index by date
How to sort your records by date.
By design, Algolia provides one ranking strategy per index: when you want to provide different rankings for the same data, you need to use different indices for each ranking. These indices are called replicas.
To set up sorting by attribute, you first need to understand how replica indices work.
To sort by attribute, create a replica index and then change the ranking formula of the replica. You can do this from Algolia’s dashboard or through the API.
For chronological sorting, consider how Algolia handles dates. For example, you have a blog and want to create a replica to sort search results from the most recent to the oldest post. Because Algolia doesn’t interpret dates as ISO 8601 strings (such as “2008-09-15T15:53:00”), you must convert your dates into Unix timestamps (numeric values such as 1221486780) before sorting them.
Convert dates into Unix timestamps: an example
Before
Say you have an index called articles
:
After
You want to create a replica that sorts your data by date. The problem is that the post_date
attribute has dates formatted as strings, which Algolia can’t process for sorting. Before creating a replica, you must transform these dates into Unix timestamps.
You don’t have to remove or change post_date
. Add a post_date_timestamp
attribute with the proper format instead.
Create a replica
Now, create a replica of your articles
index.
The recommendation is to name your replica indices with a prefix or suffix describing its sorting strategy (for example, articles_date_desc
).
First, create a standard or virtual replica (articles_date_desc
) from the primary index.
The primary index is likely sorted by relevance but you want to change that for articles_date_desc
.
Then, use the post_date_timestamp
attribute to sort the articles_date_desc
virtual index by date in descending order:
Sort a standard replica
Sort a virtual replica
Was this page helpful?