赞
踩
es按照多个字段分组查询
GET /你的索引/_search { "size": 0, "aggregations": { "字段一的结果命名": { "terms": { "field": "startTime.keyword" }, "aggregations": { "字段二的结果命名": { "terms": { "field": "aa.keyword" } } } } } }
java 代码实现:
@Autowired private RestHighLevelClient client; public Map<Object,List<Map<Object,Long>>> searchStationLineChart(String index,String stationId,String time) throws IOException { //搜索请求 SearchRequest request = new SearchRequest(index); //请求条件构建器,这里和mybatis中的自定义查询有点类型 SearchSourceBuilder builder = new SearchSourceBuilder(); // 分组 TermsAggregationBuilder oneBuilder = AggregationBuilders.terms("one").field("startTime.keyword"); TermsAggregationBuilder twoBuilder = AggregationBuilders.terms("two").field("aa.keyword"); oneBuilder.subAggregation(twoBuilder); builder.aggregation(oneBuilder); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); //条件 boolQueryBuilder.must(QueryBuilders.termsQuery("字段" + ".keyword","字段值")); builder.query(boolQueryBuilder); request.source(builder); //建立SearchResponse SearchResponse response; //从Spring中拿ES连接 response = client.search(request, RequestOptions.DEFAULT); Map<Object,List<Map<Object,Long>>> returnMap = new HashMap<>(16); if (response.getAggregations() != null) { Terms oneTerm = (Terms) response.getAggregations().asMap().get("one"); for (Terms.Bucket bucket : oneTerm.getBuckets()) { List<Map<Object,Long>> list = new ArrayList<>(); System.out.println("one下面的" + bucket.getKey() + ", count是: " + bucket.getDocCount()); Terms twoTerm = (Terms) bucket.getAggregations().asMap().get("two"); for (Terms.Bucket twoTermBucket : twoTerm.getBuckets()) { System.out.println("two下面的" + twoTermBucket.getKey() + ", count是: " + twoTermBucket.getDocCount()); Map<Object, Long> map = new HashMap<>(16); map.put(twoTermBucket.getKey(),twoTermBucket.getDocCount()); list.add(map); } returnMap.put(bucket.getKey(),list); } } return returnMap; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。