es分组聚合Agg nested
private void test(){ //第一组聚合,按brandDataNested的name分组 //这个size是一个可配置的精度 TermsAggregationBuilder brandNameAgg = AggregationBuilders.terms("brand") .field("brandDataNested.name.keyword").size(10); //第二组聚合,按name分组之后再使用sum求销额的和 String sumName = "brandSalesVolume"; SumAggregationBuilder brandSalesVolume = AggregationBuilders.sum(sumName).field("brandDataNested.salesVolume"); //第一组聚合中提交第二组聚合 brandNameAgg.subAggregation(brandSalesVolume); //聚合排序,这里使用销额倒排 brandNameAgg.order(BucketOrder.aggregation(sumName, false)); //在最外层的查询将agg聚合设置进去,并且使用nested NestedAggregationBuilder nestedAggregationBuilder = AggregationBuilders.nested("brandDataNested", "brandDataNested") .subAggregation(brandNameAgg); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //此处可以添加筛选语句 // searchSourceBuilder.query(query); //聚合查询 searchSourceBuilder.aggregation(nestedAggregationBuilder); //只返回聚合统计结果,不返回关联的具体文档 searchSourceBuilder.size(0); SearchRequest request = new SearchRequest("live_room"); request.source(searchSourceBuilder); try { SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT); //获取所有桶 Aggregations brandNameAggregations = search.getAggregations(); ParsedNested brandDataNested = brandNameAggregations.get("brandDataNested"); Aggregations brandDataNestedAggregations = brandDataNested.getAggregations(); Terms brandNameTerms = brandDataNestedAggregations.get("brand"); for (Terms.Bucket brandNameTermsBucket : brandNameTerms.getBuckets()) { Aggregations aggregationsSon = brandNameTermsBucket.getAggregations(); String keyAsString = brandNameTermsBucket.getKeyAsString(); long docCount = brandNameTermsBucket.getDocCount(); ParsedSum brandSalesVolumeMax1 = aggregationsSon.get(sumName); double value = brandSalesVolumeMax1.getValue(); } } catch (Exception e) { } }
索引结构:
索引结构 { "properties": { "roomId": { "type": "long" }, "roomName": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "brandDataNested": { "type": "nested", "properties": { "id": { "type": "long" }, "liveSales": { "type": "long" }, "name": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "productNum": { "type": "long" }, "salesVolume": { "type": "long" }, "sort": { "type": "long" } } } } }
参考: https://blog.csdn.net/h321880947/article/details/126096440