本文主要记录es的查询过滤的使用。html
过滤器不影响评分,而评分计算让搜索变得复杂,并且须要CPU资源,于是尽可能使用过滤器,并且过滤器容易被缓存,进一步提高查询的总体性能。缓存
先查询再过滤
){ "query": { "match":{"title":"Catch-22"} }, "post_filter":{ "term":{"year":1961} } }
先过滤再查询,速度快
){ "query": { "filtered": { "query": { "match": { "title": "Catch-22" } }, "filter": { "term": { "year": 1961 } } } } }
这种方式在2.2版本被废弃调用,改用bool的方式elasticsearch
{ "query": { "bool": { "must": { "match": { "title": "Catch-22" } }, "filter": { "term": { "year": 1961 } } } } }
{ "post_filter":{ "range":{ "year":{ "gte":1930, "lte":1990 } } } }
{ "post_filter":{ "exists":{ "field":"year" } } }
过滤掉给定字段有值或缺失的文档ide
{ "post_filter":{ "missing":{ "field":"year", "null_value":0, "existence":true } } }
过滤掉发表在一个世纪之前的书post
{ "post_filter":{ "script":{ "script":"now - doc[‘year‘].value > 100", "params":{"now":2012} } } }
当查询运行在多个索引上时,有用性能
{ "post_filter":{ "type":{ "value":"book" } } }
限定每一个分片返回的文档数ui
{ "post_filter":{ "limit":{ "value":1 } } }
好比要指定标识符为1,2,3的文档spa
{ "post_filter":{ "ids":{ "type":["book"], "values":[1,2,3] } } }
{ "query": { "bool": { "must": { "range": { "year": { "gte": 1930, "lte": 1990 } } }, "should": { "term": { "available": true } }, "boost": 1 } } }