AI Hints
Home›Elasticsearch Tutorial›Sub-aggregations, Cardinality, top_hits
Elasticsearch · Lesson 78 of 120

top_hits

Best documents per bucket.

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

A category page shows the best rated product in each category. That's a bucket per category, with one document inside. Top hits returns documents inside buckets.

  • Per category
  • Best product
  • top_hits

Best product per category

Terms makes a bucket per category. Top hits returns one document per bucket, sorted by rating. Source keeps just the name. Run it. The best rated product in each of the two biggest categories.

Dev Tools Consoletext
GET products/_search?filter_path=aggregations.cats.buckets.key,aggregations.cats.buckets.best.hits.hits._source.name
{
  "size": 0,
  "aggs": { "cats": {
    "terms": { "field": "category", "size": 2 },
    "aggs": { "best": { "top_hits": {
      "size": 1, "sort": [{ "rating": "desc" }],
      "_source": ["name"] } } } } }
}
Output
{
  "aggregations": {
    "cats": {
      "buckets": [
        {
          "key": "Tents",
          "best": {
            "hits": {
              "hits": [
                {"_source": {"name": "Basecamp 4-Person Tent"}}
              ]
            }
          }
        },
        {
          "key": "Footwear",
          "best": {
            "hits": {
              "hits": [
                {"_source": {"name": "River Camp Sandals"}}
              ]
            }
          }
        }
      ]
    }
  }
}
Also uses _load
catalog

top_hits uses

Show the newest order per customer. Show the best product per brand. Or group search results, like one result per category. Keep the size small, because it returns full documents.

keyvalue
Newest per customersort by date
Best per brandsort by rating
Groupingone hit per bucket
Keepsize small

Summary

Top hits returns the best documents inside each bucket. Next, facets that don't disappear when you click them.

Key takeaways
  • top_hits
  • size: 1
  • sort
Next up: Facets with post_filter — filters that keep counts