0
0
ElasticsearchHow-ToBeginner · 3 min read

How to Sort by Date in Elasticsearch: Syntax and Examples

To sort by date in Elasticsearch, use the sort parameter in your query and specify the date field with the order asc or desc. For example, { "sort": [{ "date_field": { "order": "desc" }}] } sorts results by the date field in descending order.
📐

Syntax

The sort parameter in Elasticsearch queries lets you order results by one or more fields. To sort by a date field, specify the field name and the order, which can be asc for oldest first or desc for newest first.

  • sort: The main key to define sorting rules.
  • date_field: Replace this with your actual date field name.
  • order: Direction of sorting, either asc or desc.
json
{
  "sort": [
    {
      "date_field": {
        "order": "desc"
      }
    }
  ]
}
💻

Example

This example shows how to sort documents by a date field called publish_date in descending order, so the newest documents appear first.

json
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "publish_date": {
        "order": "desc"
      }
    }
  ]
}
Output
[ { "_id": "3", "_source": {"title": "Newest Post", "publish_date": "2024-06-01T10:00:00Z"} }, { "_id": "1", "_source": {"title": "Older Post", "publish_date": "2023-12-15T08:30:00Z"} } ]
⚠️

Common Pitfalls

Common mistakes when sorting by date include:

  • Using the wrong field name or a field that is not mapped as a date type.
  • Not specifying the order, which defaults to ascending.
  • Sorting on a text field instead of a date field, which leads to unexpected order.

Always check your field mapping to confirm the field is a date type.

json
{
  "sort": [
    {
      "date_field": "desc"  
    }
  ]
}

// Correct way:
{
  "sort": [
    {
      "date_field": {
        "order": "desc"
      }
    }
  ]
}
📊

Quick Reference

ParameterDescriptionExample
sortDefines sorting rules{"sort": [{"date_field": {"order": "asc"}}]}
date_fieldYour date field name"publish_date"
orderSorting direction: asc or desc"desc"

Key Takeaways

Use the sort parameter with your date field and specify order asc or desc to sort by date.
Ensure your date field is mapped as a date type in Elasticsearch to avoid sorting errors.
The default sort order is ascending if order is not specified.
Sorting on non-date fields can cause unexpected results.
Always test your query to confirm the sorting works as expected.