Elasticsearch 使用 Java High Level REST Client 聚合查询

聚合查询不是直接查询文档数据,而是对文档数据按照某些维度进行统计,如果你熟悉 MySql 的聚合查询,这个也就好理解了。之前我们已经学习了使用 RESTful API 聚合查询,现在学 Java High Level REST Client 的聚合查询也就很简单了,

我们还是使用上一篇的文档数据学习聚合查询:


我们一般可以使用AggregationBuilders类的静态方法来构建需要的聚合方式。它会返回一个 Builder 类,当然你也可以直接new一个指定聚合方式的 Builder 类。

1、avg

public void avg() throws IOException {
    SearchRequest request = new SearchRequest("user");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // 统计文档中age字段的平均值,avgAge相当于统计结果的名称
    AvgAggregationBuilder avgBuilder = AggregationBuilders.avg("avgAge").field("age");
    // 设置聚合查询
    searchSourceBuilder.aggregation(avgBuilder);
    request.source(searchSourceBuilder);
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    // 取出统计结果
    Avg avg = response.getAggregations().get("avgAge");
    double value = avg.getValue();
    System.out.println(value);
}

上边是统计age的平均值,注意,由于没有添加其它查询条件,则会统计索引中所有文档。

2、max

统计age的最大值:

public void max() throws IOException {
    SearchRequest request = new SearchRequest("user");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // 统计文档中age字段的最大值
    MaxAggregationBuilder maxBuilder = AggregationBuilders.max("maxAge").field("age");
    searchSourceBuilder.aggregation(maxBuilder);
    request.source(searchSourceBuilder);
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    // 取出统计结果
    Max max = response.getAggregations().get("maxAge");
    double value = max.getValue();
    System.out.println(value);
}

3、min、sum

统计最小值以及求和的实现上边的类似,就不详细说了:

MinAggregationBuilder minBuilder = AggregationBuilders.min("minAge").field("age");
SumAggregationBuilder sumBuilder = AggregationBuilders.sum("sumAge").field("age");

4、range

range表示按区间统计,比如指定时间范围,指定大小区间等。如下统计age在(-∞, 30)、[30,40]、(40,+∞)三个区间的人数:

