我在 @timestamp
字段上使用 elasticsearch 日期直方图聚合。这是查询的一部分:
'stats': {
'date_histogram': {
'field': '@timestamp',
'interval': '1h',
'format': 'yyyy-MM-dd H:m:s'
}
}
以及@timestamp
的映射:
"@timestamp": {
"type": "date"
}
我的时间间隔是1小时
。但我还需要从时间戳中提取分钟信息,而不对 1m
执行聚合。我尝试指定 key 的字符串表示形式的格式。我得到以下输出:
'key_as_string': '2020-11-07 10:0:0'
'key': 1604743200000
有没有办法在聚合结果中包含分钟数?在 key
或 key_as_string
中?
在 es 中索引的一个 @timestamp
示例:
'@timestamp': '2020-12-09T13:50:46.056000Z'
最佳答案
直方图值为 rounded down到最近的桶,遵循公式
bucket_key = Math.floor(value / interval) * interval
尽管如果您在任何给定存储桶中精确地具有一个值,那么显示准确的分钟数似乎很有用,但直方图通常聚合一堆值,因此它不会当我们以小时为间隔时,讨论基于分钟的存储桶键确实很有意义。
话虽如此,日期直方图确实接受子聚合,因此如果您想以所需的格式检索各个文档的@timestamps
,您可以使用与 script_fields
的 top_hits
聚合:
{
"size": 0,
"aggs": {
"stats": {
"date_histogram": {
"field": "@timestamp",
"interval": "1h",
"format": "yyyy-MM-dd H:m:s"
},
"aggs": {
"concrete_values": {
"top_hits": {
"script_fields": {
"ts_with_minutes": {
"script": {
"source": "LocalDateTime.ofInstant(Instant.ofEpochMilli(doc['@timestamp'].value.millis), ZoneId.of('UTC')).format(DateTimeFormatter.ofPattern('yyyy-MM-dd H:m:s'))"
}
}
},
"size": 10
}
}
}
}
}
}
或者,您可能还对最常出现的时间戳感兴趣,按分钟分组(秒在格式
中被省略):
{
"size": 0,
"aggs": {
"stats": {
"date_histogram": {
"field": "@timestamp",
"interval": "1h",
"format": "yyyy-MM-dd H:m:s"
},
"aggs": {
"most_represented_timestamps": {
"terms": {
"field": "@timestamp",
"format": "yyyy-MM-dd H:m",
"size": 10
}
}
}
}
}
}
关于Elasticsearch 日期直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65218245/