赞
踩
@Test public void groupBucket() { //设置要查询的索引 SearchRequest request = new SearchRequest().indices(EdaIndex.EDaIndex.FILE_DETECTION_LOGS.value()); //构建搜索 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); //添加搜索长度 sourceBuilder.size(0); //添加搜索条件 BoolQueryBuilder bqb = new BoolQueryBuilder(); bqb.must(QueryBuilders.termsQuery("recordId.keyword", "16ed281df9164ce9bca8b3eefcb7be3b", "7291bb3e94fc402390895525156917e5", "4f7c23e6e7bb4630bcc463cdb77f9333", "14f826ac3340434a9af26c0540418226", "04a6d0bc146b4f4198659776fffbdaaf", "8d37a7c04d604dcf9ad9b71488815d03")); sourceBuilder.query(bqb); String[] groupFields = {"qualified", "size", "fileType", "qualityScore", "errorType", "articulationScore", "recognitionRateScore", "emptyRateScore"}; TermsAggregationBuilder tab = AggregationBuilders.terms(groupFields[0]).field(groupFields[0].concat(".keyword")); TermsAggregationBuilder tabTemp; TermsAggregationBuilder tabSub = tab; for (int i = 1; i < groupFields.length; i++) { tabTemp = AggregationBuilders.terms(groupFields[i]).field(groupFields[i].concat(".keyword")); tabSub.subAggregation(tabTemp); tabSub = tabTemp; } //添加聚合查询 sourceBuilder.aggregation(tab); //创建请求 request.source(sourceBuilder); //发送请求 SearchResponse response = null; try { response = esClient.search(request, RequestOptions.DEFAULT); } catch (IOException e) { throw new RuntimeException(e); } Aggregations aggregations = response.getAggregations(); List<Map<String, Object>> list = new ArrayList<>(); parseData(aggregations.getAsMap(), new HashMap<>(), list); for (Map<String, Object> stringObjectMap : list) { stringObjectMap.forEach((k, v) -> System.out.print(k + "=" + v + ", ")); System.out.println("------------------------------------"); } } /** * 解析数据 * @param asMap 被解析的数据 * @param cashMap 缓存节点数据 * @param lists 最终结果 */ private static void parseData(Map<String, Aggregation> asMap, Map<String, Object> cashMap, List<Map<String, Object>> lists) { for (String key : asMap.keySet()) { Map<String, Object> map = new LinkedHashMap<>(); Terms terms = (Terms) asMap.get(key); String name = terms.getName(); List<? extends Terms.Bucket> termsBuckets = terms.getBuckets(); for (Terms.Bucket termsBucket : termsBuckets) { String keyAsString = termsBucket.getKeyAsString(); map.put(name, keyAsString); map.putAll(cashMap); Map<String, Aggregation> childMap = termsBucket.getAggregations().asMap(); if (MapUtils.isNotEmpty(childMap)) { parseData(childMap, map, lists); } else { long count = termsBucket.getDocCount(); cashMap.put(name, keyAsString); cashMap.put("count", count); lists.add(cashMap); } } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。