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

Benthos写入SQL Server遇数组类型错误,寻求解决方案

问题分析

错误converting argument $1 type: unsupported type []interface {}, a slice of interface的根源:

  • 当前args_mapping返回的是二维数组(例如[[101], [101]]),但SQL输出默认期望单条消息对应的一维参数数组,类型不匹配导致转换失败。
  • 第二个Bloblang处理器的判断逻辑错误:this.length()判断的是整个消息对象的字段数量(永远为1,因为存在data字段),无法正确识别data数组为空的场景。
解决方案

采用拆分消息为单条插入的方式,逻辑清晰且符合预期:

步骤1:修正Bloblang逻辑错误

修改第二个Bloblang处理器,将判断条件从this.length()改为this.data.length(),确保空数组时生成默认记录。

步骤2:拆分数组为单条消息

添加split处理器,将data数组拆分为独立的单条消息,每条消息对应一次数据库插入操作。

步骤3:调整SQL参数映射

将args_mapping改为直接取当前消息的individualIdentifier,生成单条插入所需的一维参数数组。

完整修正后的配置
input:
  generate:
    count: 1
    interval: 0s
    mapping: |
      root = {
        "individualIdentifier": "101",
        "memberships": [
          {
            "effectiveDate": "2023-01-01",
            "terminationDate": "2023-12-31",
            "areaGroup": "Area1",
            "product": {
              "healthCoverageType": {
                "code": "M"
              }
            }
          },
          {
            "effectiveDate": "2023-02-01",
            "terminationDate": "2023-11-30",
            "areaGroup": "Area2",
            "product": {
              "healthCoverageType": {
                "code": "MC"
              }
            }
          },
          {
            "effectiveDate": "2023-03-01",
            "terminationDate": "2023-10-31",
            "areaGroup": "Area3",
            "product": {
              "healthCoverageType": {
                "code": "M"
              }
            }
          }
        ]
      }
pipeline:
  processors:
    - bloblang: |
        root.data = this.memberships.filter(m -> m.product.healthCoverageType.code == "M").map_each(m -> {
          "individualIdentifier": this.individualIdentifier,
          "membership": m
        })
    - bloblang: |
        root = if this.data.length() == 0 {
          [
            {
              "individualIdentifier": this.individualIdentifier,
              "membership": null
            }
          ]
        } else {
          this.data
        }
    - split: {} # 将数组拆分为独立的单条消息
output:
  broker:
    pattern: fan_out
    outputs:
      - type: sql
        sql:
          driver: mssql
          data_source_name: "" # 填入数据库连接信息
          query: |
            INSERT INTO <table_name>
            (
              source_primary_key
            )
            VALUES (?);
          args_mapping: |
            root = [ this.individualIdentifier ]
验证效果

修正后,Benthos会将过滤后的2条membership记录拆分为2条独立消息,每条消息执行一次INSERT操作,最终数据库表中会插入2条source_primary_key为101的记录,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 13:35:07