How to Sort the Results Using a Sort Property | Elasticsearch


Allows to add one or more sort on specific fields. Each sort can be reversed as well. The sort is defined on a per field level, with a special field name for _score to sort by score, and _doc to sort by index order.

Elasticsearch Sorting

In order to sort by relevance, we need to represent relevance as a value. In Elasticsearch, the relevance score is represented by the floating-point number returned in the search results as the _score, so the default sort order is _score descending.

In the previous example, we searched for movies from 1962. In this case, all hits have the same score. They both match the query equally. Unless told otherwise, ElasticSearch will then resort to sorting the results by their IDs. In cases such as these, or when we don’t want to sort by the score, we can tell ElasticSearch how to sort the results by adding a sort property to the request body.

The sort property’s value should be an array with JSON objects. The first object describes the primary way the results should be sorted, the second how results with the same value for the primary way should be sorted and so on.

In its simplest form, an object in the sort array is an object with a single property whose name matches the field to sort by and whose value is the order by which to sort, “asc” for ascending or “desc” for descending.

So, a request searching for all movies and sorting them by newest first can look like this:

A search request that searches for everything in the ‘movies’ index and sorts the result based on the ‘year’ property in descending order.

curl -XPOST "http://localhost:9200/movies/_search" -d'
 "query": {
 "match_all": {}
 "sort": [
 "year": "desc"

When there’s a sort property in the search request body, ElasticSearch won’t only apply the sorting rule(s) found in it. It will also extend the hit objects with a property explaining what value(s) were used for the hit during sorting.

elasticsearch sorting

Search results in Sense when using a sort property in the request body.

There is more to sorting in ElasticSearch. For instance, we can re-introduce sorting by score by adding the string “_score” as one of the values in the sort array and we can tell ElasticSearch how it should handle missing values.

0 Responses on How to Sort the Results Using a Sort Property | Elasticsearch"

Leave a Message

Your email address will not be published. Required fields are marked *

Copy Rights Reserved © Mindmajix.com All rights reserved. Disclaimer.