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;
    }
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