在 Elasticsearch 中,如何将时区应用于脚本化日期操作?

In Elasticsearch, how can I apply a timezone to a scripted date operation?

通过下面的聚合并使用 ES5,我想根据给定时区(作为标识符从 TZ 数据库提供)获取星期几和星期几。

如何编辑 "doc['created'].date.dayOfWeek' 以调整偏移量?

    aggs: {
      dayOfWeek: {
        terms: {
          script: {
            inline: "doc['created'].date.dayOfWeek",
            lang: 'painless',
          },
        },
        aggs: {
          hourOfDay: {
            terms: {
              script: {
                inline: "doc['created'].date.hourOfDay",
                lang: 'painless',
              },
            },
          },
        },
      },
    },

像这样的东西应该可以工作:

{
  "size": 0,
  "aggregations": {
    "dayOfWeek": {
      "terms": {
        "script": {
          "inline": "doc['created'].date.setZone(org.joda.time.DateTimeZone.forID(tz)); doc['created'].date.dayOfWeek",
          "lang": "groovy",
          "params": {
            "tz": "Europe/London"
          }
        }
      },
      "aggs": {
        "hourOfDay": {
          "terms": {
            "script": {
              "inline": "doc['created'].date.setZone(org.joda.time.DateTimeZone.forID(tz)); doc['created'].date.hourOfDay",
              "lang": "groovy",
              "params": {
                "tz": "Europe/London"
              }
            }
          }
        }
      }
    }
  }
}

您可能需要通过将 script.engine.groovy.inline.aggs: on 添加到 elasticsearch.yml 文件来为 groovy 启用内联脚本。参见:This discussion.

注意。以上不适用于 painless 因为它被锁定并且 does not allow you to edit the whitelist..

找到使用无痛的解决方案。因为他们正在将 elasticsearch 从 Joda 迁移到原生 java.time,对 Joda 的支持在 painless 中并不好

{
  "size": 0,
  "aggregations": {
    "dayOfWeek": {
      "terms": {
        "script": {
          "inline": "Instant.ofEpochMilli(doc.created.date.millis).atZone(ZoneId.of(params.tz)).dayOfWeek",
          "params": {
            "tz": "Europe/London"
          }
        }
      },
      "aggs": {
        "hourOfDay": {
          "terms": {
            "script": {
               "inline": "Instant.ofEpochMilli(doc.created.date.millis).atZone(ZoneId.of(params.tz)).hour",
               "params": {
                  "tz": "Europe/London"
              }
            }
          }
        }
      }
    }
  }
}