Sorting Results
In this article we will be taking a look at how to sort the search results.
When retrieving documents from Elasticsearch, it is possible to sort the search results. If you are familiar with relational databases, then this is equivalent of the ORDER BY query clause. I will perform a search for the term pasta as usual and order the results by the quantity field in the descending order.
GET /ecommerce/product/_search
{
"query": {
"match": {
"name": "pasta"
}
},
"sort": [
{
"quantity": {
"order": "desc"
}
}
]
}
As you may have noticed, the sort property contains an array of objects. This means that you can, in fact, add multiple sort orders just like in relational databases, if you would like. If you do this, then note that the ordering of the objects is important, as results are sorted by the first criterion first. Documents whose first sort values are identical, are then sorted by the second criteria. This concept continues for as many sort criterions that you add.
Looking at the results, we can see that the products have indeed been sorted with the largest quantities first. Let’s change the sort order to ascending instead.
GET /ecommerce/product/_search
{
"query": {
"match": {
"name": "pasta"
}
},
"sort": [
{
"quantity": {
"order": "asc"
}
}
]
}
Now the products with the lowest quantity are placed first in the results.
That’s all there is to say about sorting documents in search results.
Here is what you will learn:
- The architecture of Elasticsearch
- Mappings and analyzers
- Many kinds of search queries (simple and advanced alike)
- Aggregations, stemming, auto-completion, pagination, filters, fuzzy searches, etc.
- ... and much more!
