Convert String to Integer using Painless

Hi Team,

I am trying to convert one of our field which is in String to Int using painless. Please find my code below.

Code:

String s = doc['TotalDiskSpace'].value;
int tdvalue = Integer.parseInt(s);
return tdvalue;

Used the below in the scripted fields -
Name - TotalDisk
Type - Number
Format - Number (default)

Also, should i use TotalDiskSpace or TotalDiskSpace.keyword ?
I'm still unable to get the value. Am i missing anything. Please help.

Thanks.

Its recommended to use always the.keyword because every value which is not a .keyword must be loaded into RAM which slow down your ELK-Stack´s performance if you do not have much RAM. If you use the field without .keyword you must activate the fielddata for this field. (You can make this with a PUT-Message)

https://www.elastic.co/guide/en/elasticsearch/reference/current/fielddata.html

Which value do you get from the return value? Is there any error? (Please post it, if there is one)

PS.: I would also recommend you to use a null-check.

Best regards,
Robert

1 Like

Error message after i create the scripted field -

Error: Request to Elasticsearch failed: {"error":{"root_cause":[{"type":"script_exception","reason":"runtime error","script_stack":["java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)","java.lang.Integer.parseInt(Integer.java:583)","java.lang.Integer.parseInt(Integer.java:615)","tdvalue = Integer.parseInt(s);\n"," ^---- HERE"],"script":"String s = doc['TotalDiskSpace.keyword'].value;\nint tdvalue = Integer.parseInt(s);\nreturn tdvalue;","lang":"painless"}],"type":"search_phase_execution_exception","reason":"all shards failed","phase":"query","grouped":true,"failed_shards":[{"shard":0,"index":"check-2018.04.16","node":"sdfgsdfgsfd","reason":{"type":"script_exception","reason":"runtime error","script_stack":["java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)","java.lang.Integer.parseInt(Integer.java:583)","java.lang.Integer.parseInt(Integer.java:615)","tdvalue = Integer.parseInt(s);\n"," ^---- HERE"],"script":"String s = doc['TotalDiskSpace.keyword'].value;\nint tdvalue = Integer.parseInt(s);\nreturn tdvalue;","lang":"painless","caused_by":{"type":"number_format_exception","reason":"For input string: "31568334500""}}}]},"status":500}

Scripted field -
Untitled

If you have Kibana 6.x please type in your script in the developer-console and let you give the result for the normal field (non-scripted). I think your field is containing non-numeric data so painless will fail to convert it.

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