How to get date difference in weeks between today and date_timestamp field

Hello Team,

could any one help me to write scripted field to get date difference in weeks between current datetime and doc['timestamp'].
to get current date time used datetime.new date().getTime()

Used this script.
(new Date().getTime()-doc['timestamp'].value)/7;

please give any other way if we have!

Refer error:
{
"root_cause": [
{
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"(new Date().getTime()-doc['timestamp'].value)/7",
" ^---- HERE"
],
"script": "(new Date().getTime()-doc['timestamp'].value)/7",
"lang": "painless",
"position": {
"offset": 38,
"start": 0,
"end": 47
}
}
],
"type": "search_phase_execution_exception",
"reason": "all shards failed",
"phase": "query",
"grouped": true,
"failed_shards": [
{
"shard": 0,
"index": "kibana_sample_data_logs",
"node": "8mBwNeFOTrucFuoSsAwrog",
"reason": {
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"(new Date().getTime()-doc['timestamp'].value)/7",
" ^---- HERE"
],
"script": "(new Date().getTime()-doc['timestamp'].value)/7",
"lang": "painless",
"position": {
"offset": 38,
"start": 0,
"end": 47
},
"caused_by": {
"type": "class_cast_exception",
"reason": "Cannot apply [-] operation to types [java.lang.Long] and [org.elasticsearch.script.JodaCompatibleZonedDateTime]."
}
}
}
]
}

Thanks in advance.

Rakesh

Used this one too:

(datetime.new Date().getTime()-doc['timestamp'].value)/7

error:
],
"script": "(datetime.new Date().getTime()-doc['timestamp'].value)/7",
"lang": "painless",
"position": {
"offset": 14,
"start": 0,
"end": 39
},
"caused_by": {
"type": "illegal_argument_exception",
"reason": "invalid sequence of tokens near ['Date'].",
"caused_by": {
"type": "no_viable_alt_exception",
"reason": null
}
}
}
}
]
}

I think your question is answered in very complete detail by the Painless docs about using datetime:

Hey Rakesh,

Your script is erroring because doc['timestamp'].value is not a long but a ZonedDateTime see the available methods to convert to long

A simple example could be...

ZonedDateTime now = ZonedDateTime.ofInstant(Instant.ofEpochMilli(new Date().getTime()), ZoneId.of('Z'));
double days = doc['timestamp'].value.until(now, ChronoUnit.DAYS);
double daysInWeek = 7;
days/daysInWeek;

You must assign to double to avoid rounded values.

In addition to the links @wylie provided this is also a good reference Shared API for package java.time | Painless Scripting Language [8.11] | Elastic

Thanks Nick,

This is exactly match with my requirement.

1 Like

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