You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch 7.10 Ingest Pipeline处理WEI数值转换及动态计算

解决Elasticsearch中WEI数值的Ingest Pipeline转换问题

一、固定小数位数(ETH,18位)的转换

完全可以通过Ingest Pipeline实现,核心是用script处理器执行数值计算。以下是具体的Pipeline定义:

PUT _ingest/pipeline/wei-to-eth
{
  "description": "将WEI单位的ETH金额转换为整数形式的ETH",
  "processors": [
    {
      "script": {
        "lang": "painless",
        "source": """
          if (ctx.wei_amount != null) {
            // 直接使用10^18的整数常量,避免Math.pow的精度问题
            long divisor = 1000000000000000000L;
            ctx.eth_amount = ctx.wei_amount / divisor;
          }
        """
      }
    }
  ]
}

使用时,索引文档时指定该Pipeline即可:

PUT your-index/_doc/1?pipeline=wei-to-eth
{
  "wei_amount": 1000000000000000000000
}

文档索引完成后,eth_amount字段值会是1000,符合预期计算结果。

二、基于文档内动态小数位数的转换

同样可以实现,只需在script处理器中引用当前文档的decimals字段动态计算除数。示例Pipeline如下:

PUT _ingest/pipeline/wei-to-token
{
  "description": "根据文档内的decimals字段,将WEI单位的代币金额转换为整数形式",
  "processors": [
    {
      "script": {
        "lang": "painless",
        "source": """
          if (ctx.token_wei_amount != null && ctx.decimals != null && ctx.decimals instanceof Integer) {
            long divisor = (long) Math.pow(10, ctx.decimals);
            ctx.token_amount = ctx.token_wei_amount / divisor;
          }
        """
      }
    }
  ]
}

使用示例:

PUT your-token-index/_doc/1?pipeline=wei-to-token
{
  "token_wei_amount": 123456000,
  "decimals": 3
}

索引完成后,token_amount字段值为123456,对应123456000 / 10^3的计算结果。

注意事项

  1. 确保原WEI字段的类型为long或integer,防止精度丢失;
  2. 若文档可能缺失decimals字段,可在脚本中添加默认值处理逻辑;
  3. Elasticsearch 7.10完全支持上述Painless脚本语法,无需额外配置。

内容的提问来源于stack exchange,提问作者estransconder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:09:24