Parse Date from Script_Fields Params

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 langauge, I was not able to get it work

I faced one or the other exception

This example below returns the difference of days between dates, you can edit to achieve your goal.
The difference is that the currentdate is already in the millis.

GET index_002/_search
{
  "_source": [
    "name", "create_date"
  ],
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "diff_dates": {
      "script": {
        "source": """
        Instant instant = Instant.ofEpochMilli(params.current_date);
        ZonedDateTime now = ZonedDateTime.ofInstant(instant, ZoneId.of('Z'));
        return doc['create_date'].value.until(now, ChronoUnit.DAYS);
        """,       
        "params": {
          "current_date": 1650516960000
        }
      }
    }
  }
}
1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.