AI Hints
Home›Elasticsearch Tutorial›More Queries, Sorting and Paging
Elasticsearch · Lesson 32 of 120

Sorting

Not just by score.

⏱ 2 min read▶ Video at 29:24🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

By default, the best match comes first. But shoppers love buttons like, price low to high, and newest first. That's sorting by a field.

  • Default: by score
  • Price low to high
  • Newest first

Cheapest tents first

We match tents in the name, and sort by price, ascending. Run it. The cheapest tent comes first. Notice the score is now null, because we didn't sort by it.

Dev Tools Consoletext
GET products/_search?filter_path=hits.hits._score,hits.hits._source.price
{
  "query": { "match": { "name": "tent" } },
  "sort": [ { "price": "asc" } ],
  "_source": ["price"],
  "size": 3
}
Output
{
  "hits": {
    "hits": [
      {"_score": null, "_source": {"price": 175.99}},
      {"_score": null, "_source": {"price": 237.99}},
      {"_score": null, "_source": {"price": 288.99}}
    ]
  }
}
Also uses _load
products

Sort by two fields

Sort takes a list. First by rating, highest first. If two ratings tie, the most reviewed product wins. Run it.

Dev Tools Consoletext
GET products/_search?filter_path=hits.hits._source
{
  "sort": [
    { "rating": "desc" },
    { "reviews": "desc" }
  ],
  "_source": ["name", "rating", "reviews"],
  "size": 3
}
Output
{
  "hits": {
    "hits": [
      {
        "_source": {
          "name": "Squeeze Water Filter",
          "rating": 5.0,
          "reviews": 58
        }
      },
      {
        "_source": {
          "name": "Expedition 65L Hiking Backpack",
          "rating": 4.9,
          "reviews": 543
        }
      },
      {
        "_source": {
          "name": "River Camp Sandals",
          "rating": 4.9,
          "reviews": 118
        }
      }
    ]
  }
}
Also uses _load
products

Summary

Sort orders results by any number, date or keyword field, ascending or descending, and you can sort by several fields. Next, paging through results.

Key takeaways
  • sort
  • asc / desc
  • Tie-breakers
Next up: Paging and _source — from, size and fields