PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 25, 2022

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

 October 25, 2022     elasticsearch, elasticsearch-painless, java     No comments   

Issue

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.


Solution

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)



Answered By - Bohemian
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing