Search code examples
elasticsearchopensearch

Elastic Search - Multiple match condition


I need to write one complex scenario and wondering how to do that - I have 3 different types entry as below

I need to find the call status with **completed **, but there are scenario where status with completed stored in 2 entries.

Record-1 [ Condition-1: when lastOutboundStatus is busy and lastInbountStatus is completed ]

Note: lastOutboundStatus should be busy | it can be other status as well like no-answer, rejected

"lastOutboundStatus": {
  "status": "busy",
  "timeStamp": 1664945413238
 },
 "lastInboundStatus": {
  "status": "completed",
  "timeStamp": 1664945413238
 },

Record-2 [ Condition-2: when lastInbountStatus is completed and lastOutboundStatus does not exist ]

"lastInboundStatus": {
  "status": "completed",
  "timeStamp": 1664945413238
 }

Record-3 [ Condition-3: when lastOutboundStatus is completed, and "lastInboundStatus" may exist or not exist, does not matter - priority is if lastOutboundStatus is completed ]

"lastOutboundStatus": {
  "status": "completed",
  "timeStamp": 1664945413238
 }
"lastInboundStatus": {
  "status": "completed",
  "timeStamp": 1664945413238
 },

With just one single query I need to accommodate the 3 conditions - so that proper records will come. SO when I search with status completed, all above 3 records should come.

Any Ninja can help !!!!

I am newbie here in elasticsearch, need some master's help


Solution

  • You can use the following OR query:

    POST test/_search
    {
      "query": {
        "bool": {
          "minimum_should_match": 1,
          "should": [
            {
              "bool": {
                "filter": [
                  {
                    "term": {
                      "lastInboundStatus.status": "completed"
                    }
                  },
                  {
                    "terms": {
                      "lastOutboundStatus.status": [
                        "busy",
                        "other-status"
                      ]
                    }
                  }
                ]
              }
            },
            {
              "bool": {
                "filter": [
                  {
                    "term": {
                      "lastInboundStatus.status": "completed"
                    }
                  },
                  {
                    "bool": {
                      "must_not": {
                        "exists": {
                          "field": "lastOutboundStatus.status"
                        }
                      }
                    }
                  }
                ]
              }
            },
            {
              "term": {
                "lastOutboundStatus.status": "completed"
              }
            }
          ]
        }
      }
    }