Painless (Elasticsearch) convert any type of value to integer
Asked Answered
M

2

7

I am converting an Elasticsearch script from Groovy to Painless. The script accepts a parameter, which can be either an integer or a string convertible to an integer (i.e. could be either 123 or "123").

In Groovy, doing my_val.toLong() converted both just fine, but that method is not available in Painless.

Is there any alternative syntax that would do the same in Painless?

I tried explicit casting with (long) my_var, but I get java.lang.String cannot be cast to java.lang.Number

In short, I want to do the following in Painless and to get true as a result:

GET _search
{
  "script_fields": {
    "test": {
      "script": {
        "lang": "groovy",
        "params": {
          "my_val1": "123",
          "my_val2": 123
        },
        "source": """
        my_val1.toLong() == my_val2.toLong()
        """
      }
    }
  }
}
Midtown answered 10/4, 2018 at 15:8 Comment(0)
M
5

Since I can see this question is still getting some interest, in the end the best way I could find to do this is:

Long.parseLong(params.my_val1.toString()) == Long.parseLong(params.my_val2.toString())
Midtown answered 26/6, 2020 at 10:26 Comment(0)
E
0

My problem was use integer field Math.abs(doc['age'] - 30) directly.

After change it to Math.abs(doc['age'].value - 30), everything works.

Emblaze answered 15/5, 2023 at 3:10 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.