如何在java代码中使用elasticsearch无痛BigDecimal



我使用无痛更新文档。如何使用BigDecimal来完成它?使用Elasticsearch 6.8.1。编写JavaDoc脚本脚本构造器是:

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

我的代码是:

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);

我的问题是:如何让ctx_使用BigDecimal方法的source.mamount*params.oundageRate相乘并设置缩放

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

非常感谢,我会很感激

BigDecimal在ES 6.8中肯定得到了Painless的支持。

应该将poundageRate参数作为字符串,而不是将其转换为双值。

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

然后,您的脚本可以包含您显示的代码(稍作修改(,即

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

试试看,效果很好。

最新更新