Search code examples
elasticsearchnosqlelasticsearch-aggregation

Single query for terms aggregation with or without nested objects


I want to get an aggregation of all the unique values for a field. I found that this query works well for a "simple" field with no nested type in the json path.

GET /_search
{
  "aggs": {
    "myResult": {
      "terms": { "field": "school.student.name" }
    }
  },
  "size": 0
}

However, when one of the objects in the path is of nested type, I have to make a different request. Let say student is nested just for the example, then I change the query like this:

GET /_search
{
  "aggs": {
    "myResult": {
      "nested": {
         "path": "school.student"
      }
      "aggs": {
        "myResult2": {
           "terms": { "field": "school.student.name" }
        }
      }
    }
  },
  "size": 0
}

However, in my app, I only have the json path such as "school.student.name" but I do not know if there is a nested object, and who is the nested. I did not find any solution to make a single request that could work to handle both case, and I end up with a configuration file where I have to explicitly list all the nested path that I have in my elastic database, to build the correct request. However, if I have hundreds of fields, this is not maintainable. Does elastic really do not implement such a simple and basic feature?

I just want to get all unique values corresponding to a json path in my elastic database.

Would you have a better solution than the config file?


Solution

  • No need for configuration file, you should directly retrieve the mapping as it is currently stored in ES, parse it and you'd always have the right fields.