es 多个字段 group by
{ "size": 0, "aggregations": { "createDate": { "date_histogram": { "field": "createDate", "format": "yyyy-MM-dd", "time_zone": "+08:00", "calendar_interval": "1d", "offset": 0, "order": { "_key": "asc" }, "keyed": false, "min_doc_count": 1 }, "aggregations": { "userAccount": { "terms": { "field": "userAccount" } } } } } }
GET 索引name/索引type/_search { "size": 0, "aggregations": { "字段一的结果命名": { "terms": { "field": "要group的字段" }, "aggregations": { "字段二的结果命名": { "terms": { "field": "要group的字段" } } } } } }
代码实现
public void demo1(RestHighLevelClient client) { // group TermsAggregationBuilder oneBuilder = AggregationBuilders.terms("one").field("flowCode.keyword"); TermsAggregationBuilder twoBuilder = AggregationBuilders.terms("two").field("stepExecuteId"); oneBuilder.subAggregation(twoBuilder); // search SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.aggregation(oneBuilder); // request SearchRequest searchRequest = new SearchRequest("index"); searchRequest.types("type"); searchRequest.source(searchSourceBuilder); try { SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); Terms oneTerm = (Terms) response.getAggregations().asMap().get("one"); for (Terms.Bucket bucket : oneTerm.getBuckets()) { 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()); } } } catch (Exception ex) { ex.printStackTrace(); } }
参考:https://blog.csdn.net/cainiao1412/article/details/120876972