Convert string to int if it contains only int


(Nikhil Kumar) #1

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


(Mark Walkom) #2

Posting your errors would help,

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


(Nikhil Kumar) #3

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


(Mark Walkom) #4

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


(Nikhil Kumar) #5

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"
}
}
}
]
}


(system) #6

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