scala - 如何将 StructType 从 Spark 中的 json 数据帧分解为行而不是列

标签 scala apache-spark apache-spark-sql

我用这个模式阅读了一个嵌套的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"

在此先感谢您的帮助,

棘手

最佳答案

使用联合试试这个:

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()

关于scala - 如何将 StructType 从 Spark 中的 json 数据帧分解为行而不是列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47418971/

相关文章:

scala - 如何在不升级到 Akka HTTP 的情况下停止使用路由 DSL 的喷雾服务器?

python - 迭代 pyspark Dataframe,然后为每一行与 mongoDB 交互

java - 创建 SQLContext 对象时,构造函数 HiveContext(JavaSparkContext) 出现未定义错误

scala - 在 scala 中将 Spark Dataframe 转换为 RDD

java - 如何获取变量中的数据帧值

scala - 了解 `f: Int => _`

scala - 强制执行 JSON 结果的顺序

scala - 理解偏函数中的 'case'关键字

python - 通过键与 RDD 相交

python-3.x - ModuleNotFoundError : No module named 'py4j'