在使用es时,我们经常会用到聚合查询。
简单的聚合查询,已经在前面介绍过,详情见: https://www.cnblogs.com/expiator/p/13843969.html
有时,也会用到多字段聚合查询。类似于Mysql的Group By多个字段。
比如,查询统计各个地区的各个日期,各自的订单总量。
es多字段聚合
DSL的格式,如下所示:
{
"size" : 0,
"query" : { },
"aggregations" : {
"自己命名的聚合名称1" : {
"terms" : {
"field" : "字段名称1",
"size" : 20000,
"order" : {
"_term" : "asc"
}
},
"aggregations" : {
"自己命名的聚合统计名称2" : {
"sum" : {
"field" : "字段名称2"
}
},
"自己命名的聚合名称3" : {
"terms" : {
"field" : "字段名称3",
"size" : 20,
"order" : {
"_term" : "asc"
}
},
"aggregations" : {
"自己命名的聚合统计名称4" : {
"sum" : {
"field" : "字段名称4"
}
}
}
}
}
}
}
}
示例如下:
{
"size" : 0,
"query" : { },
"aggregations" : {
"agg_area" : {
"terms" : {
"field" : "area",
"size" : 20000,
"order" : {
"_term" : "asc"
}
},
"aggregations" : {
"sum_area" : {
"sum" : {
"field" : "amount"
}
},
"agg_day" : {
"terms" : {
"field" : "day",
"size" : 20,
"order" : {
"_term" : "asc"
}
},
"aggregations" : {
"sum_day" : {
"sum" : {
"field" : "amount"
}
}
}
}
}
}
}
}
es多字段聚合的java api
示例的代码如下:
public String getAggDSL() {
SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();
//聚合的第二个字段
AggregationBuilder dayAgg = AggregationBuilders.terms("agg_day").field("day")
.order(Terms.Order.aggregation(TERM, true)).size(20)
.subAggregation(AggregationBuilders.sum("sum_day").field("amount"));
//聚合的第一个字段
AggregationBuilder areaDayAgg = AggregationBuilders.terms("agg_area").field("area")
.order(Terms.Order.aggregation(TERM, true)).size(10000)
.subAggregation(AggregationBuilders.sum("sum_area").field("amount"))
.subAggregation(dayAgg);
return searchSourceBuilder.query().aggregation(areaDayAgg).size(0).toString();
}
script实现es多字段聚合
es多字段聚合,对性能要求不高的话,可以使用script。
对A,B等多个字段进行聚合,那也可以直接将它们组合起来,形成A和B相关的script,
只要script的值相同,就聚合到同一组。
查询语句如下:
{
"size" : 0,
"query" : {
"bool" : {
"filter" : [
{
"term" : {
"过滤字段1" : {
"value" : "匹配值"
}
}
},
{
"term" : {
"过滤字段2" : {
"value" : "匹配值"
}
}
}
]
}
}
,"aggregations" : {
"聚合名称" : {
"terms" : {
"script" : {
"inline" : "doc['字段名称1'].values +'-'+ doc['字段名称2'].values",
"lang" : "painless"
},
"size" : 10000,
"order" : {
"排序字段" : "desc"
}
},
"aggregations" : {
"自已命令的聚合名称" : {
"sum" : {
"field" : "聚合求和字段"
}
}
}
}
}
}