【问题标题】:How combine query, must and must_not in elasticsearch?如何在 elasticsearch 中结合查询、必须和 must_not?
【发布时间】:2018-04-06 17:52:31
【问题描述】:

应找到以下文件:

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. 通过 OR mustfilter 部分进行布尔组合
  2. 第一个must查询选择
  3. 过滤器使用由 OR must andmust_not 组合而成的 bool

但这就像must 通过AND 子句结合must_not。例如。当我删除“must”或“must_not”查询时有效。

如何通过OR子句更改查询以将“must”与“must_not”结合起来?

Elasticsearch 版本为5.3.2

【问题讨论】:

  • 伙计,我试图遵循你的 AND OR 规则但不能。也许this 可以帮助您重新排序条款。

标签: elasticsearch


【解决方案1】:

您需要在 mustmust_not 术语之间增加一个 bool filter

您还应该考虑您的 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"]
                     }
                   }
                }
              }]

         }
      }
   }
  }
}

【讨论】:

    【解决方案2】:

    在 Elasticsearch 7.X 上,您可以这样做:

    {
      "query": {
        "bool": {
          "must": [
            {"match": {"field1": {"query": "Hero"}}}
          ],
          "must_not": [
            {"terms":{"field3":["Batman"]}},
          ]
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-02-05
      • 2015-04-16
      • 2020-06-22
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      相关资源
      最近更新 更多