首页 > 解决方案 > 在 Scala 中将嵌套数据作为嵌套案例类读取

问题描述

我有带有架构的数据:

DummyData
 |-- a: string (nullable = true)
 |-- b: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- b1: string (nullable = true)
 |    |    |-- b2: string (nullable = true)
 |-- c: long (nullable = true)

案例类定义为:

case class DummyData (a : String, b : List[DummyDataChild], c : Long)
case class DummyDataChild (b1 : String, b2 : String)

当我尝试在 Dataframe 中读取此数据时,子案例类被读取为 GenericRowWithSchema 而不是预期的实际案例类(在这种情况下为 DummyDataChild),无论如何也可以将嵌套的子对象作为案例类读取在斯卡拉火花?

PS:我知道我们可以从 GenericRowWithSchema 类中提取字段,作为解决方法。

标签: scalaapache-sparkapache-spark-sql

解决方案


您应该能够将内置编码器用于案例类:

val ds = df.as[DummyData]
df.printSchema
ds.printSchema

输出:

ds: org.apache.spark.sql.Dataset[DummyData] = [a: string, b: array<struct<b1:string,b2:string>> ... 1 more field]

root
 |-- a: string (nullable = true)
 |-- b: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- b1: string (nullable = true)
 |    |    |-- b2: string (nullable = true)
 |-- c: long (nullable = false)

root
 |-- a: string (nullable = true)
 |-- b: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- b1: string (nullable = true)
 |    |    |-- b2: string (nullable = true)
 |-- c: long (nullable = false)

推荐阅读