How can I query many indexes based on a particular field value?

Background:

  • Indexes: index-apple, index-banana, index-orange, etc. Each of them has a field called type.

I wanna query "apple" and "banana":

POST /index-apple,index-banana/_search
{
  "query": {
    "terms": {
      "type": ["apple", "banana"]
    }
  }
}

This query, in my opinion, would function as follows: look up "banana" or "apple" in two indexes.

How can I use a single query to look up "apple" and "banana" separately in their respective indexes?

May be something like this:

PUT _scripts/fruit-template
{
  "script": {
    "lang": "mustache",
    "source": {
      "query": {
        "bool": {
          "should": [
            {
              "bool": {
                "must": [
                  {
                    "terms": {
                      "type": [
                        "{{name}}"
                      ]
                    }
                  }
                ],
                "filter": [
                  {
                    "term": {
                      "_index": "index-{{name}}"
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}
GET _msearch/template
{ }
{ "id": "fruit-template", "params": { "name": "banana" }}
{ }
{ "id": "fruit-template", "params": { "name": "apple" }}

But it's 2 separated queries at the end.

How about using ES|QL ?

ES|QL REST API | Elasticsearch Guide [8.15] | Elastic

not exactly, but something like this :

POST /_query
{
"query": """
FROM index-apple, index-banana
| where "type" == "apple"
| LIMIT 5
"""
}

Thanks for you reply. But I don't think it is related to this question.