public void range() throws IOException {
    SearchRequest request = new SearchRequest("user");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // 统计文档中age字段的最大值
    RangeAggregationBuilder rangeBuilder = AggregationBuilders.range("rangeAge")
            .field("age")
            .addUnboundedTo(30)
            .addRange(30, 40)
            .addUnboundedFrom(40);
    searchSourceBuilder.aggregation(rangeBuilder);
    request.source(searchSourceBuilder);
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    // 取出统计结果
    Range range = response.getAggregations().get("rangeAge");
    for (Range.Bucket bucket : range.getBuckets()) {
        // 打印每个区间的人数
        System.out.println("age区间 " + bucket.getKeyAsString() + " 的人数:" + bucket.getDocCount());
    }

统计的结果如下:


5、filter

filter可以按指定的查询条件过滤数据,如下统计姓school北大的人数:

public void filter() throws IOException {
    SearchRequest request = new SearchRequest("user");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // 统计文档中school是北大的人数
    // 先构建查询条件
    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("school.keyword", "北大");
    // 设置过滤统计的查询条件
    FilterAggregationBuilder filterBuilder = AggregationBuilders.filter("count", termQueryBuilder);
    searchSourceBuilder.aggregation(filterBuilder);
    request.source(searchSourceBuilder);
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    // 取出统计结果
    Filter filter = response.getAggregations().get("count");
    double value = filter.getDocCount();
    System.out.println(value);
}

6、count

count是统计数量的,如下根据文档 id 统计索引中的文档数:

public void valueCount() throws IOException {
    SearchRequest request = new SearchRequest("user");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // 根据文档id统计索引的文档数
    ValueCountAggregationBuilder valueCountBuilder = AggregationBuilders.count("count").field("_id");
    searchSourceBuilder.aggregation(valueCountBuilder);
    request.source(searchSourceBuilder);
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    // 取出统计结果
    ValueCount valueCount = response.getAggregations().get("count");
    double value = valueCount.getValue();
    System.out.println(value);
}

7、terms

terms是按指定字段对文档数据进行分组,如下按school字段进行分组,统计出前20组(默认10组),并按每组的数据量升序排列(默认降序):

public void terms() throws IOException {
    SearchRequest request = new SearchRequest("user");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // 按照school分组
    TermsAggregationBuilder termsBuilder = AggregationBuilders.terms("schoolGroup")
            .field("school.keyword")
            // 按每组的数据量升序排列
            .order(BucketOrder.aggregation("_count", true))
            // 最多统计出20组数据
            .size(20);
    searchSourceBuilder.aggregation(termsBuilder);
    request.source(searchSourceBuilder);
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    // 取出统计结果
    Terms terms = response.getAggregations().get("schoolGroup");
    for (Terms.Bucket bucket : terms.getBuckets()) {
        System.out.println(bucket.getKeyAsString() + " 的人数:" + bucket.getDocCount());
    }
}

8、子统计

上边我们使用terms对文档数据按照school字段进行了分组,我们还可以对组内的数据进行其它统计,例如统计age的最小值,这就是子统计。代码如下:

public void sub() throws IOException {
    SearchRequest request = new SearchRequest("user");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // 按照school分组
    TermsAggregationBuilder termsBuilder = AggregationBuilders.terms("schoolGroup")
            .field("school.keyword")
            // 按每组的数据量升序排列
            .order(BucketOrder.aggregation("_count", true))
            // 最多统计出20组数据
            .size(20)
            // 添加子统计
            .subAggregation(AggregationBuilders.min("minAge").field("age"));
    searchSourceBuilder.aggregation(termsBuilder);
    request.source(searchSourceBuilder);
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    // 取出统计结果
    Terms terms = response.getAggregations().get("schoolGroup");
    for (Terms.Bucket bucket : terms.getBuckets()) {
        // 取出子统计的结果
        Min min = bucket.getAggregations().get("minAge");
        System.out.println(bucket.getKeyAsString() + " 的人数:" + bucket.getDocCount() + ",age的最小值:" + min.getValue());
    }
}

9、topHits

前边的各种聚合查询只能统计出最终的结果,我们并不能知道那些文档数据参与了统计,topHits可以用来跟踪正在参与分组聚合统计的文档数据,我在前边terms例子的基础上继续修改,来跟踪每组内的前20条数据(默认10条数据),并按age升序排列:

public void topHits() throws IOException {
    SearchRequest request = new SearchRequest("user");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // 跟踪正在参与分组聚合统计的文档数据
    TopHitsAggregationBuilder topHitsBuilder = AggregationBuilders.topHits("groupData")
            // 跟踪前20条数据
            .size(20)
            // 按age升序排列
            .sort("age", SortOrder.ASC);
    // 按照school分组
    TermsAggregationBuilder termsBuilder = AggregationBuilders.terms("schoolGroup")
            .field("school.keyword")
            // 按每组的数据量升序排列
            .order(BucketOrder.aggregation("_count", true))
            // 最多统计出20组数据
            .size(20)
            // 添加文档数据跟踪
            .subAggregation(topHitsBuilder);
    searchSourceBuilder.aggregation(termsBuilder);
    request.source(searchSourceBuilder);
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    // 取出统计结果
    Terms terms = response.getAggregations().get("schoolGroup");
    for (Terms.Bucket bucket : terms.getBuckets()) {
        System.out.println(bucket.getKeyAsString() + " 的人数:" + bucket.getDocCount());
        // 取出topHits跟踪的文档数据
        TopHits groupData = bucket.getAggregations().get("groupData");
        for (SearchHit hit : groupData.getHits()) {
            System.out.println(hit.getSourceAsString());
        }
        System.out.println("---------------------------------------------------------------------------");
    }
}

聚合查询的相关内容就介绍这么多了,更多的可以查看官方文档。

你可能感兴趣的:(Elasticsearch 使用 Java High Level REST Client 聚合查询)