Convert string to int if it contains only int

String parts = "123"
parts.matches("[0-9]+") ?Integer.parseInt(parts): parts

I am using above script to create a scripted field
if a string contains integer : convert it to int and return
else return as it is
But i am getting errors and scripted field is not getting created.
Can someone point out error. I am very new to ES and painless script

Posting your errors would help,

Please remember to format your code using the </> button.

Note: parts[-1] in this pic corresponds to "parts" in my question

Please don't post pictures of text, they are difficult to read and some people may not be even able to see them.

My Script :
String parts = "123"
parts.matches("[0-9]+") ?Integer.parseInt("parts"): parts

This is the error i got :

Note: parts[-1] here corresponds to "parts" in My Script

{
"root_cause": [
{
"type": "script_exception",
"reason": "compile error",
"script_stack": [
"... index'].value);\nparts[-1].matches("[0-9]+") ?Integ ...",
" ^---- HERE"
],
"script": "String parts = /_/.split(doc['index'].value);\nparts[-1].matches("[0-9]+") ?Integer.parseInt("4"): parts[-1]\n\n",
"lang": "painless"
}
],
"type": "search_phase_execution_exception",
"reason": "all shards failed",
"phase": "query",
"grouped": true,
"failed_shards": [
{
"shard": 0,
"index": "kibana_sample_data_flights",
"node": "obX0kP72Txenm9NhCQgKzA",
"reason": {
"type": "script_exception",
"reason": "compile error",
"script_stack": [
"... index'].value);\nparts[-1].matches("[0-9]+") ?Integ ...",
" ^---- HERE"
],
"script": "String[] parts = /
/.split(doc['_index'].value);\nparts[-1].matches("[0-9]+") ?Integer.parseInt("4"): parts[-1]\n\n",
"lang": "painless",
"caused_by": {
"type": "illegal_argument_exception",
"reason": "method [java.lang.String, matches/1] not found"
}
}
}
]
}

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