在使用ElasticSearch中经常会遇到统计、查询需求,实现类似
sql
分组计算、条件查询的语法,ES在这些方面都支持的较不错,用起来也比较方便。笔者就自己开发中用到的Java API举例如下。
分组聚合查询
实现类似select avg(executionTime) from t WHERE executionDate between 'A' AND 'B' group by executionDate ORDER BY executionDate ASC
的查询后聚合。ES分组计算的逻辑是先将executionDate
分组,然后在每个分组内在进行聚合,在API中是两个聚合aggregation
包含的逻辑关系。
- HTTP请求
POST请求体
{
"from":0,
"size":2,
"query": {
"range": {
"executionDate": {
"gte":"2019-01-20",
"lte":"2019-01-25"
}
}
},
"aggregations":{
"executionDateGroup":{
"terms":{
"field":"executionDate"
},
"aggregations":{
"executionTimeAvg":{
"avg":{
"field":"executionTime"
}
}
}
}
}
}
POST返回结果
{
"took": 1510,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 52,
"max_score": 1,
"hits": [
//....
]
},
"aggregations": {
"executionDateGroup": {