Home > Software engineering >  How to use elasticsearch painless BigDecimal in java code?
How to use elasticsearch painless BigDecimal in java code?

Time:12-25

I use painless to update doc. how to use BigDecimal to finish it ? Using Elasticsearch 6.8.1. Script JavaDoc Script construtor is:

public Script (ScriptType type,
              java.lang.String lang,
              java.lang.String idOrCode,
              java.util.Map<java.lang.String, java.lang.Object> params)

My Code is:

StringBuilder script = new StringBuilder();
Map<String, Object> params = new HashMap<>();
params.put("poundageRate", poundageRate.doubleValue());
script.append("ctx._source.poundage=ctx._source.amount*params.poundageRate;");
Script scriptObj = new Script(INLINE, DEFAULT_SCRIPT_LANG, script.toString(), params);

My Question is: How to let ctx._source.amount*params.poundageRate using BigDecimal method multiply and setScale

new BigDecimal("ctx._source.amount").multiply(new BigDecimal("params.poundageRate")).setScale(2, HALF_UP).stripTrailingZeros()

Thanks a lot i will appreciate it

CodePudding user response:

BigDecimal is definitely supported by Painless in ES 6.8.

You should let the poundageRate parameter as a string instead of transforming it to a double value.

params.put("poundageRate", poundageRate.toString());

Then, your script can contain the code you're showing (with slight modifications), i.e.

ctx._source.amount = new BigDecimal(ctx._source.amount).multiply(new BigDecimal(params.poundageRate)).setScale(2, RoundingMode.HALF_UP).stripTrailingZeros()

Try it out, it works well.

  • Related