Java操作ElasticSearch(五、聚合分桶)

聚合功能通过 SearchSourceBuilder 的 aggregation(AggregationBuilder aggregation) 方法用来构建聚合条件

其中要用到的各种聚合如:

  • Term 聚合
  • Rang 聚合
  • Sum 聚合

等都通过 AggregationBuilders 来提供

 

 

举例,对性别字段 gender 做聚合,

@Test
public void test23() throws IOException {
    SearchRequest request = new SearchRequest("user");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.matchAllQuery());
    // 聚合分桶
    searchSourceBuilder.aggregation(AggregationBuilders.terms("gender_agg_name").field("gender"));
    request.source(searchSourceBuilder);

    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    SearchHits searchHits = response.getHits();
    System.out.println("命中数:" + searchHits.getTotalHits().value);
    SearchHit[] hits = searchHits.getHits();
    for (SearchHit hit : hits) {
        String sourceAsString = hit.getSourceAsString();
        User user = JSON.parseObject(sourceAsString, User.class);
        System.out.println(user);
    }
    System.out.println("==============================================================");
    Aggregations aggregations = response.getAggregations();
    Terms terms = aggregations.get("gender_agg_name");

    List<? extends Terms.Bucket> buckets = terms.getBuckets();
    for (Terms.Bucket bucket : buckets) {
        // 获取key
        String key = bucket.getKeyAsString();
        System.out.println("key = " + key);
        long count = bucket.getDocCount();
        System.out.println("count = " + count);
    }
}

 

posted @ 2022-12-10 21:04  徐林俊  阅读(400)  评论(0编辑  收藏  举报