首页 > 解决方案 > 子字符串类型不匹配中的 Spark Length 函数

问题描述

在 Spark 3.0.1、Scala 2.12 中,我得到了以下信息:

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, length(col("Input")).cast("int")+0 )
      ).show()



    command-1067744798817014:7: error: type mismatch;
     found   : org.apache.spark.sql.Column
     required: Int
        substring(col("Input"),1, length(col("Input")).cast("int")+0 )
                                                              ^

所以我想我有错误的“长度”函数,通过隐式导入或其他什么?

这有效

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


+----------+----------+-------------+
|     Input|    format|length(Input)|
+----------+----------+-------------+
|1987.01.01|1987-01-01|           10|
+----------+----------+-------------+

标签: apache-sparkapache-spark-sql

解决方案


substringScala API 中的方法只接受整数作为第二个和第三个参数。如果要传递列,则需要expr使用 Spark SQL APIsubstring方法:

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

+----------+----------+-------------+----------------------------------------+
|     Input|    format|length(Input)|substring(Input, 1, (length(Input) + 0))|
+----------+----------+-------------+----------------------------------------+
|1987.01.01|1987-01-01|           10|                              1987.01.01|
+----------+----------+-------------+----------------------------------------+

推荐阅读