ElasticSearch 术语聚合脚本时区转换

InT*_*eep 0 elasticsearch elasticsearch-painless

我真的很挣扎。在 Painless 中,我将如何更新以下内容:

 "aggs": {
    "total_messages_per_day_of_week": {
      "terms": {
        "script": {
          "lang": "painless",
          "source": "doc['date'].value.dayOfWeek"
        }
      },
Run Code Online (Sandbox Code Playgroud)

在获取星期几之前,要将 doc.date 中的 UTC 日期时间转换为区域设置(例如“America/Los_Angeles”)?

基本上我想按天数聚合,但其中天数代表所需的时区日,而不是 UTC 日。

提前谢谢了!

Val*_*Val 5

You'd do it like this by first transforming your UTC date into a ZonedDateTime via Instant.atZone() and then taking the day of the week:

Instant date = Instant.ofEpochMilli(doc['timestamp'].value);
ZonedDateTime zdt = date.atZone(ZoneId.of('America/Los_Angeles'));
return zdt.getDayOfWeek().getValue();
Run Code Online (Sandbox Code Playgroud)

And since doc.date.value is actually JodaCompatibleZonedDateTime (i.e. a delegate of ZonedDateTime), in your aggregation you can try this:

{
  ...,
  "aggs": {
    "days": {
      "terms": {
        "script": "doc['timestamp'].value. withZoneSameInstant(ZoneId.of('America/Los_Angeles')).getDayOfWeek().getValue()"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)