In this short guide, we will look at how to sort query results in Elasticsearch.
Basic Usage
You can sort the results using one line method in a query. For example:
In the example query above, we fetch all the documents where the field DestCityName is equal to Denver and then sort the results on the AvgTicket Price.
The resulting query should include the documents where the city is Denver, with the ticket prices sorted in ascending order.
Example output is as shown:
Although the one-line method can be helpful when you need to perform a quick sort, it is not very readable and can get complicated when you need to sort multiple fields.
To solve this, you can use the recommended Elasticsearch query method. For example, we can write the above query as:
{
"query": {
"match": {
"DestCityName": "Denver"
}
}
, "sort": [
{
"AvgTicketPrice": {
"order": "asc"
}
}
]
}
This query functions similarly to the one-line method shown above. However, it is more descriptive and is more readable.
Sort By Ascending Order
To change by reverse order, you can change the order from asc to desc, which will sort the values from the highest to the lowest as shown:
{
"query": {
"match": {
"DestCityName": "Denver"
}
}
, "sort": [
{
"AvgTicketPrice": {
"order": "desc"
}
}
]
}
The example output is as shown:
Geo Distance Sorting
Elasticsearch allows you to sort by geo-information using the _geo_distance parameter. For example, consider the following query:
{
"query": {
"match": {
"DestCountry": "US"
}
},
"sort": [
{
"_geo_distance": {
"OriginLocation": {
"lat": 30,
"lon": -103
},
"order": "desc"
}
}
]
}
The above query should return the records where the Destination country is equal to the US and the location is within the specified latitude and longitude range.
Sort By Text Type
Sorting is not limited to numerical values, you sort by text as:
{
"query": {
"match": {
"DestCityName": "Sydney"
}
},
"sort": [
{
"Carrier": {
"order": "desc"
}
}
]
}
Conclusion
In this tutorial, we covered how to sort results from an Elasticsearch query using the sort keyword. Check the documentation to learn more.