ES-JavaAPI实现 group by 查询

public Set<String> queryBzms() {
    Set<String> result = new HashSet<>();
    try {
        // 搜索出成功上报的原始数据
        Object[] objects = new Object[]{};
        // 查询的结果字段,类似于(select id, XSE from ..)
        String[] fields = {"BZM"};
        FetchSourceContext sourceContext = new FetchSourceContext(true, fields, null);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.boolQuery().must(QueryBuilders.existsQuery("BZM")));
        searchSourceBuilder.fetchSource(sourceContext);
        searchSourceBuilder.aggregation(AggregationBuilders.terms("BZM_group").field("BZM").size(Constant.max_es_size));
        String[] indes = {this.getAliase()};
        SearchRequest searchRequest = new SearchRequest(indes, searchSourceBuilder);
        searchSourceBuilder.size(0);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        long total = 0;
        Terms terms = searchResponse.getAggregations().get("BZM_group");
        for (Terms.Bucket bucket : terms.getBuckets()) {
            String bzm = bucket.getKeyAsString();
            result.add(bzm);
            total += 1;
        }
        logger.info("-------------- query BZM number by SpecificationEs to success : {} ----------------", total);
    } catch (Exception e){
        logger.error("-------------- query BZM by SpecificationEs to error : {} ----------------", e.getMessage());
    }
    return result;
}

 

posted @ 2021-05-10 10:57  朝油  阅读(901)  评论(0编辑  收藏  举报