Search code examples
elasticsearchelasticsearch-5elasticsearch-aggregation

How to filter each index in a query with two indexes in Elastic?


I'm trying to make a query to fetch information on two different indexes in Elastic:

GET _search
{
  "query": {
    "bool": {
      "must" : [{
        "bool" : {
          "should" : [{
             "match" : {
               "action": "VoiceQueueAbandonAction"
              }},
              { 
              "match" : {
                "action": "QualifyVoiceWel"
              } 
             }     
           ]
          }
         }
       ],
      "filter": {
        "range": {
          "created_at": {
            "gte": "2022-05-04 00:00:00",
            "lte": "2022-05-04 23:59:59"
          }
        }
      }
    }
  }
}

It's coming correctly, but it's duplicating information, because in the index "qualifications" and "queueevents" there is the same action "QualifyVoiceWel".

In this case, I would need to filter that the "QualifyVoiceWel" field came only from the qualifications index and not from queueevents either!


Solution

  • You can add bool clause inside existing should like below:

    {
      "query": {
        "bool": {
          "must": [
            {
              "bool": {
                "should": [
                  {
                    "match": {
                      "action": "VoiceQueueAbandonAction"
                    }
                  },
                  {
                    "bool": {
                      "must": [
                        {
                          "match": {
                            "action": "QualifyVoiceWel"
                          }
                        },
                        {
                          "term": {
                            "_index": {
                              "value": "qualifications"
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          ],
          "filter": {
            "range": {
              "created_at": {
                "gte": "2022-05-04 00:00:00",
                "lte": "2022-05-04 23:59:59"
              }
            }
          }
        }
      }
    }