Get all documents for _id stored as array values inside the document using elasticsearch query

518 Views Asked by At

Below is my mapping index document sample:

{
  "_index": "sample_index",
  "_type": "default",
  "_id": "id-sample-0005",
  "_score": 1,
  "_source": {
      "name": "Eenst Y kios",
      "ids_mapped": [
         "id-sample-00010",
         "id-sample-00011"
      ]
   }
}

I need to write a query that will get the document based on _id passed as parameter and along with that all the _id value exist in "ids_mapped" field.

GET sample_index/_search
{
  "query": {
    "terms": {
      "_id": [
         "id-sample-0005"
      ]
    }
  }
}

Dont know how to write the query above to meet my requirement. Basically in the above query user will pass only the "id-sample-0005" value as parameter and the query should return 3 documents. i.e. [id-sample-0005,id-sample-00010,id-sample-00011].

Any help is greatly appreciated.

1

There are 1 best solutions below

0
Val On BEST ANSWER

One way of achieving this is by leveraging the terms lookup feature.

The following query would return all three documents with id id-sample-0005, id-sample-00010 and id-sample-00011:

POST sample_index/_search?pretty
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "_id": "id-sample-0005"              <-- input your ID here
          }
        },
        {
          "terms": {
            "_id": {
              "index": "sample_index",
              "type": "default",
              "id": "id-sample-0005",            <-- and here
              "path": "ids_mapped.keyword"
            }
          }
        }
      ]
    }
  }
}

The first sub-constraint returns the main document itself and the second sub-constraint will return the documents with the mapped IDs.