【问题标题】:How to use elasticsearch painless BigDecimal in java code?如何在java代码中使用elasticsearch painless BigDecimal?
【发布时间】:2022-01-24 07:07:42
【问题描述】:

我使用无痛更新文档。如何使用 BigDecimal 来完成它?使用 Elasticsearch 6.8.1。 Script 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._source.amount*params.poundageRate 使用 BigDecimal 方法 乘法和setScale

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

非常感谢,我会很感激的

【问题讨论】:

    标签: elasticsearch elasticsearch-painless


    【解决方案1】:

    BigDecimal 绝对是 ES 6.8 中 Painless 的 supported

    您应该让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()
    

    试试看,效果不错。

    【讨论】:

    • 非常感谢。但是 es 发生错误。 printstack 是:由:org.elasticsearch.common.io.stream.NotSerializableExceptionWrapper 引起:class_cast_exception:无法在 org.elasticsearch.painless.PainlessScript$Script.execute(ctx._source. payFrom=params.payFrom;ctx._source.finishTime=params.finishTime;ctx._source.userId=params.userId;ctx._source.status=params.status;ctx._source.poundage=new BigDecimal(ctx._source.amount ).multiply(new BigDecimal(params.poundageRate)).setScale(2, ...:190) BigDecimal(ctx._source.amount).multiply(new
    • 我认为这是因为您将 amount 存储为本机双精度而不是字符串化双精度(这使您可以保持精度)...如果是这种情况,那么您只需要做 @ 987654326@
    • 成功了!非常感谢您解决了我的问题。圣诞快乐~
    • 太棒了,很高兴它有帮助!也祝你圣诞快乐;-)
    猜你喜欢
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    相关资源
    最近更新 更多