filtered query
filtered
クエリはquery
とfilter
を組み合わせるために用いられます。フィルターは単純にクエリを使うよりも高速となるケースが多く、なぜなら、*1
- フィルターは、ドキュメントとの関連度スコアを数値計算するのではなく、マッチしたか否かのboolだけを返します*2
- フィルターを用いた検索の結果はメモリにキャッシュされその後につづく処理を高速化します*3
Tips >> フィルターを用いて検索対象ドキュメントをなるべく少なくすることが強く推奨されます。*4
filtered
クエリは、query
を用いることができるフィールドではどこでも使用することができます。たとえば、以下のように_searchのクエリとして使えます。*5
curl -XGET localhost:9200/_search -d ' { "query": { "filtered": { // `filtered`クエリは、親の`query`のvalueとして使っています "query": { "match": { "tweet": "full text search" } }, "filter": { "range": { "created": { "gte": "now - 1d / d" }} } } } } '
filtering without query
query
を使わずにfilter
のみを使うと、デフォルトではmatch_all
クエリを使った場合の挙動となります。テクい使い方として、filter
のみをfiltered
でらっぷすることで、ほかのquery
に対するすべてのフィルタとして使えるということです。*6
curl -XGET localhost:9200/_search -d ' { "query": { "filtered": { "filter": { "range": { "created": { "gte": "now - 1d / d" }} } } } } '
// queryが与えられない場合、これはfilterされた結果すべてのドキュメントとマッチし、返します
multiple filters
複数のフィルターを定義する場合は、bool
フィルタでこれをラップします*7
{ "filtered": { "query": { "match": { "tweet": "full text search" }}, "filter": { "bool": { "must": { "range": { "created": { "gte": "now - 1d / d" }}}, "should": [ { "term": { "featured": true }}, { "term": { "starred": true }} ], "must_not": { "term": { "deleted": false }} } } } }
同様に、複数のqueryもboolによって組み合わせることが可能です。*8
filter strategy
ストラテジを指定できるらしい。今回は割愛
*1:The filtered query is used to combine another query with any filter. Filters are usually faster than queries because:
*2:they don’t have to calculate the relevance _score for each document — the answer is just a boolean “Yes, the document matches the filter” or “No, the document does not match the filter”.
*3:the results from most filters can be cached in memory, making subsequent executions faster.
*4:Exclude as many document as you can with a filter, then query just the documents that remain.
*5:The filtered query can be used wherever a query is expected, for instance, to use the above example in search request:
*6:If a query is not specified, it defaults to the match_all query. This means that the filtered query can be used to wrap just a filter, so that it can be used wherever a query is expected.
*7:Multiple filters can be applied by wrapping them in a bool filter, for example:
*8:Similarly, multiple queries can be combined with a bool query.