How to combine multiple AND with OR in a query?

I am trying to figure out if it is possible to combine multiple AND with OR in a single request.

The query I am trying to make is: field1 == 1 && field2 == 2 && field3!=3 && ( field4==4 || field5==5 || field6!=6 ).
I don't need score for the query so I tried to use filters:

{
  "query": {
    "bool" : {
      "filter": {
        "term" : { "field1" : 1 },
        "term" : { "field2" : 2 }
      },
      "must_not" : {
        "term" : { "field3" : 3 }
      }
    }
  }
}

How should I use field4, field5 and field6 in the query?
Any advice is appreciated.

Hello, Oleksandr.
Shouldnt it be something

{
"query": {
"bool" : {
"filter": [
{"term" : { "field1" : 1 }},
{"term" : { "field2" : 2 }},

    {"bool" : {

            "must_not" : [

                     {"term" : { "field3" : 3 }},
                      { "term" : { "field6" : 6 }  }
            ],
     }}

  ],

}
}
}

Notice json syntax. I suppose that filed 4,5 clasues meaning less in boolean retrieval, which differs from predicate logic.

Thank you Mikhail for pointing it! It helped.
I didn't test yet but I think the following query will work:

{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "field1": 1
          }
        },
        {
          "term": {
            "field2": 2
          }
        },
        {
          "bool": {
            "should": [
              {
                "term": {
                  "field4": 4
                }
              },
              {
                "term": {
                  "field5": 5
                }
              },
              {
                "bool": {
                  "must_not": {
                    "term": {
                      "field6": 6
                    }
                  }
                }
              }
            ]
          }
        }
      ],
      "must_not": {
        "term": {
          "field3": 3
        }
      }
    }
  }
}

Alternatively, you could use the query string query syntax if your boolean conditions get more complex.

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html

Hope, this helps.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.