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

Spark 3.0.1 Scala环境下substring传length返回值报类型不匹配错误

问题根因

报错和length函数导入无关,是Spark语法使用错误导致的:
你代码中length(col("Input")).cast("int")+0写法里的+0是Scala原生的数值加法,编译器会要求加号两侧都是Scala原生Int类型,但length(col("Input")).cast("int")返回的是Spark的Column类型,类型不匹配所以触发报错。
你单独使用length可以正常运行的原因是此时Column类型直接作为输出列参与Spark SQL计算,不需要转换为Scala原生Int类型,不会触发类型校验。

修复方案

方案1:修正Column运算逻辑

如果确实需要动态计算截取长度,用Spark提供的lit()函数将常量包装为Column类型参与运算即可,起始位置也可以统一用lit()包装避免隐式转换问题:

import spark.implicits._
import org.apache.spark.sql.functions._

Seq(("1987.01.01"))
      .toDF("Input")
      .select( 
        col("Input"), 
        to_date(col("Input"), "yyyy.M.d").as("format"),
        length(col("Input")),
        substring(col("Input"), lit(1), length(col("Input")) + lit(0)).as("sub_str")
      ).show()

注:length返回的列本身就是整数类型,不需要额外执行cast("int")。

方案2:省略长度参数(更推荐)

Spark SQL的substring原生支持仅传入字符串和起始位置,默认直接截取到字符串末尾,不需要手动计算长度:

import spark.implicits._
import org.apache.spark.sql.functions._

Seq(("1987.01.01"))
      .toDF("Input")
      .select( 
        col("Input"), 
        to_date(col("Input"), "yyyy.M.d").as("format"),
        length(col("Input")),
        substring(col("Input"), 1).as("sub_str")
      ).show()

以上两种方案运行后均可得到正确结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 15:06:05