AI Hints
Home›Elasticsearch Tutorial›Deep Paging, collapse and Geo
Elasticsearch · Lesson 86 of 120

collapse

One result per group.

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

Searching for warm shows five sleeping bags in a row. It might be nicer to show the best match from each category, so shoppers see the variety. Collapse does that.

  • Five bags in a row
  • Show variety
  • collapse

Best match per category

Collapse on category keeps only the top hit per category. Run it. One warm product from each category, boots, a harness, a pack, a jacket, and more.

Dev Tools Consoletext
GET products/_search?filter_path=hits.hits._source.name
{
  "query": { "match": { "description": "warm" } },
  "collapse": { "field": "category" },
  "_source": ["name"]
}
Output
{
  "hits": {
    "hits": [
      {"_source": {"name": "Nonstick Cook Set"}},
      {"_source": {"name": "Summit Hiking Boots"}},
      {"_source": {"name": "Sport Climbing Harness"}},
      {"_source": {"name": "Rolltop 28L Travel Pack"}},
      {"_source": {"name": "Storm Rain Jacket"}},
      {"_source": {"name": "Rechargeable 600 Headlamp"}},
      {"_source": {"name": "Alpine Down Sleeping Bag"}}
    ]
  }
}
Also uses _load
catalog

collapse notes

Collapse works on keyword or number fields. Inner hits can show a few more results from each group. It's faster than top hits for grouping search results. And total hits still counts every match, not the groups.

keyvalue
Fieldkeyword or number
inner_hitsmore per group
vs top_hitsfaster for results
Totalcounts all matches

Summary

Collapse returns one top hit per group, for more varied results. Next, searching by location.

Key takeaways
  • collapse
  • One per group
  • inner_hits
Next up: Geo Search — stores near me