有没有办法使用java API检索搜索响应中的聚合桶?
{
"took" : 185,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 200,
"max_score" : 1.0,
"hits" : [...]
},
"aggregations" : {
"agg1" : {
"buckets" : [...]
},
"agg2" : {
"buckets" : [...]
}
}
}
目前,可以获得聚合,但我无法弄清楚如何获取数据。
ElasticSearch的当前1.0版本(v1.0.0.Beta2)仍然是测试版,可能仍然需要添加此功能,但也没有找到关于该点的信息。
答案 0 :(得分:33)
查看ES source on Github我在测试中看到以下内容:
SearchResponse response = client().prepareSearch("idx").setTypes("type")
.setQuery(matchAllQuery())
.addAggregation(terms("keys").field("key").size(3).order(Terms.Order.count(false)))
.execute().actionGet();
Terms terms = response.getAggregations().get("keys");
Collection<Terms.Bucket> buckets = terms.getBuckets();
assertThat(buckets.size(), equalTo(3));
答案 1 :(得分:8)
如果有人想知道如何从这些存储桶中获取实际文档,那么代码可能有所帮助。
Terms terms = response.getAggregations().get("agg1");
Collection<Terms.Bucket> buckets = terms.getBuckets();
for (Bucket bucket : buckets) {
System.out.println(bucket.getKeyAsText() +" ("+bucket.getDocCount()+")");
}
答案 2 :(得分:0)
万一有人在寻找sum
聚合,就像将结果分配给org.elasticsearch.search.aggregations.metrics.sum.Sum
变量一样简单:
ElasticConnector connector = ... // initialize ES connector
SearchResponde response = connector.getClient()
.prepareSearch(...)
.setQuery(...)
.addAggregation(AggregationBuilders.sum("my_sum").field(...))
.get();
Sum sum = response.getAggregations().get("my_sum");
double result = sum.getValue();