scala - 在 Spark 的 Dataframe 中展平数组
问题描述
如何将数组展平为包含列 [a,b,c,d,e] 的数据框
root
|-- arry: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- a string (nullable = true)
| | |-- b: long (nullable = true)
| | |-- c: string (nullable = true)
| | |-- d: string (nullable = true)
| | |-- e: long (nullable = true)
任何帮助表示赞赏。
解决方案
假设您有一个具有以下结构的 json:
{
"array": [
{
"a": "asdf",
"b": 1234,
"c": "a",
"d": "str",
"e": 1234
},
{
"a": "asdf",
"b": 1234,
"c": "a",
"d": "str",
"e": 1234
},
{
"a": "asdf",
"b": 1234,
"c": "a",
"d": "str",
"e": 1234
}
]
}
- 读取文件
scala> val nested = spark.read.option("multiline",true).json("nested.json")
nested: org.apache.spark.sql.DataFrame = [array: array<struct<a:string,b:bigint,c:string,d:string,e:bigint>>]
- 检查架构
scala> nested.printSchema
root
|-- array: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- a: string (nullable = true)
| | |-- b: long (nullable = true)
| | |-- c: string (nullable = true)
| | |-- d: string (nullable = true)
| | |-- e: long (nullable = true)
- 使用
explode
功能
scala> nested.select(explode($"array").as("exploded")).select("exploded.*").show
+----+----+---+---+----+
| a| b| c| d| e|
+----+----+---+---+----+
|asdf|1234| a|str|1234|
|asdf|1234| a|str|1234|
|asdf|1234| a|str|1234|
+----+----+---+---+----+
推荐阅读
- azure - Azure Functions Core Tools vs CLI aka 如何在 functionapp 中拥有函数列表
- oracle - 无法删除 Oracle 中的还原点
- apache-kafka - 离开组请求后 Spring Kafka 消费者无法重新加入
- c# - 将此代码上传到 unity 时出现错误
- html - 当我向右浮动时,菜单顺序会发生变化
- javascript - 阻止加载选择的 JS 文件
- r - 将 RMarkdown html 文档中的所有值更改为 NA 或 0
- javascript - 使用 livewire/alpine 关注错误包中的第一个表单元素?
- javascript - 如何将 JSON 数据导入 MySQL 并在网页上可视化?
- php - 使用php提取文档中的特定信息