如何在 SearchResponse 中使用 elasticSearch java api 访问聚合结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21018493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:00:18  来源:igfitidea点击:

How to access Aggregations result with elasticSearch java api in SearchResponse?

javaelasticsearchbuckets

提问by ThomasC

Is there a way to retrieve the aggregations' buckets in a search response, with the java API ?

有没有办法使用 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" : [...]
    }
  }
}

Currently, it's possible to get the aggregations but I can't figure out how to get the buckets.

目前,可以获取聚合,但我不知道如何获取存储桶。

Current 1.0 version of ElasticSearch (v1.0.0.Beta2) is still a beta version, and maybe this feature still has to be added, but didn't find info on that point too.

目前 ElasticSearch 的 1.0 版本(v1.0.0.Beta2)仍然是 beta 版本,也许这个功能还需要添加,但也没有找到这方面的信息。

采纳答案by mconlin

Looking at the ES source on GithubI see the following in their tests:

查看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));

回答by Charith De Silva

If anyone wonder about accessing actual documents count out of these buckets following code might help.

如果有人想知道从这些存储桶中访问实际文档计数可能会有所帮助。

Terms  terms = response.getAggregations().get("agg1");
Collection<Terms.Bucket> buckets = terms.getBuckets();
for (Bucket bucket : buckets) {
    System.out.println(bucket.getKeyAsText() +" ("+bucket.getDocCount()+")");
}