0
0
ElasticsearchHow-ToBeginner · 3 min read

How to Sort by Multiple Fields in Elasticsearch

To sort by multiple fields in Elasticsearch, use the sort parameter with an array of objects, each specifying a field and its sort order. For example, "sort": [{"field1": "asc"}, {"field2": "desc"}] sorts first by field1 ascending, then by field2 descending.
📐

Syntax

The sort parameter accepts an array of fields to sort by. Each element can be a field name with an order or an object specifying the field and order.

  • Field name: The name of the field to sort on.
  • Order: asc for ascending or desc for descending.
  • The order of fields in the array defines the priority of sorting.
json
{
  "sort": [
    { "field1": { "order": "asc" } },
    { "field2": { "order": "desc" } }
  ]
}
💻

Example

This example sorts documents first by age in ascending order, then by name.keyword in descending order.

json
{
  "query": {
    "match_all": {}
  },
  "sort": [
    { "age": { "order": "asc" } },
    { "name.keyword": { "order": "desc" } }
  ]
}
Output
[ {"_source": {"name": "Mike", "age": 25}}, {"_source": {"name": "Zara", "age": 25}}, {"_source": {"name": "Anna", "age": 30}} ]
⚠️

Common Pitfalls

  • For text fields, use keyword subfields (e.g., name.keyword) to sort correctly.
  • Omitting the order defaults to ascending, which might not be intended.
  • Sorting on fields that are not indexed or not sortable will cause errors.
  • Mixing data types in sort fields can lead to unexpected results.
json
{
  "sort": [
    "name",  
    { "age": "desc" }
  ]
}

// Correct way:
{
  "sort": [
    { "name.keyword": { "order": "asc" } },
    { "age": { "order": "desc" } }
  ]
}
📊

Quick Reference

ConceptDescriptionExample
Sort ParameterArray of fields to sort by priority[{"field1": {"order": "asc"}}, {"field2": {"order": "desc"}}]
Order ValuesSort direction"asc" or "desc"
Keyword FieldsUse for sorting text fields"name.keyword"
Default OrderIf omitted, defaults to ascending"field1" is same as {"field1": {"order": "asc"}}

Key Takeaways

Use the sort array with objects specifying field names and order to sort by multiple fields.
Always specify the order explicitly to avoid confusion; default is ascending.
Use keyword subfields for sorting text fields to get correct results.
The order of fields in the sort array defines the sorting priority.
Ensure fields used for sorting are indexed and sortable to prevent errors.