Elasticsearch Filtered query vs Filter [duplicate]

Solution 1:

The difference is related to performance. "filter" on top level is always executed after the query. This means the query is executed on all documents, score is computed for all documents etc. - and only then documents not matching filter are excluded.

With "filtered" query there is a possibility that ES will optimize this computation, e.g. first executing the filter, then executing query on a limited set of documents, saving time on testing the documents that don't match the filter against the query, and on computing scores for them if they do match the query.

If you are performing multiple queries with same filter, then there are even more advantages: the filter may be cached, improving performance of each query even further. This applies to your example: "term" filters are cached by default.

You also can explicitly control the execution of "filtered" query (see the documentation) to optimize it for your particular use case.

Solution 2:

The filters in the two types can be referred as pre and post filters also. As @alexey explained, root level filter is performed after query and filter in filtered query is performed before the query.

In addition you need to understand the impact of the same other then the order they are executed. The filter in "filtered" query comes under the query scope which means that while calculating aggregations the filtered output will be considered while in case of the root level filter aggregations will be performed only on the results of the query excluding the filter. Though in both case the result documents will be same.

For example with the two queries you have posted, both will give same results, but if you are performing aggregations also the first query will calculate aggregation count from documents matching title kitchen3 and price 10000 while the second query will calculate aggregation count from documents matching title kitchen3 only without filter of price 1000.