如何在elasticsearch中结合查询,必须和must_not?

时间:2017-10-25 15:02:22

标签: elasticsearch

应找到以下文件:

matches query 'my text' AND (has not field OR field with value)

我尝试了以下内容:

GET /myIndex/_search

{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "my text"
          }
        },
        {
        }
      ],
      "filter": {
        "bool": {
          "must_not": {
            "exists": {
              "field": "myField"
            }
          },
          "must": {
            "terms": {
              "myField": [
                "myValue"
              ]
            }
          }
        }
      }
    }
  }
}

它应该(但)工作谎言:

  1. bool通过OR mustfilter部分
  2. 进行组合
  3. 首先must按查询选择
  4. 过滤器使用由OR must and must_not`
  5. 组合的bool

    但这类似于mustmust_not通过 AND 子句相结合。例如。当我删除"必须"或者" must_not"查询工作。

    如何更改查询以及#34;必须"用" must_not"通过 OR 条款?

    Elasticsearch版本为5.3.2

1 个答案:

答案 0 :(得分:1)

bool filtermust条之间需要额外must_not

您还应该考虑 myField 字段。如果它被定义为文本或关键字。 使用elasticsearch 5.6.1进行测试以下查询有效:

{
  "query": {
     "bool": {
        "must": [{

          "query_string": {
             "query": "this is a text content"
          }
        }],

        "filter": {
           "bool": {
              "should" : [{                
                 "bool" : {
                    "must_not": {
                      "exists": {
                         "field": "myField"
                       }
                     }
                  }
              },
              {
                "bool" : {
                  "must": {
                    "terms": {
                       "myField.keyword": ["my field exists and has a value"]
                     }
                   }
                }
              }]

         }
      }
   }
  }
}