When searching for results, the most common criteria for sorting in ElasticSearch is the relevance to a text query. Sometimes, real-world applications need to control the sorting criteria in typical scenarios, as follows:
Sorting a user by their last name and first name
Sorting items by stock symbols and price (ascending and descending)
Sorting documents by size, file type, source, and so on
You need a working ElasticSearch cluster and an index populated with the script chapter_05/populate_query.sh
, available in the code bundle for this book.
In order to sort the results, perform the following steps:
Add a
sort
section to your query, as follows:curl -XGET 'http://127.0.0.1:9200/test-index/test-type/_search?pretty=true' -d '{"query":{"match_all":{}}, "sort" : [ {"price" : {"order" : "asc", "mode" : "avg", "ignore_unmapped":true, "missing":"_last"}}, "_score" ] }'
The returned result will be similar to this:
…, "hits" : { "total" : 3, ...