VarcharType不匹配Spark数据帧

问题描述 投票:0回答:1

我正在尝试更改数据框的架构。每当我有一个字符串类型的列时,我都想将其类型更改为VarcharType(max),其中max是该列中字符串的最大可用长度。我写了下面的代码。 (我想稍后将数据帧导出到sql server,并且我不想在sql server中使用nvarchar,所以我想在火花端限制它))>

val df = spark.sql(s"SELECT * FROM $tableName")

var l : List [StructField] = List()

val schema = df.schema
schema.fields.foreach(x => {

  if (x.dataType == StringType) {
    val dataColName = x.name
    val maxLength = df.select(dataColName).reduce((x, y) => {
      if (x.getString(0).length >= y.getString(0).length) {
        x
      } else {
        y
      }
    }).getString(0).length

    val dataType = VarcharType(maxLength)
    l = l :+ StructField(dataColName, dataType)
  } else {
    l = l :+ x
  }
})

val newSchema = StructType(l)
val newDf = spark.createDataFrame(df.rdd, newSchema)

但是运行它时出现此错误。

  20/01/22 15:29:44 ERROR ApplicationMaster: User class threw exception: scala.MatchError: 
  VarcharType(9) (of class org.apache.spark.sql.types.VarcharType)
  scala.MatchError: VarcharType(9) (of class org.apache.spark.sql.types.VarcharType)

数据框列的类型可以为VarcharType(n)吗?

我正在尝试更改数据框的架构。每当我有一个字符串类型的列时,我都想将其类型更改为VarcharType(max),其中max是该列中字符串的最大可用长度。 i ...

dataframe apache-spark varchar
1个回答
1
投票

从数据库到/从数据帧的数据映射在方言类中发生。对于MS SQL Server,类为org.apache.spark.sql.jdbc.MsSqlServerDialect。您可以从中继承并覆盖getJDBCType以影响从数据帧到表的数据类型映射。然后注册您的方言以使其生效。

© www.soinside.com 2019 - 2024. All rights reserved.