elasticsearch 从Script_Fields参数解析日期

hgqdbh6s  于 2022-11-02  发布在  ElasticSearch
关注(0)|答案(2)|浏览(257)

我正在尝试查找已用时间已用时间:持续时间B/w nowcreatedTime
为了传递current_time(即now),我已经将其添加到params中,并且可以通过写入params['now']source字段中访问它。问题是params['now']的值是字符串,而不是日期类型
下面的示例的工作原理是我添加了doc['updatedTime'],代替了params['now'],如何让它与params['now']一起工作
工作中

GET entity.incident_action_item/_search
{
  "script_fields": {
    "timeElapsed": {
      "script": {
        "source": "doc['updatedTime'].value.toInstant().getEpochSecond() - doc['createdTime'].value.toInstant().getEpochSecond()",
        "params": {
          "now": "2022-03-31T17:18:28.153+0530"
        }
      }
    }
  }
}

不工作

GET entity.incident_action_item/_search
{
  "script_fields": {
    "timeElapsed": {
      "script": {
        "source": "params['now'].value.toInstant().getEpochSecond() - doc['createdTime'].value.toInstant().getEpochSecond()",
        "params": {
          "now": "2022-03-31T17:18:28.153+0530"
        }
      }
    }
  }
}

我已经尝试了多种组合,并尝试了不同的方法支持的无痛语言,我是不能让它的工作
我遇到过一个或另一个例外

qpgpyjmq

qpgpyjmq1#

Tldr;

这是一个格式问题。
params[now]保存一个字符串类型值。您需要将该字符串转换为ZonedDateTimeDateTime

将字符串转换为区域日期时间

我一直在使用中提供的painless Lab来运行以下代码。

String datetime = "2022-03-31T17:18:28.153+0530";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxxx");
ZonedDateTime zdt = ZonedDateTime.parse(datetime, dtf);
return zdt;
h9a6wy2h

h9a6wy2h2#

POST _reindex
{
  "source": {
    "index": "old_index"
  },
  "dest": {
    "index": "new_index"
  },
  "script": {
    "source": """
      String dateTime = ctx._source.createDateTimeStr;

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS").withZone(ZoneId.systemDefault());
        ZonedDateTime date = ZonedDateTime.parse(dateTime, df);
          DateTimeFormatter df2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
  ctx._source.createDateTime = date.format(df2)

""",
    "lang": "painless"
  }
}

相关问题