Home > OS >  how to resolve `member method [java.lang.Object, add/1] not found` in painless
how to resolve `member method [java.lang.Object, add/1] not found` in painless

Time:08-29

I want to calculate (1 / num 1) by using painless.
When num is 0, the whole result should be null.
I wrote like this;

POST /_scripts/painless/_execute
{
  "script": {
    "source":  """
      (
        params.num == 0 ? null : BigDecimal.valueOf(1).divide(BigDecimal.valueOf(params.num))
      ).add(BigDecimal.valueOf(1))
    """,
    "params": {"num": 1}
  }
}

But I got a compile error:

"caused_by" : {
  "type" : "illegal_argument_exception",
  "reason" : "member method [java.lang.Object, add/1] not found"
}

How to resolve this? I want to write this code by one-liner if possible (so I don't want to use if statement). Thank you in advance.

CodePudding user response:

Move the call to add() inside the brackets.

(
    params.num == 0 ? null : BigDecimal.ONE.divide(BigDecimal.valueOf(params.num).add(BigDecimal.ONE))
)

You were calling add() on the result of the expression, which has type Object.

Note also the use of BigDecimal.ONE in preference to BigDecimal.valuesOf(1)

  • Related