【问题标题】:Spark Length function in substring type mismatch子字符串类型不匹配中的 Spark Length 函数
【发布时间】:2021-05-24 05:02:14
【问题描述】:

在 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-spark apache-spark-sql


    【解决方案1】:

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

    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|
    +----------+----------+-------------+----------------------------------------+
    

    【讨论】:

      猜你喜欢
      • 2015-06-04
      • 2021-10-30
      • 2021-03-07
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 2022-10-13
      • 2022-01-21
      相关资源
      最近更新 更多