ES聚合脚本的使用及API的调用
聚合脚本使用场景
有以下数据结构,需要统计 suspected
字段中的event_type为3时的数据有多少条,event_type为1的数据有多少条,这时候直接使用sum
聚合统计不出来,此时就需要在聚合
中使用脚本
的方式来统计。脚本本质上就是自己写逻辑来处理统计数据的方式。
- 注意es使用脚本的功能很强大,能够查询使用也可以在聚合中使用,但是当数据量大的时候,会有性能问题,所以在场景使用中需要合理评估,是否能使用该技术
数据如图
kibanna语句
此时对应的执行查询的脚本语句为
GET car/_search
{
"size": 0,
"aggs": {
"total_1_agg": {
"sum": {
"script": {
"lang": "painless",
"source": """
int total = 0;
for (int i = 0; i < params._source.suspected.length; ++i) {
if (params._source.suspected[i].event_type == 1) {
total++;
}
}
return total;
"""
}
}
}
}
}
得到的结果
java API
使用java API的方式来调用
使用字符串的方式来传入脚本内容,取的时候正常的使用取聚合的方式来获取即可
这里APi给我们提供了很多种方法,可以直接使用第一个重载方法
String sourceScript
= " int total = 0;" +
" for (int i = 0; i < params._source.suspected.length; ++i) {" +
" if (params._source.suspected[i].event_type == 1) {" +
" total++;" +
" }" +
" }" +
" return total;";
Script script = new Script(sourceScript);
AggregationBuilders.sum("total_1_agg").script(script);
获取聚合数据时,正常获取聚合即可,此时就可以获取到聚合的值来进行后续的业务处理
//...拼接查询条件等
SearchResponse response = client.search(request, EsConfig.COMMON_OPTIONS);
Aggregations aggregations = response.getAggregations();
Sum total1Agg = aggregations.get("total_1_agg");
double value = total1Agg.getValue();