0

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?

1
  • 1
    can you please share some sample index data, and expected search result ? Commented Apr 24, 2022 at 4:42

1 Answer 1

2

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 }}
          ]
        }
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.