Home > Back-end >  Combined OR and AND query for elastic search
Combined OR and AND query for elastic search

Time:04-01

Can someone please help to create elastic search query for below case scenario.

((Field1=Keyword1 AND Field2=Keyword1) OR (Field1=Keyword2 AND Field2=Keyword2) OR ...

Thank you in advance.

CodePudding user response:

It's basically a top-level bool/should with nested bool/filter

{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "Field1": "Keyword1"
                }
              },
              {
                "term": {
                  "Field2": "Keyword1"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "Field1": "Keyword2"
                }
              },
              {
                "term": {
                  "Field2": "Keyword2"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

CodePudding user response:

one of the simplest you can use is Query String type of query from Elasticsearch. this will create bool query internally.

{
  "query": {
    "query_string": {
      "query": "((Field1:Keyword1 AND Field2:Keyword1) OR (Field1:Keyword2 AND Field2:Keyword2) OR (Field2:Keyword2))"
    }
  }
}
  • Related