在更新查询elasticsearch中轻松获取日期值

Get date value in update query elasticsearch painless

我正在尝试获取两个日期的毫秒值并将它们减去另一个日期。 当我像 doc['begin_time'].value.toInstant().toEpochMilli() 这样使用 ctx._sourse.begin_time.toInstant().toEpochMilli() 时,它会给我运行时错误。 ctx._source.begin_time.date.getYear()(像这样Update all documents of Elastic Search using existing column value)给我运行时错误消息

  "ctx._source.work_time = ctx._source.begin_time.date.getYear()",
  "                                              ^---- HERE"

如果此代码正常工作,我 ctx._source 会得到什么类型 doc['begin_time'].value.toInstant().toEpochMilli()。 我无法在无痛文档中找到如何正确获取值。 begin_time 是日期 100%。

那么,如何编写一个脚本来获取两个日期之间的差异并将其写入另一个整数?

如果仔细观察,链接问题中的脚本语言在 groovy 中,但不再受支持。我们现在(2021)用的叫painless.

这里的要点是 ctx._source 属性是原始的 JSON -- 这意味着日期将是字符串或整数(取决于格式)而不是 java.util.Date 或您可以调用 .getDate() 的任何其他数据类型。这意味着我们必须首先解析值。

因此,假设您的 begin_time 格式为 yyyy/MM/dd,您可以执行以下操作:

POST myindex/_update_by_query
{
  "query": {
    "match_all": {}
  },
  "script": {
    "source": """
      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
      LocalDate begin_date = LocalDate.parse(ctx._source.begin_time, dtf);
      
      ctx._source.work_time = begin_date.getYear()
    """
  }
}

顺便说一句,_update_by_query 脚本上下文(可访问的和不可访问的)是 documented here and working with datetime in painless is nicely documented here