我在弹性搜索中有一个存储系统警报的索引。该索引具有警报的 startTime 和 endTime 等值。我需要获取日期直方图,它指定指定时间间隔内每分钟/每小时发生的警报。要获取我使用了以下查询:
GET ocm_alert/_search
{
"size": 0,
"query": {
"bool": {
"filter": [
{
"range": {
"endTime": {
"from": 1561393800000,
"to": null,
"include_lower": true,
"include_upper": true,
"boost": 1
}
}
},
{
"range": {
"startTime": {
"from": null,
"to": 1562828606000,
"include_lower": true,
"include_upper": false,
"boost": 1
}
}
}
],
"adjust_pure_negative": true,
"boost": 1
}
},
"aggregations": {
"aggs_by_time": {
"date_histogram": {
"script": {
"source": "long startTime = doc['startTime'].value.toInstant().toEpochMilli(); long endTime = doc['endTime'].value.toInstant().toEpochMilli(); List dates = new ArrayList(); long rangeFrom = startTime < 1561116600000l ? 1561116600000l : startTime; long rangeTo = endTime > 1562828606000l ? 1562828606000l : endTime; for(long date = rangeFrom; date < rangeTo ; date+=3600000){dates.add(date)} dates.add(rangeTo);return dates;",
"lang": "painless"
},
"interval": "1h",
"offset": 0,
"order": {
"_key": "asc"
},
"keyed": false,
"min_doc_count": 1
},
"aggregations": {
"aggs_by_severity": {
"min": {
"field": "severity"
}
}
}
}
}
}
结果很好,但结果中的键是使用我在脚本中计算的日期字段计算的。例如,如果警报开始时间为 12:15:00,则密钥计算为 11:30:00,第二个密钥为 12:30:00。但我需要根据我在查询中指定的开始时间(如 12:00:00)启动键值。这样聚合键是 12:00:00 , 13:00:00。