【问题标题】:ElasticSearch Term Aggregation script timezone conversionElasticSearch 术语聚合脚本时区转换
【发布时间】:2020-09-30 15:07:11
【问题描述】:

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

 "aggs": {
    "total_messages_per_day_of_week": {
      "terms": {
        "script": {
          "lang": "painless",
          "source": "doc['date'].value.dayOfWeek"
        }
      },

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

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

非常感谢!

【问题讨论】:

    标签: elasticsearch elasticsearch-painless


    【解决方案1】:

    您可以这样做,首先将您的 UTC 日期通过 Instant.atZone() 转换为 ZonedDateTime,然后取一周中的某一天:

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

    由于doc.date.value 实际上是JodaCompatibleZonedDateTime(即ZonedDateTime 的代表),因此在您的聚合中您可以试试这个:

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

    【讨论】:

    • 谢谢,刚刚试过这个:"aggs":{ "period":{ "terms":{ "script":{ "source":"Instant.ofEpochMilli(doc['timestamp'] .value).atZone(ZoneId.of('America/Los_Angeles')).getDayOfWeek().getValue()", "lang":"painless" } }, 'timestamp' 是实际字段,而不是日期。我收到以下错误:error_method_type_exception: cannot convert MethodHandle(Dates)JodaCompatibleZonedDateTime to (Object)long
    • 'timestamp' is the actual field, not date 是什么意思?
    • 我的意思是在文档中存储日期的属性的名称是'timestamp'。我使用上面的“日期”来增加清晰度。希望确保该错误对您有意义。谢谢
    • 好的,有道理。查看我更新的答案,它应该可以工作
    • 太棒了。感谢您的帮助。非常感谢。
    猜你喜欢
    • 2014-07-09
    • 2021-06-06
    • 2021-06-06
    • 2015-11-06
    • 2015-01-21
    • 1970-01-01
    • 2017-07-19
    • 2020-01-23
    • 2019-12-06
    相关资源
    最近更新 更多