Multi Index Search - Multiple Queries within the query

You could do this in one query by building a composite query that combines the query that you would wish to execute against a specific index with a term or terms query that filters only to those indices you're interested in.

As an example, here's a query that executes a search request against all indices, but targets indices index-1 and index-2 differently to the rest by using two bool queries in the should clause of a bool query. Each of the inner bool queries combines a must clause (the query to execute) with a filter or must_not clause that determines the indices to apply to.

POST http://localhost:9200/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "query-field": {
                    "value": "query-term"
                  }
                }
              }
            ],
            "filter": [
              {
                "terms": {
                  "_index": [
                    "index-1",
                    "index-2"
                  ]
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "no-match-query-field": {
                    "value": "no-match-query-term"
                  }
                }
              }
            ],
            "must_not": [
              {
                "terms": {
                  "_index": [
                    "index-1",
                    "index-2"
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}
3 Likes