19、ES实战:实现常用聚合查询-max聚合、min聚合、avg聚合、sum聚合、cardinality聚合

max聚合查询
最大值聚合查询使用

public class EsAgg throws UnknownHostException{
   
     
    public void maxAgg(TransportClient client){
   
     
       //最大值聚合查询(max)
       AggregationBuilder agg = AggregationBuilders.max("aggMax").field("age");

	   SearchResponse response = client.prepareSearch("lib3").addAggregation(agg).get();
	   //获取最大值聚合结果
	   Max max = response.getAggregations().get("aggMax");
	   Systtem.out.println(max.getValue());
    }
}

min聚合查询
最小值聚合查询使用

public class EsAgg throws UnknownHostException{
   
     
    public void minAgg(TransportClient client){
   
     
       //最小值聚合查询(min)
       AggregationBuilder agg = AggregationBuilders.min("aggMin").field("age");

	   SearchResponse response = client.prepareSearch("lib3").addAggregation(agg).get();
	   //获取最大值聚合结果
	   Min min = response.getAggregations().get("aggMin");
	   Systtem.out.println(min.getValue());
    }
}

avg聚合查询
平均值聚合查询使用

public class EsAgg throws UnknownHostException{
   
     
    public void avgAgg(TransportClient client){
   
     
       //平均值聚合查询(min)
       AggregationBuilder agg = AggregationBuilders.min("aggAvg").field("age");

	   SearchResponse response = client.prepareSearch("lib3").addAggregation(agg).get();
	   //获取平均值聚合结果
	   Avg avg = response.getAggregations().get("aggAvg");
	   Systtem.out.println(avg.getValue());
    }
}

sum聚合查询
求和聚合查询使用

public class EsAgg throws UnknownHostException{
   
     
    public void sumAgg(TransportClient client){
   
     
       //求和聚合查询(min)
       AggregationBuilder agg = AggregationBuilders.min("aggSum").field("age");

	   SearchResponse response = client.prepareSearch("lib3").addAggregation(agg).get();
	   //获取求和聚合结果
	   Sum sum = response.getAggregations().get("aggSum");
	   Systtem.out.println(sum.getValue());
    }
}

cardinality聚合查询
基数(字段中互不相同的值的个数)聚合查询使用

public class EsAgg throws UnknownHostException{
   
     
    public void cardinalityAgg(TransportClient client){
   
     
       //基数聚合查询(min)
       AggregationBuilder agg = AggregationBuilders.cardinality("aggCardinality").field("age");

	   SearchResponse response = client.prepareSearch("lib3").addAggregation(agg).get();
	   //基数求和聚合结果
	   Cardinality cardinality = response.getAggregations().get("aggCardinality");
	   Systtem.out.println(cardinality.getValue());
    }
}

版权声明:本文不是「本站」原创文章,版权归原作者所有 | 原文地址: