Can we script common objects in painless scripts

Considering the following painless script.
"dateadddays" :{
"script" :{
"lang": "painless",
"source" : "int days = 5; long millis = 5 * 24 * 3600 * 1000; long totalmillis = doc.born.value.millis + millis; SimpleDateFormat sdf = new SimpleDateFormat('dd-M-yyyy hh:mm:ss'); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(totalmillis); return sdf.format(cal.getTime());"
}
}

is there a way to store objects such as
SimpleDateFormat sdf = new SimpleDateFormat('dd-M-yyyy hh:mm:ss');

And use it in the multiple scripts.

Unfortunately there is no way to share anything across invocations (per document) in a scoring script.

Also, note that that your example can be done much more simply with the java time api. Here I used an existing ISO format, but you could also use DateTimeFormatter.ofPattern('dd-M-yyyy hh:mm:ss') to get your exact format if it is important.


Instant time = Instant.ofEpochMill(doc.born.value.millis).plus(Duration.ofDays(5));
return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(time);

thanks.
Can we share using stored scripts ?

storing the following script
SimpleDateFormat sdf = new SimpleDateFormat('dd-M-yyyy hh:mm:ss');

and reading as params ?
i am getting the following exception
"lang": "painless",
"caused_by": {
"type": "class_cast_exception",
"reason": "java.util.HashMap cannot be cast to java.text.SimpleDateFormat"
}

can i specify the params type ?

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