es按照多个字段分组查询文章来源:https://www.toymoban.com/news/detail-523746.html
GET /你的索引/_search
{
"size": 0,
"aggregations": {
"字段一的结果命名": {
"terms": {
"field": "startTime.keyword"
},
"aggregations": {
"字段二的结果命名": {
"terms": {
"field": "aa.keyword"
}
}
}
}
}
}
java 代码实现:文章来源地址https://www.toymoban.com/news/detail-523746.html
@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;
}
到了这里,关于Es Java多字段分组查询的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!