有没有办法使用 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 (v1.0.0.Beta2) 的当前 1.0 版本仍然是测试版,也许仍然需要添加此功能,但也没有找到有关这一点的信息。
查看 Github 上的 ES 源代码,我在他们的测试中看到以下内容:
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));
如果有人想知道访问这些存储桶中的实际文档,以下代码可能会有所帮助。
Terms terms = response.getAggregations().get("agg1");
Collection<Terms.Bucket> buckets = terms.getBuckets();
for (Bucket bucket : buckets) {
System.out.println(bucket.getKeyAsText() +" ("+bucket.getDocCount()+")");
}
如果有人正在寻找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();