过滤查询<Filter Query>
ES的查询操作分为2种,查询(query)和过滤(filter)。查询默认会计算每个返回文档的得分,根据得分排序。过滤只会筛选符合文档,并不计算得分,可以缓存文档。所以但从性能上考虑。过滤比查询比更快。过滤适合大范围筛选数据,而查询适合精确匹配数据。一般应用时,应先使用过滤操作过滤数据,然后使用查询匹配数据。
注意📢📢📢:
- 在执行filter和query时,先执行filter再执行query
- ES会自动缓存经常使用的过滤器,以加快性能
类型
常见的过滤类型有:term、terms、range、exists、ids等。
term
# 删除索引 DELETE /products # 创建索引 PUT /products { "settings":{ "number_of_shards":1, "number_of_replicas":0 }, "mappings":{ "properties": { "id":{ "type":"integer" }, "title":{ "type":"keyword" }, "create_at":{ "type":"date" }, "description":{ "type":"text", "analyzer": "ik_max_word" } } } } # 文档批量操作 POST /products/_bulk {"index":{"_id":1}} {"id":3,"title":"龙猫","price":188,"create_at":"2022-01-02", "description":"龙猫肥宅"} {"index":{"_id":2}} {"id":4,"title":"大白","price":88,"create_at":"2022-01-01", "description":"大白真可爱"} {"index":{"_id":3}} {"id":3,"title":"冰墩墩","price":388,"create_at":"2022-02-02", "description":"一墩难求"} {"index":{"_id":4}} {"id":4,"title":"雪融融","price":288,"create_at":"2022-02-25", "description":"真可爱"} # filer query 过滤查询 GET /products/_search { "query": { "term": { "description": { "value": "可爱" } } } } # 过滤查询 term GET /products/_search { "query": { "bool": { "must": [ { "match_all": {} } ], "filter": [ { "term": { "description": "大白" } } ] } } }
terms
# 过滤查询 terms GET /products/_search { "query": { "bool": { "must": [ { "match_all": {} } ], "filter": [ { "terms": { "description": [ "可爱", "宅" ] } } ] } } }
range
范围过滤
# 过滤查询 range GET /products/_search { "query": { "bool": { "must": [ { "match_all": {} } ], "filter": [ { "range": { "price": { "gte": 100, "lte": 300 } } } ] } } }
exist
存在字段过滤
# 过滤查询 exist GET /products/_search { "query": { "bool": { "must": [ { "match_all": {} } ], "filter": [ { "exists": { "field": "description" } } ] } } }
ids
# 过滤查询 ids GET /products/_search { "query": { "bool": { "must": [ { "match_all": {} } ], "filter": [ { "ids": { "values": [ "1", "2", "3" ] } } ] } } }