Convert a field from String to Number using Painless in Kibana – Elasticsearch

The Java method Integer.parseInt should make the trick, i.e:
return Integer.parseInt(doc['myField.keyword'].value)

If there some empty fields, add a condition:
if(!doc['myField.keyword'].empty){
return Integer.parseInt(doc['myField.keyword'].value)
}
return 0

If all fields do not contain numeric characters, use regex:
if(!doc['myField.keyword'].empty) {
def m = /^([0-9]+)$/.matcher(doc['myField.keyword'].value);
if ( m.matches() ) {
return Integer.parseInt(m.group(1))
}
}
return 0

Note: regex is by default disabled in Elasticsearch, you will get the error below if you don’t enable it. Set [script.painless.regex.enabled] to [true] in elasticsearch.yml to enable it

{
"root_cause": [
{
"type": "script_exception",
"reason": "compile error",
"script_stack": [
"... yword'].empty) {\ndef m = /^([0-9]+)$/.matcher(doc[ ...",
" ^---- HERE"
],
"script": "if(!doc['myField.keyword'].empty) {\ndef m = /^([0-9]+)$/.matcher(doc['myField.keyword'].value);\nif ( m.matches() ) {return Integer.parseInt(m.group(1))}}\nreturn 0",
"lang": "painless"
}
],
"type": "search_phase_execution_exception",
"reason": "all shards failed",
"phase": "query",
"grouped": true,
"failed_shards": [
{
"shard": 0,
"index": "logstash-2018.12.21",
"node": "nP0PTyybSeO5yTMsqWvLiA",
"reason": {
"type": "script_exception",
"reason": "compile error",
"script_stack": [
"... yword'].empty) {\ndef m = /^([0-9]+)$/.matcher(doc[ ...",
" ^---- HERE"
],
"script": "if(!doc['myField.keyword'].empty) {\ndef m = /^([0-9]+)$/.matcher(doc['myField.keyword'].value);\nif ( m.matches() ) {return Integer.parseInt(m.group(1))}}\nreturn 0",
"lang": "painless",
"caused_by": {
"type": "illegal_state_exception",
"reason": "Regexes are disabled. Set [script.painless.regex.enabled] to [true] in elasticsearch.yaml to allow them. Be careful though, regexes break out of Painless's protection against deep recursion and long loops."
}
}
}
]
}

Leave a Reply

Your email address will not be published.