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

时间:2016-11-07 22:53:16

标签: elasticsearch timezone elasticsearch-painless

通过以下聚合并使用ES5,我想获得dayOfWeek& hourOfDay基于给定的时区(作为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',
              },
            },
          },
        },
      },
    },

2 个答案:

答案 0 :(得分:7)

使用无痛发现解决方案。因为他们正在将弹性搜索从Joda迁移到本地java.time,所以对Joda的支持并不好无痛。

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

答案 1 :(得分:4)

这样的事情应该有效:

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

请注意。以上不会因为被锁定而does not allow you to edit the whitelist.而无痛无效。