How to sub aggregation from nested aggregation in Java

I have some nested fields, of which I want to calculate all distinct values, for example:

"author":{
  "type":"nested",
  "properties":{
    "first_name":{
      "type": "text",
      "fields": {
        "keyword": {
          "type": "keyword",
          "ignore_above": 256
         }
       }
     }
   "last_name":{
      "type": "text",
      "fields": {
         "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
       }
    }
 }

Suppose I need all unique first names, so I am adding an aggregation like this :

GET /statementmetadataindex/data/_search?size=0
{
  "aggs": {
    "distinct_authors": {
      "nested": {
        "path": "authors"
      },
      "aggs": {
        "distinct_first_names": {
          "terms": {
            "field": "authors.first_name.keyword"
          }
        }
      }
    }
  }
}

which returns an aggregation like this:

"aggregations" : {
    "distinct_authors" : {
      "doc_count" : 20292,
      "distinct_first_names" : {
        "doc_count_error_upper_bound" : 4761,
        "sum_other_doc_count" : 124467,
        "buckets" : [
          {
            "key" : "Charles",
            "doc_count" : 48411
          },
          {
            "key" : "Rudyard",
            "doc_count" : 30954
          }
        ]
      }
    }
  } 

Now, I am using Nested aggregation builder in the java code like this :

NestedAggregationBuilder uniqueAuthors=AggregationBuilders.nested("distinct_authors", "authors");
TermsAggregationBuilder distinct_first_name= AggregationBuilders.terms("distinct_first_names")
 .field("authors.first_name.keyword").size(size);
uniqueAuthors.subAggregation(distinct_first_name);

and I usually get the aggregation like this from the response:

Terms distinct_authornames=aggregations.get("distinct_authors");

but the buckets that I need are in the sub-aggregation "distinct_first_names" inside "distinct_authors" , so how do I parse the aggregation result to get the unique buckets with the first names?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.