Scripted field convert string to number

Hi,

I need to convert a string to a number.

I wrote this script but it does not work and causes no data to display anymore when looking at discovery.

if (doc['stringnumber']) {
    Integer.parseInt(doc['stringnumber'].value)
}

The field type in the scripted field is set as a number.

The source data looks like this: 077.8.

Is it possible to convert a string to a number with a scripted field?

You're going to need to return inside the if statement.

1 Like

Thanks but that doesn't change anything.

The problem seems to be that the initial if statement just doesn't do anything but no information is provided as to why.

I tried a simple test on two indices just to see if the if statement works.

if (doc['myfield'].value == "some value") { 
    return "YES"
} else {
    return "NO"
}

Does not return anything in the test screen.

I got another index where I had Elastic do the mapping and for some reason it does work there by using 'myfield.keyword'. Adding .keyword to the field for the other two indices does not work.

In the two indices that don't return any results, myfield is mapped as keyword only.

"myfield" : {
  "type" : "keyword",
  "ignore_above" : 256
}

One problem is that "077.8" is not an integer.

Try this:

if (doc['stringnumber']) {
  return Double.parseDouble(doc['stringnumber'].value)
}

Note that you can troubleshoot scripted fields nicely by using constants instead of document fields until you've got the syntax correct, then drop in your fields. To do this, you would simply build a scripted field with this code:

return Double.parseDouble("077.8");
1 Like

Thanks for the tip. I figured out the problem is with the if statement. Apparently they don't work on strings.

This script sort of works though it produces a lot of unnecessary data.

However this could work in my benefit. Is it possible to use painless to check for a last known value instead of only returning a static value?

This probably won't work as I would need to last known value before there is another known value and not simply the last known value.

If I had something like this
100
0
0
0
200
0
0
0
300

I would want it to look like this
100
100
100
100
200
200
200
200
300

if (doc['stringnumber'].empty) { 
    return "0" 
} else { 
    return Double.parseDouble(doc['stringnumber'].value); 
}

Limitations

There are a few limitations relative to other script languages:

  • Only numeric, boolean, date, and geo_point fields may be accessed
  • Stored fields are not available

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