Sorting Results

Published on November 12, 2016 by

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.

Pagination
Aggregations
Featured

Learn Elasticsearch today!

Take an online course and become an Elasticsearch champion!

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!
Elasticsearch logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.