Search code examples
elasticsearchelasticsearch-dsl

How to define DSL query with combinations of AND & OR logic(OR logic inside AND)?


I'd like to define a DSL query, to describe the query in Lucene below :

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

I know that I can use should to indicate the OR logic, however, the DSL query below :

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

can't achieve what I need, since the data

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

would be considered as valid, but it DOESN'T.

How can I fix my DSL query? I'm using ElasticSearch 5.2.2, thanks!


Solution

  • You need to do it like this:

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