为什么查询不包含某个词的记录时 must_not不生效呢?

为什么must_not就不生效呢?

mapping:

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

数据

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

怎么此时四条记录都能查出来呢?

阅读 13k
1 个回答

添加第五条记录

"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应该放在nested外面

补充:

  • must_notnested 内部
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]"
    }
  ]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进