我用这个模式读了一个嵌套的json:
root
|-- company: struct (nullable = true)
| |-- 0: string (nullable = true)
| |-- 1: string (nullable = true)
| |-- 10: string (nullable = true)
| |-- 100: string (nullable = true)
| |-- 101: string (nullable = true)
| |-- 102: string (nullable = true)
| |-- 103: string (nullable = true)
| |-- 104: string (nullable = true)
| |-- 105: string (nullable = true)
| |-- 106: string (nullable = true)
| |-- 107: string (nullable = true)
| |-- 108: string (nullable = true)
| |-- 109: string (nullable = true)
当我尝试:
df.select(col("company.*"))
我得到结构的每个领域"公司"作为列。但我希望它们成为行。我想在另一列中获取id和字符串的行:
0 1 10 100 101 102
"hey" "yooyo" "yuyu" "hey" "yooyo" "yuyu"
而是得到类似的东西:
id name
0 "hey"
1 "yoooyo"
10 "yuuy"
100 "hey"
101 "yooyo"
102 "yuyu"
先谢谢你的帮助,
棘手
答案 0 :(得分:5)
尝试使用union:
val dfExpl = df.select("company.*")
dfExpl.columns
.map(name => dfExpl.select(lit(name),col(name)))
.reduce(_ union _)
.show
或者使用array / explode:
val dfExpl = df.select("company.*")
val selectExpr = dfExpl
.columns
.map(name =>
struct(
lit(name).as("id"),
col(name).as("value")
).as("col")
)
dfExpl
.select(
explode(array(selectExpr: _*))
)
.select("col.*")
.show()