Elasticsearch 过滤器

本文主要记录es的查询过滤的使用。

使用过滤器

过滤器不影响评分,而评分计算让搜索变得复杂,而且需要CPU资源,因而尽量使用过滤器,而且过滤器容易被缓存,进一步提升查询的整体性能。

post_filter(先查询再过滤)

{ 
    "query": {
        "match":{"title":"Catch-22"}
    },
    "post_filter":{
        "term":{"year":1961}
    }
}

filtered(先过滤再查询,速度快)

{
    "query": {
        "filtered": {
            "query": {
                "match": {
                    "title": "Catch-22"
                }
            }, 
            "filter": {
                "term": {
                    "year": 1961
                }
            }
        }
    }
}

这种方式在2.2版本被废弃调用,改用bool的方式

{
    "query": {
        "bool": {
            "must": {
                "match": {
                    "title": "Catch-22"
                }
            }, 
            "filter": {
                "term": {
                    "year": 1961
                }
            }
        }
    }
}

过滤器种类

范围过滤器

{
   "post_filter":{
         "range":{
             "year":{
                 "gte":1930,
                 "lte":1990
             }
         }         
    }
}

exists过滤器

{
   "post_filter":{
         "exists":{
             "field":"year"
         }
    }
}

missing过滤器

过滤掉给定字段有值或缺失的文档

{
   "post_filter":{
         "missing":{
             "field":"year",
             "null_value":0,
             "existence":true
         }
    }
}

脚本过滤器

过滤掉发表在一个世纪以前的书

{
   "post_filter":{
         "script":{
             "script":"now - doc[‘year‘].value > 100",
             "params":{"now":2012}
         }
    }
}

类型过滤器

当查询运行在多个索引上时,有用

{
   "post_filter":{
         "type":{
             "value":"book"
         }
    }
}

限定过滤器

限定每个分片返回的文档数

{
   "post_filter":{
         "limit":{
             "value":1
         }
    }
}

标识符过滤器

比如要指定标识符为1,2,3的文档

{
   "post_filter":{
         "ids":{
             "type":["book"],
             "values":[1,2,3]
         }
    }
}

组合过滤器

{
    "query": {
        "bool": {
            "must": {
                "range": {
                    "year": {
                        "gte": 1930, 
                        "lte": 1990
                    }
                }
            }, 
            "should": {
                "term": {
                    "available": true
                }
            }, 
            "boost": 1
        }
    }
}
原文地址:https://www.cnblogs.com/Hai--D/p/6774971.html