ElasticSearch High Level REST API【7】聚合

获取平均值聚合示例,最大值、最小值、求和类似

public void aggregation(){
       RestHighLevelClient client = elasticClient.getRestHighLevelClient();
       SearchRequest searchRequest = new SearchRequest();
       SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
       TermsAggregationBuilder aggregation = AggregationBuilders.terms("by_sex")
               .field("sex.keyword");   //text类型不能用于索引或排序,必须转成keyword类型
       aggregation.subAggregation(AggregationBuilders.avg("avg_age")
               .field("age"));  //avg_age 为子聚合名称,名称可随意
       searchSourceBuilder.aggregation(aggregation);
       searchRequest.source(searchSourceBuilder);
       SearchResponse searchResponse = null;
       try {
           searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
       } catch (IOException e) {
           e.printStackTrace();
       }
       Aggregations aggregations = searchResponse.getAggregations();
       Terms byCompanyAggregation = aggregations.get("by_sex");
       Terms.Bucket elasticBucket = byCompanyAggregation.getBucketByKey("女性");
       Avg averageAge = elasticBucket.getAggregations().get("avg_age");
       double avg = averageAge.getValue();
       System.out.println("女性平均年龄:"+avg);
}

Stats统计

public void stats(){
       RestHighLevelClient client = elasticClient.getRestHighLevelClient();
       SearchRequest searchRequest = new SearchRequest();
       SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
       TermsAggregationBuilder aggregation = AggregationBuilders.terms("by_sex")
               .field("sex.keyword");  //by_sex为聚合名称,名称可随意
       aggregation.subAggregation(AggregationBuilders.stats("stat_age")
               .field("age"));  //avg_age 为子聚合名称,名称可随意
       searchSourceBuilder.aggregation(aggregation);
       searchRequest.source(searchSourceBuilder);
       SearchResponse searchResponse = null;
       try {
           searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
       } catch (IOException e) {
           e.printStackTrace();
       }
       Aggregations aggregations = searchResponse.getAggregations();
       Terms byCompanyAggregation = aggregations.get("by_sex");
       List<? extends Terms.Bucket> buckets = byCompanyAggregation.getBuckets();
       for (Terms.Bucket bucket : buckets) {
           Stats statAge = bucket.getAggregations().get("stat_age");
           System.out.println(bucket.getKey()); //获取分组名称
           System.out.println("平均值:"+statAge.getAvg());
           System.out.println("总数:"+statAge.getSum());
           System.out.println("最大值:"+statAge.getMaxAsString());
           System.out.println("最小值:"+statAge.getMin());
       }
   }

 

posted @ 2019-01-24 10:48  有追求的程序员  阅读(5788)  评论(0编辑  收藏  举报