striker77
striker77

Reputation: 552

How do I create an elasticsearch query that includes nested data in the results

I need to get data from an elasticsearch query that includes nested data. The source for the data is set to true. Adding 'fields'

"fields":["*"],
"query": {
...

returns all data at the root level.

But I need to get to data that is in a nested document (actually a nested, nested doc). Played around with _source and fields that has the nested object ref

"fields":["products.envs.title"],

but no joy so far. Anyone have any idea on how to get this data as part of query. Query includes aggregations and that are returned fine but also need to get nested data as part of results so that I can check for a flag and return data to call dependent on the flag.

Upvotes: 1

Views: 418

Answers (1)

Adam Łepkowski
Adam Łepkowski

Reputation: 2078

You haven’t specify your mappings and object structure so I created my own as you can see below:

POST /so/so/1
{
   "id": 1,
   "user": {
      "name": "adam",
      "role": {
         "code": "admin"
      }
   }
}

Now let's try to query data and cut return results using fields parameter.
Query:

POST /so/so/_search
{
   "fields": [
      "id",
      "user.role.code"
   ],
   "query": {
      "match_all": {}
   }
}

Result:

"hits": {
      "total": 1,
      "max_score": 1,
      "hits": [
         {
            "_index": "so",
            "_type": "so",
            "_id": "1",
            "_score": 1,
            "fields": {
               "user.role.code": [
                  "admin"
               ],
               "id": [
                  1
               ]
            }
         }
      ]
   }

As you can see everything is working correctly. The problem will be if you want to tell that you want to return entire object like "user" or "user.role" then you will get the "field [X] isn't a leaf field" exception. The only solution is to stop using fields paramter and start using _source parameter to cut your data - this issue is described here: https://github.com/elastic/elasticsearch/issues/4888. Additionally fields parameter is not recommended and you should always use _source parameter as shown below.
Query:

POST /so/so/_search
{
   "_source": [
      "id",
      "user.role.code"
   ],
   "query": {
      "match_all": {}
   }
}

Response:

 "hits": {
      "total": 1,
      "max_score": 1,
      "hits": [
         {
            "_index": "so",
            "_type": "so",
            "_id": "1",
            "_score": 1,
            "_source": {
               "id": 1,
               "user": {
                  "role": {
                     "code": "admin"
                  }
               }
            }
         }
      ]
   }

Upvotes: 1

Related Questions