如何通过AND和OR逻辑(AND内的OR逻辑)的组合定义DSL查询?

时间:2019-05-02 08:07:12

标签: elasticsearch elasticsearch-dsl

我想定义一个DSL查询,以在下面的Lucene中描述该查询:

q = role:(admin OR manager) AND priority:(high OR middle).

我知道我可以使用should来表示OR逻辑,但是,下面的DSL查询是:

{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "role": "admin"
          }
        },
        {
          "match": {
            "role": "manager"
          }
        },
        {
          "match": {
            "priority": "high"
          }
        },
        {
          "match": {
            "priority": "middle"
          }
        }
      ],
      "minimum_should_match": "2"
    }
  }
}

无法实现我所需要的,因为数据

{
  "role": [ "admin", "manager"],
  "priority": "low"
}

将被视为有效,但事实并非如此。

如何解决DSL查询?我正在使用ElasticSearch 5.2.2,谢谢!

1 个答案:

答案 0 :(得分:1)

您需要这样做:

{
  "query": {
    "bool": {
      "filter": [
        {
          "bool": {
            "minimum_should_match": "1",
            "should": [
              {
                "match": {
                  "role": "admin"
                }
              },
              {
                "match": {
                  "role": "manager"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "minimum_should_match": "1",
            "should": [
              {
                "match": {
                  "priority": "high"
                }
              },
              {
                "match": {
                  "priority": "middle"
                }
              }
            ]
          }
        }
      ]
    }
  }
}