elasticsearch,stats聚合多个字段JAVA API

时间:2015-07-30 19:24:09

标签: elasticsearch aggregation

我有以下聚合查询,我测试并运行正常。我想知道如何使用其JAVA API构建等效查询。事实上,我有List<String>每个元素,我想看看统计数据。我怎么能动态地这样做?

提前谢谢。

{
  "from" : 0,
  "size" : 0,
  "aggs": {
    "value_stats" :{
      "stats": {
        "field" : "value"
      }
    },
    "qty_stats":{
      "stats": {"field" : "qty"}
    }
  }
}

1 个答案:

答案 0 :(得分:1)

使用AggregationBuilders

添加聚合非常简单
// 1. replace this list of fields with yours
List<String> statFields = getFields();

// 2. bootstrap the query
SearchRequestBuilder search = node.client().prepareSearch()
    .setSize(0).setFrom(0)
    .setQuery(QueryBuilders.matchAllQuery());

// 3. add a stats aggregation for each of your fields
for (String field : statFields) {
    search.addAggregation(AggregationBuilders.stats(field+"_stats").field(field));
}

// 4. execute the query
SearchResponse response = search.execute().actionGet();