Post Filteredit

So far, we have a way to filter both the search results and aggregations (a non-scoring filter query), as well as filtering individual portions of the aggregation (filter bucket).

You may be thinking to yourself, "hmm…​is there a way to filter just the search results but not the aggregation?" The answer is to use a post_filter.

This is a top-level search-request element that accepts a filter. The filter is applied after the query has executed (hence the post moniker: it runs post query execution). Because it operates after the query has executed, it does not affect the query scope—​and thus does not affect the aggregations either.

We can use this behavior to apply additional filters to our search criteria that don’t affect things like categorical facets in your UI. Let’s design another search page for our car dealer. This page will allow the user to search for a car and filter by color. Color choices are populated via an aggregation:

GET /cars/transactions/_search
{
    "size" : 0,
    "query": {
        "match": {
            "make": "ford"
        }
    },
    "post_filter": {    
        "term" : {
            "color" : "green"
        }
    },
    "aggs" : {
        "all_colors": {
            "terms" : { "field" : "color" }
        }
    }
}

The post_filter element is a top-level element and filters just the search hits.

The query portion is finding all ford cars. We are then building a list of colors with a terms aggregation. Because aggregations operate in the query scope, the list of colors will correspond with the colors that Ford cars are painted.

Finally, the post_filter will filter the search results to show only green ford cars. This happens after the query is executed, so the aggregations are unaffected.

This is often important for coherent UIs. Imagine that a user clicks a category in your UI (for example, green). The expectation is that the search results are filtered, but not the UI options. If you applied a Boolean filter query, the UI would instantly transform to show only green as an option—​not what the user wants!

Performance consideration

Use a post_filter only if you need to differentially filter search results and aggregations. Sometimes people will use post_filter for regular searches.

Don’t do this! The nature of the post_filter means it runs after the query, so any performance benefit of filtering (such as caches) is lost completely.

The post_filter should be used only in combination with aggregations, and only when you need differential filtering.