Home > Software engineering >  Querying array with nested objects in Elasticsearch to get multiple objects
Querying array with nested objects in Elasticsearch to get multiple objects

Time:09-30

I have data in Elasticsearch in the below format -

"segments": [
  {"id": "ABC", "value":123},
  {"id": "PQR", "value":345},
  {"id": "DEF", "value":567},
  {"id": "XYZ", "value":789},
]

I want to retrieve all segments where id is "ABC" or "DEF".

I looked up the docs (https://www.elastic.co/guide/en/elasticsearch/reference/7.9/query-dsl-nested-query.html) and few examples on YouTube but the all look to retrieve only a single object while I want to retrieve more than 1.

Is there a way to do this?

CodePudding user response:

You can use nested query with inner hits as shown here.

I hope your index mapping is looks like below and segments field is define as nested

"mappings": {
      "properties": {
        "segments": {
          "type": "nested",
          "properties": {
            "id": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            },
            "value": {
              "type": "long"
            }
          }
        }
      }
    }

You can use below Query:

{
  "_source" : false,
  "query": {
    "nested": {
      "path": "segments",
      "query": {
        "terms": {
          "segments.id.keyword": [
            "ABC",
            "DEF"
          ]
        }
      },
      "inner_hits": {}
    }
  }
}

Response:

"hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 1,
    "hits": [
      {
        "_index": "73895503",
        "_id": "TmM8iYMBrWOLJcwdvQGG",
        "_score": 1,
        "inner_hits": {
          "segments": {
            "hits": {
              "total": {
                "value": 2,
                "relation": "eq"
              },
              "max_score": 1,
              "hits": [
                {
                  "_index": "73895503",
                  "_id": "TmM8iYMBrWOLJcwdvQGG",
                  "_nested": {
                    "field": "segments",
                    "offset": 0
                  },
                  "_score": 1,
                  "_source": {
                    "id": "ABC",
                    "value": 123
                  }
                },
                {
                  "_index": "73895503",
                  "_id": "TmM8iYMBrWOLJcwdvQGG",
                  "_nested": {
                    "field": "segments",
                    "offset": 2
                  },
                  "_score": 1,
                  "_source": {
                    "id": "DEF",
                    "value": 567
                  }
                }
              ]
            }
          }
        }
      }
    ]
  }
  • Related