scala - 在 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 类中提取字段,作为解决方法。
解决方案
您应该能够将内置编码器用于案例类:
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)
推荐阅读
- android - 撤销权限时阻止应用重启
- airflow - 如何为只读用户禁用 DAG 开关?
- amazon-web-services - 如何制作要在 EKS 中使用的自定义基础 AMI
- java - 如何解析和优化字符串中的数学表达式?
- python - 如何将数字元组转换为显示该数字是否存在的二进制数字列表
- protractor - 我们可以使用量角器在角度应用程序中自动化电子图表数据吗
- rust - 如何使用 serde_json 从对象数组中反序列化单个字段?
- postgresql - 如何从postgres中具有最大计数的列中获取值?
- keyboard-shortcuts - Sublime text 2,如何为菜单项“查看-自动换行列-等”设置热键?
- node.js - npm install 在这么多警告后给出错误