Elasticsearch 日期直方图

标签 elasticsearch elasticsearch-aggregation

我在 @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

有没有办法在聚合结果中包含分钟数?在 keykey_as_string 中?

在 es 中索引的一个 @timestamp 示例:

'@timestamp': '2020-12-09T13:50:46.056000Z'

最佳答案

直方图值为 rounded down到最近的桶,遵循公式

bucket_key = Math.floor(value / interval) * interval

尽管如果您在任何给定存储桶中精确地具有一个值,那么显示准确的分钟数似乎很有用,但直方图通常聚合一堆值,因此它不会当我们以小时为间隔时,讨论基于分钟的存储桶键确实很有意义。

话虽如此,日期直方图确实接受子聚合,因此如果您想以所需的格式检索各个文档的@timestamps,您可以使用与 script_fieldstop_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/

相关文章:

python - 在 elasticsearch 中更新索引时出现 RequestError

elasticsearch - NEST是否支持基于脚本的排序?

elasticsearch - Elasticsearch 聚合存储桶保持为空

ElasticSearch 映射折叠/对分组文档执行操作的结果

Elasticsearch 多个聚合不起作用

azure - 使用其 REST API 将 Azure DevOps 指标获取到 Elasticsearch 数据库中?

ruby-on-rails - 重定向搜索表单

elasticsearch - 使用本地卷获取错误 'unknown field hostPath' Kubernetes Elasticsearch

elasticsearch - Elasticsearch 查询过滤器和聚合不起作用

elasticsearch - ElasticSearch聚合可以执行SQL的功能吗?