不支持类型org.apache.spark.sql.types.DataType的架构

mzsu5hc0  于 2022-12-27  发布在  Apache
关注(0)|答案(1)|浏览(158)

我试着用schema创建空df:

val sparkConf = new SparkConf()
    .setAppName("app")
    .setMaster("local")

  val sparkSession = SparkSession
    .builder()
    .config(sparkConf)
    .getOrCreate()

  val sparkContext = sparkSession.sparkContext

  var tmpScheme = StructType(
    StructField("source_id", StringType, true) :: Nil)

var df = conf.SparkConf.sparkSession.createDataFrame(tmpScheme)

得到了Schema for type org.apache.spark.sql.types.DataType is not supported ...
我不明白为什么-甚至在Imports中也没有.DataType

import org.apache.spark.sql.types.{BooleanType, IntegerType, StringType, StructField, StructType}

这里有什么问题吗?
PS:Spark版

"org.apache.spark" %% "spark-sql" % "3.2.2", // spark
  "org.apache.spark" %% "spark-core" % "3.2.2", // spark
nbysray5

nbysray51#

如果查看文档,可以看到StructType的参数fields的类型为Array[StructField],并且传递的是StructField
这意味着您应该使用Array Package StructField,例如:

val simpleSchema = StructType(Array(
  StructField("source_id", StringType, true))
)

祝你好运!

    • 编辑**

createDataframe中有一个参数的情况:

val data = Seq(
  Data(1, "test"),
  Data(2, "test2")
)
val dataDf = spark.createDataFrame(data)
dataDf.show(10, false)

createDataframe中有两个参数e的情况:

val someSchema = List(
  StructField("number", IntegerType, true),
  StructField("word", StringType, true)
)
val someData = Seq(Row(1, "test"), Row(2, "test2"))
val someDF = spark.createDataFrame(
  spark.sparkContext.parallelize(someData),
  StructType(someSchema)
)

两种情况的输出是相同的:

+------+-----+
|number|word |
+------+-----+
|1     |test |
|2     |test2|
+------+-----+

在您的例子中,模式试图从类的属性(StructType)中推断出来,并试图用StructField: source_id填充。StructType扩展了DataType,这就是错误的来源(Spark不能解析类型)

相关问题