Varun Jain
Varun Jain

Reputation: 507

Elasticsearch Query with And and Or Condition

I have data like below in Elastic

{
  "_index": "prod",
  "_type": "log",
  "_id": "aa",
  "_source": {
    "input_type": "log",
    "sourcetype": "sourcetypeapp1",
    "message": "APP COMPANY|80d596f6-2082-4a1d-bcfc-740478f626ec|001 ErrorMessage: Some error"
    "type": "log",
    "tags": [
      "beats_input_codec_plain_applied"
    ]
  }
}

I wanted to search all the message which contain below data in message :-

(Message : "COMPANY|80d596f6-2082-4a1d-bcfc-740478f626eA|001" AND Message:"ErrorMessage")
Or
(Message : "COMPANY|80d596f6-2082-4a1d-bcfc-740478f626eB|002" AND Message:"ErrorMessage")
Or
(Message : "COMPANY|80d596f6-2082-4a1d-bcfc-740478f626eC|003" AND Message:"ErrorMessage")

i dont know much about elasticsearch query,

i have tried below simple query its not working (with only one condition):

{
  "query": {
    "bool": {
      "must": {
        "bool": {
          "should": [
            {
              "match": {
                "Message": "COMPANY|80d596f6-2082-4a1d-bcfc-740478f626eA|001"
              }
            }
          ]
        }
      }
    }
  }
}

Upvotes: 3

Views: 19202

Answers (2)

Dhavaprathap
Dhavaprathap

Reputation: 308

( (condition11 AND condition12) OR (condition21 AND condition22) )

If this is what you want to achieve, try this

{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              { "match": { "message": "COMPANY|80d596f6-2082-4a1d-bcfc-740478f626eA|001" } },
              { "match": { "message": "ErrorMessage"}}
            ]
          }
        },
        {
          "bool": {
            "must": [
              { "match": { "message": "COMPANY|80d596f6-2082-4a1d-bcfc-740478f626eB|002" } },
              { "match": { "message": "ErrorMessage"}}
            ]
          }
        },
        {
          "bool": {
            "must": [
              { "match": { "message": "COMPANY|80d596f6-2082-4a1d-bcfc-740478f626eC|003" } },
              { "match": { "message": "ErrorMessage"}}
            ]
          }
        }        
      ]
    }
  }
}

But in your example, condition12 and condition22 are same. In that case, you can rewrite it as

{
  "query": {
    "bool": {
      "must": [
        { "match": { "message": "ErrorMessage"}},
        { 
          "bool": {
            "should": [
              { "match": { "message": "COMPANY|80d596f6-2082-4a1d-bcfc-740478f626eA|001" } },
              { "match": { "message": "COMPANY|80d596f6-2082-4a1d-bcfc-740478f626eB|002" } },
              { "match": { "message": "COMPANY|80d596f6-2082-4a1d-bcfc-740478f626eC|003" } }
            ]
          } 
        }
      ]
    }
  }
}

Upvotes: 8

DivyaMenon
DivyaMenon

Reputation: 311

Can you try with something like

{
 "query": {
  "match": {
     "Message": "COMPANY|80d596f6-2082-4a1d-bcfc-740478f626eA|001"
  }
 }
}

Upvotes: 0

Related Questions