最近有一個線上的es查詢問題,最後肯定在使用
bool query
多條件組合查詢時出現should
子句查詢失效,因而查找資料來肯定問題所在。html
其中Elasticsearch
: 5.5.0
json
找到相關的查詢語句:app
"query": {
"bool": { // bool query 查詢
"should": [ // should子句
{
"match_phrase": {
"name": {
"query": "星起",
"boost": 30,
"slop": 5
}
}
}
],
"filter": { // #filter子句
"bool": {
"must": [
{
"terms": {
"round": ["A輪"]
}
},
]
}
}
}
}
複製代碼
問題在於:使用 bool query
組合查詢時,should
與filter
組合查詢的結果只匹配了filter
子句,並不匹配should
子句,達不到should
和filter
取交集的預期。elasticsearch
翻了一下官方文檔:Bool Query | Elasticsearch Reference [5.5] | Elastic 對should
的解釋:ide
The clause (query) should appear in the matching document. If the
bool
query is in a query context and has amust
orfilter
clause then a document will match thebool
query even if none of theshould
queries match. In this case these clauses are only used to influence the score. If thebool
query is a filter context or has neithermust
orfilter
then at least one of theshould
queries must match a document for it to match thebool
query. This behavior may be explicitly controlled by settings the minimum_should_match parameter.測試
大致的意思就是:should
子句是在匹配文檔中使用的,若是bool
查詢是在query
上下文,而且有must
或者 filter
子句時無論should
查詢是否匹配,都不影響must
或者filter
子句的查詢。這些子句只是影響查詢的score
而已。若是bool
查詢是在filter
上下文 或者 既沒有must
也沒有filter
則應至少一個should
查詢必須匹配bool
查詢。也能夠顯式設置minimum_should_match這個參數來解決。 從官方文檔能夠看出,有2種方式能夠在bool query
取各數據的交集:ui
filter
上下文裏minimum_should_match
參數用上面提到2種方式,咱們分別嘗試一下是否能夠達到預期目標。this
使用filter
上下文:spa
"query": {
"bool": {
"filter": { // filter上下文
"bool": {
"should": [ // should子句
{
"match_phrase": {
"name": {
"query": "星起",
"boost": 30,
"slop": 5
}
}
}
],
"filter": { // filter子句
"bool": {
"must": [
{
"terms": {
"round": ["A輪"]
}
}
]
}
}
}
}
}
}
複製代碼
測試結果以下:code
"hits": {
"total": 1,
"max_score": null,
"hits": [
{
"_index": "index_name",
"_type": "hub/product",
"_id": "id",
"_score": 0.0, // filter下分值爲0.0
"_source": {
"round": "A輪",
"name": "星起Starup",
"created_at": "2015-12-25T22:20:36.210+08:00",
"sector_name": "企業服務"
},
"highlight": {
"name": ["<em>星起</em>Starup"]
},
"sort": []
}
]
}
複製代碼
測試結果知足should
與filter
子句交集,須要注意結果的分值爲0.0
, 沒有對查詢結果匹配程度打分。
使用minimum_should_match
,至少匹配一項should
子句,能夠以下設置:
"query": {
"bool": {
"should": [ // should 子句
{
"match_phrase": {
"name": {
"query": "星起",
"boost": 30,
"slop": 5
}
}
}
],
"minimum_should_match": 1, // 最少匹配一項should中條件子句
"filter": { // filter子句
"bool": {
"must": [
{
"terms": {
"round": ["A輪"]
}
},
]
}
}
}
}
複製代碼
測試結果以下:
"hits": {
"total": 1,
"max_score": null,
"hits": [
{
"_index": "index_name",
"_type": "hub/product",
"_id": "id",
"_score": 757.66394,
"_source": {
"round": "A輪",
"name": "星起Starup",
"created_at": "2015-12-25T22:20:36.210+08:00",
"sector_name": "企業服務"
},
"highlight": {
"name": ["<em>星起</em>Starup"]
},
"sort": [757.66394]
}
]
}
複製代碼
數據爲should
與filter
子句的交集,符合預期的結果,而且有相應的匹配程度分值。
從上面2種解決方案能夠看出,Elasticsearch
在查詢上仍是比較靈活,平時除了須要熟悉官方的文檔,還要結合業務的需求,才能找到正確解決問題的方法。