ElasticSearch日期直方图

ny6fqffe  于 2021-06-13  发布在  ElasticSearch
关注(0)|答案(1)|浏览(350)

我正在使用elasticsearch日期直方图聚合 @timestamp 现场。这是查询的一部分:

'stats': {
    'date_histogram': {
        'field': '@timestamp',
        'interval': '1h',
        'format': 'yyyy-MM-dd H:m:s'
    }
}

以及 @timestamp :

"@timestamp": {
    "type": "date"
}

我的时间间隔是 1h . 但我还需要从时间戳中提取分钟信息,而不必对其执行聚合 1m . 我试图指定键的字符串表示形式的格式。我得到以下输出:

'key_as_string': '2020-11-07 10:0:0'
'key': 1604743200000

有没有办法在聚合结果中包含分钟数?要么在 key 或者 key_as_string ?
1 @timestamp 在es中索引的示例:

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

ezykj2lf1#

直方图值按公式向下舍入到最接近的桶

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

尽管如果在任何给定的bucket中只有一个值,那么显示精确的分钟似乎很有用,但是直方图通常会聚合一组值,因此当我们使用小时间隔时,谈论基于分钟的bucket键并不是真正有意义的。
也就是说,日期直方图确实接受子聚合,所以如果您想检索单个文档的 @timestamps 在所需的格式中,可以使用 top_hits 聚合 script_fields :

{
  "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
          }
        }
      }
    }
  }
}

或者,您也可能对最常出现的时间戳感兴趣,这些时间戳按分钟分组(秒从 format ):

{
  "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
          }
        }
      }
    }
  }
}

相关问题