How to Sort Results in Elasticsearch: Syntax and Examples
To sort results in
Elasticsearch, use the sort parameter in your search query. You specify the field to sort by and the order (asc for ascending or desc for descending). This controls the order in which documents appear in the results.Syntax
The sort parameter is added inside the search query body. It accepts an array of fields to sort by. Each field can be specified as a simple string for ascending order or as an object to define the order explicitly.
- Field name: The document field to sort on.
- Order:
ascfor ascending ordescfor descending.
json
{
"sort": [
{ "field_name": { "order": "asc" } },
"another_field"
]
}Example
This example sorts documents by the price field in ascending order and then by rating in descending order. It shows how to combine multiple sort criteria in a search query.
json
{
"query": {
"match_all": {}
},
"sort": [
{ "price": { "order": "asc" } },
{ "rating": { "order": "desc" } }
]
}Output
[
{"_id": "3", "price": 10, "rating": 5},
{"_id": "1", "price": 10, "rating": 3},
{"_id": "2", "price": 20, "rating": 4}
]
Common Pitfalls
Common mistakes when sorting in Elasticsearch include:
- Not specifying the
order, which defaults to ascending but can cause confusion. - Trying to sort on fields that are not indexed or not sortable (like analyzed text fields).
- Using string fields without keyword subfields, which can cause errors.
- Forgetting that sorting on multiple fields applies in order, so the second field only sorts documents with the same value in the first field.
json
{
"query": { "match_all": {} },
"sort": [
"text_field"
]
}
// Wrong: sorting on analyzed text field without keyword
{
"query": { "match_all": {} },
"sort": [
{ "text_field.keyword": { "order": "asc" } }
]
}
// Right: sorting on keyword subfieldQuick Reference
| Parameter | Description | Example |
|---|---|---|
| sort | Array of fields to sort by | [{"price": {"order": "asc"}}] |
| order | Sort direction: asc or desc | "order": "desc" |
| field.keyword | Use keyword subfield for text sorting | "name.keyword" |
| Multiple fields | Sort by multiple fields in order | [{"price": {"order": "asc"}}, {"rating": {"order": "desc"}}] |
Key Takeaways
Use the sort parameter in the search query to control result order.
Specify order as asc or desc for each field to sort.
Sort only on fields that are indexed and sortable, like keyword or numeric fields.
Multiple sort fields apply in sequence to break ties.
Avoid sorting on analyzed text fields without keyword subfields.