当前位置:   article > 正文

Es Java多字段分组查询_es分组查询级联字段

es分组查询级联字段

es按照多个字段分组查询

GET /你的索引/_search
{
	"size": 0,
	"aggregations": {
		"字段一的结果命名": {
			"terms": {
				"field": "startTime.keyword"
			},
			"aggregations": {
				"字段二的结果命名": {
					"terms": {
						"field": "aa.keyword"
					}
				}
			}
		}
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

在这里插入图片描述
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;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/68118
推荐阅读
相关标签
  

闽ICP备14008679号