Home > Enterprise >  How do I match by all objects in an array of objects in Elasticsearch?
How do I match by all objects in an array of objects in Elasticsearch?

Time:04-25

I want to get documents like below with match from Elasticsearch.

{
  "configurationId": "dp4wb8kpw4k1s2z",
  "type": 1,
  "items": [
    {
      "text": "car",
      "rank": 1
    },
    {
      "text": "ship",
      "rank": 2
    }
  ],
  "date": "2021-07-08"
}

But I want a match on all objects in the items array and I want to get documents with this match. For example, the text value of the object with a rank value of 1 in the items array should definitely be "car", and the text value of the object with a rank value of 2 in the array should definitely be "ship".

How do I write a query in Elasticsearch for this?

CodePudding user response:

You need to use nested object instead of array of object in Elasticsearch.

Arrays of objects do not work as you would expect: you cannot query each object independently of the other objects in the array. If you need to be able to do this then you should use the nested data type instead of the object data type.

for more information check Elasticsearch official documentation about arrays here and for Nested object here.

After changing your mapping to nested object you will be able to query like this:

Query:

GET my-index-000001/_search
{
  "query": {
    "nested": {
      "path": "items",
      "query": {
        "bool": {
          "must": [
            { "match": { "items.text": "car" }},
            { "match": { "items.rank": 1 }}
          ]
        }
      }
    }
  }
}
  • Related