鍍金池/ 問答/Java/ 為什么查詢不包含某個詞的記錄時 must_not不生效呢?

為什么查詢不包含某個詞的記錄時 must_not不生效呢?

為什么must_not就不生效呢?

mapping:

"text_terms": {
    "type": "nested",
    "properties": {
        "term": {
            "type": "string",
            "index": "not_analyzed"
        },
        "freq": {
            "type": "integer"
        }
    }
}

數(shù)據(jù)

{ "text_terms" : [ { "term" : "aaa", "freq" : 1 }, { "term" : "bbb", "freq" : 1 }, { "term" : "ccc", "freq" : 1 } ] }
{ "text_terms" : [ { "term" : "aaa", "freq" : 1 }, { "term" : "西門子", "freq" : 1 }, { "term" : "ccc", "freq" : 1 } ] }
{ "text_terms" : [ { "term" : "ccc", "freq" : 1 }, { "term" : "西門子", "freq" : 1 }, { "term" : "ddd", "freq" : 1 } ] }
{ "text_terms" : [ { "term" : "ddd", "freq" : 1 }, { "term" : "eee", "freq" : 1 } ] }

查詢包含西門子的記錄 沒有問題 能查出包含西門子的兩條記錄

"query": { "nested": { "query": { "bool": { "must": [{ "term": { "text_terms.term": "西門子" } }] } }, "path": "text_terms" } }

但是查詢不包含西門子的記錄時 就不生效了呢?

"query": { "nested": { "query": { "bool": { "must_not": [{ "term": { "text_terms.term": "西門子" } }] } }, "path": "text_terms" } }

怎么此時四條記錄都能查出來呢?

回答
編輯回答
伴謊

添加第五條記錄

"text_terms" : [ { "term" : "西門子", "freq" : 1 } ]

must_not 查不出此條記錄來 于是知道原因

只要text_term中存在term不等于西門子的記錄 都能查出來 即使其中也有term等于西門子

正確的查詢方法

"query": { "bool":{ "must_not":{ "nested": {"path": "text_terms", "query": { "term": { "text_terms.term": "西門子" } } } } } }

must_not應(yīng)該放在nested外面

補充:

  • must_notnested 內(nèi)部
curl 'http://localhost:9200/test/_validate/query?explain=true&pretty' -H 'Content-Type: application/json' -d'
{
"query": { "nested": {  "path": "text_terms", "query": { "bool": { "must_not": [{ "term": { "text_terms.term": "西門子" } }] } } } }
}
'

  "explanations" : [
    {
      "index" : "test",
      "valid" : true,
      "explanation" : "ToParentBlockJoinQuery (+(-text_terms.term:西門子 +*:*) #_type:__text_terms)"
    }
  ]
  • must_notnested外部
curl 'http://localhost:9200/test/_validate/query?explain=true&pretty' -H 'Content-Type: application/json' -d'
{
"query": { "bool":{ "must_not":{ "nested": {"path": "text_terms", "query": { "term": { "text_terms.term": "西門子" } } } } } }
}
'

  "explanations" : [
    {
      "index" : "test",
      "valid" : true,
      "explanation" : "+(-ToParentBlockJoinQuery (text_terms.term:西門子) +*:*) #DocValuesFieldExistsQuery [field=_primary_term]"
    }
  ]
2018年9月23日 16:24