How to get MonthYear from DateTime using Painless

Hello team,

I wrote a script to get month (string) = doc['@timstamp'].value.getMonth().
Year=doc['@timstamp'].value.getYear().

Used concatenation montheYear=doc['@timstamp'].value.getMonth()+doc['@timstamp'].value.getYear().

Error: String + integer is not possible .

please help me to get year in string or else any other way we have to get monthyear (eg;Jan2021).

Thanks in advance

Regards
Rakesh R

Have you tried casting the year, or using String.format() or casting? Eg

montheYear = doc['@timstamp'].value.getMonth() + String.format("%d", doc['@timstamp'].value.getYear())

Thank you Patrick for responding..
Could you please give one Eg for casting?
Here is the error with String . format

{
"root_cause": [
{
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"doc['TimeStamp'].value.getMonth() + String.format("%d", doc['TimeStamp'].value.getYear())",
" ^---- HERE"
],
"script": "doc['TimeStamp'].value.getMonth() + String.format("%d", doc['TimeStamp'].value.getYear())",
"lang": "painless",
"position": {
"offset": 78,
"start": 0,
"end": 89
}
}
],
"type": "search_phase_execution_exception",
"reason": "all shards failed",
"phase": "query",
"grouped": true,
"failed_shards": [
{
"shard": 0,
"index": "iq",
"node": "uJDR1PCXTdSJpz--zeIPBg",
"reason": {
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"doc['TimeStamp'].value.getMonth() + String.format("%d", doc['TimeStamp'].value.getYear())",
" ^---- HERE"
],
"script": "doc['TimeStamp'].value.getMonth() + String.format("%d", doc['TimeStamp'].value.getYear())",
"lang": "painless",
"position": {
"offset": 78,
"start": 0,
"end": 89
},
"caused_by": {
"type": "wrong_method_type_exception",
"reason": "cannot convert MethodHandle(JodaCompatibleZonedDateTime)int to (Object)Object"
}
}
}
]
}

I mentioned casting in case you were familiar with it, but you should use the String.format() method if you're not familiar with casting.

The problem appears to be with the doc['TimeStamp'].value.getMonth() call. Here's some doc on working with date fields in Painless: Using Datetime in Painless | Painless Scripting Language [master] | Elastic

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