nabrugir nabrugir - 4 months ago 26
Java Question

elasticsearch Get aggregations in Java

How can I get the aggregations of a query in Java?

This is my query:

GET my_dataset/document/_search
{
"query": {
"match": {
"docId": "1"
}
},
"aggs": {
"text": {
"avg": {
"script": "doc['text'].values.size()"
}
}
}
}


This is the output that I get

..
},
"aggregations": {
"text": {
"value": 32
}
}


How can I get the value 32? I am trying the following with no success

response.getAggregations().getValue("text");


This is how I build the query in Java and get the response

XContentBuilder aggregationBuilder = XContentFactory.jsonBuilder();
aggregationBuilder.startObject()
.startObject("query")
.startObject("match")
.field("docId", docID)
.endObject()
.endObject()
.startObject("aggs")
.startObject("text")
.startObject("max")
.field("script", "doc['text'].values.size()")
.endObject()
.endObject()
.endObject()
.endObject();

SearchResponse response = client.prepareSearch("my_dataset").setTypes("document")
.setSource(aggregationBuilder)
.execute()
.actionGet();


This is the response that I got while debugging
enter image description here

Answer

The solution that worked is

response.getAggregations().get("text").getProperty("value") 

getProperty("value") has to be used instead of getValue().