elasticsearch-RestClient数据聚合

上一节中我们讲到DSL的数据聚合操作,这一节我们讲用RestClient如果进行数据聚合操作

先看图

img

聚合的结果也与查询结

果不同,API 也比较特殊。不过同样是 JSON 逐层解析

img

代码演示

@Test
    public void testAggregation() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(20));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Terms brandAgg = response.getAggregations().get("brandAgg");
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            long count = bucket.getDocCount();
            System.out.println("key = " + key+", count = " + count);
        }
    }

结果

key = 7天酒店, count = 30
key = 如家, count = 30
key = 皇冠假日, count = 17
key = 速8, count = 15
key = 万怡, count = 13
key = 华美达, count = 13
key = 和颐, count = 12
key = 万豪, count = 11
key = 喜来登, count = 11
key = 希尔顿, count = 10
key = 汉庭, count = 10
key = 凯悦, count = 8
key = 维也纳, count = 7
key = 豪生, count = 6
key = 君悦, count = 4
key = 万丽, count = 2
key = 丽笙, count = 2

elasticsearch-RestClient数据聚合
https://www.zhaojun.inkhttps://www.zhaojun.ink/archives/1014
作者
卑微幻想家
发布于
2022-01-28
许可协议