0

I have an Elastic index with nested documents. I am trying to retrieve multiple documents by ids along with their nested documents. Retrieving the documents themselves is simple enough with a Should query, but where and how would I include the nested doc query in this?

Boolean "Should" query:

GET myIndex/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "id": "123"
          }
        },
        {
          "term": {
            "id": "456"
          }
        },
        {
          "term": {
            "id": "789"
          }
        }
      ]
    }
  }
}

Query to retrieve nested docs:

"nested": {
   "path": "myNestedDocs",
            "query": {
              "match_all": {}
}

It is not possible to add the nested query to each term query, because this gives a parsing exception: "[term] malformed query, expected [END_OBJECT] but found [FIELD_NAME]"

Also, it is not possible to add the nested doc query on the same level as the term queries, because then it would be treated as just another OR clause and simply retrieve all docs from the index.

Any ideas? Thanks!

martin_wun
  • 1,599
  • 1
  • 15
  • 33

1 Answers1

0

As per my understanding, you want to match any one id from list and retrive nested document. If my understanding correct then You need to combined both the query to must clause like below:

{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "id": [
              "123",
              "456",
              "789"
            ]
          }
        },
        {
          "nested": {
            "path": "myNestedDocs",
            "query": {
              "match_all": {}
            }
          }
        }
      ]
    }
  }
}
Sagar Patel
  • 4,993
  • 1
  • 8
  • 19
  • Why do you need the nested query? Even if you don't include the nested query in `must`, all nested documents for those ids will come by default if there is not any source filtering. – YD9 May 10 '22 at 08:34
  • 1
    Ya thats also true, he can create nested query itself (if need to search id inside nested field) and pass list of id in `terms` query. – Sagar Patel May 10 '22 at 08:53
  • 1
    Thanks a lot, Sagar. It works with the "terms" query. I didn't realize that there is this query type where you pass an array of IDs. – martin_wun May 11 '22 at 09:49