2

I am trying to find the elapsed time elapsed time: duration of time b/w now and createdTime

To pass the current_time (ie now) I have added it to the params, and I can access that in the source field by writing params['now'] The problem is that this value of params['now'] is a string and not of type date

The below example works as I have added doc['updatedTime'], in place of params['now'] how can I get it to work with params['now']

WORKING

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

NOT WORKING

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

I have tried multiple combinations and tried different methods supported by the painless language, I was not able to get it work

I faced one or the other exception

Paulo
  • 8,690
  • 5
  • 20
  • 34

3 Answers3

1

Tldr;

It is a format issue.

The params[now] holds a string type value. You need to convert the string into a ZonedDateTime or DateTime.

String to ZonedDateTime

I have been using the painless Lab available in to run the following code.

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;
Paulo
  • 8,690
  • 5
  • 20
  • 34
0
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"
  }
}
取一个好的名字
  • 1,677
  • 14
  • 16
0

do not need formater, just parse it.

"script_fields": {
    "test2": {
      "script": {
        "lang": "painless",
          "source": "ZonedDateTime zdt = ZonedDateTime.parse(params.date); return zdt.withZoneSameInstant(ZoneId.of('Europe/London'));",
          "params": {
          "date": "2023-05-05T19:06:09.324Z"
        }
      }
    }
  },
Rafiq
  • 8,987
  • 4
  • 35
  • 35