elasticsearch之查詢過濾

will007 9年前發布 | 8K 次閱讀 ElasticSearch 搜索引擎

來自: https://segmentfault.com/a/1190000004429689


本文主要記錄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
             }
         }

}

}</pre>

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
        }
    }
}

參考

 本文由用戶 will007 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!