Bool query 包含那些?
Bool query 對應lucene 的BooleanQuery
,一般由一個或者多個查詢子句組成,如下表格所示:
用法 | 描述 |
---|---|
|
查詢一定包含匹配查詢內容,並且提供得分 |
|
查詢一定包含匹配查詢內容,但是不提供得分,會對查詢結果進行緩存 |
|
子查詢不一定包含查詢內容 |
|
查詢一定不包含查詢內容,來自於filter 上下文,所以不會由評分,但是會緩存
|
bool 查詢秉持匹配越多越接近的原則,每個子查詢(must or should)評分會被加在一起作為最終評分。
POST _search { "query": { "bool" : { "must" : { "term" : { "user.id" : "kimchy" } }, "filter": { "term" : { "tags" : "production" } }, "must_not" : { "range" : { "age" : { "gte" : 10, "lte" : 20 } } }, "should" : [ { "term" : { "tags" : "env1" } }, { "term" : { "tags" : "deployed" } } ], "minimum_should_match" : 1, "boost" : 1.0 } } }
使用 minimum_should_match
可以使用minimum_should_match參數指定返回的文檔必須匹配的子句的數量或百分比。
如果bool 查詢包含至少一個should 子查詢並且沒有must 或者filter 查詢,則默認數值是1.否則默認為0.
使用bool.filter評分
filter 對評分無影響返回值為0,評分只受到特殊查詢影響,比如,如下三種情況的得分
使用filter,返回的文檔得分都為0:
GET _search { "query": { "bool": { "filter": { "term": { "status": "active" } } } } } 使用match_all查詢,所有文檔評分都為1.0 GET _search { "query": { "bool": { "must": { "match_all": {} }, "filter": { "term": { "status": "active" } } } } } constant_score 查詢與match_all 完全一致,使用filter 返回所有文檔都分配一個1.0 的評分 GET _search { "query": { "constant_score": { "filter": { "term": { "status": "active" } } } } }
Named queries
每個查詢在頂部的定義里面都要接收一個_name 。可以使用這種查詢追蹤匹配返回的文檔。比如,返回命中文檔必須包含一個match 查詢的屬性:
GET /_search { "query": { "bool": { "should": [ { "match": { "name.first": { "query": "shay", "_name": "first" } } }, { "match": { "name.last": { "query": "banon", "_name": "last" } } } ], "filter": { "terms": { "name.last": [ "banon", "kimchy" ], "_name": "test" } } } } }