AI Hints
Home›Elasticsearch Tutorial›Facets and Dashboards
Elasticsearch · Lesson 79 of 120

Facets with post_filter

Filters that keep counts.

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

A shopper clicks the TrailCo brand. If that filter goes in the query, the brand list now only shows TrailCo, and the other brands vanish. Shoppers want to see the other brands, so they can change their mind.

  • Click TrailCo
  • Other brands vanish
  • Bad experience

post_filter

The query matches jackets. The brand aggregation runs on all jackets. Post filter then narrows only the hits to TrailCo. Run it. The hits are TrailCo jackets, but the brand counts still show every brand.

Dev Tools Consoletext
GET products/_search?filter_path=hits.hits._source.name,aggregations.brands.buckets
{
  "query": { "term": { "category": "Jackets" } },
  "aggs": { "brands": { "terms": { "field": "brand" } } },
  "post_filter": { "term": { "brand": "TrailCo" } }
}
Output
{
  "hits": {
    "hits": [
      {"_source": {"name": "Storm Rain Jacket"}},
      {"_source": {"name": "Breeze Rain Jacket"}},
      {"_source": {"name": "Classic Fleece Jacket"}}
    ]
  },
  "aggregations": {
    "brands": {
      "buckets": [
        {"key": "TrailCo", "doc_count": 3},
        {"key": "Granite", "doc_count": 2},
        {"key": "Alpina", "doc_count": 1},
        {"key": "Ridgeline", "doc_count": 1}
      ]
    }
  }
}
Also uses _load
catalog

When to use it

Use post filter for the facet a shopper just clicked, so its own counts stay complete. Keep other filters in the query, since they're faster there. Post filter runs after aggregations, so it doesn't affect them.

keyvalue
post_filterclicked facet
Countsstay complete
Other filtersin the query
Orderafter aggs

Summary

Post filter narrows the hits after aggregations run, so facet counts stay useful. Next, pipeline aggregations.

Key takeaways
  • post_filter
  • Facet counts
  • After aggs
Next up: Pipeline Aggregations — aggregations of aggregations