Spark获取嵌套json的列名

Phi*_*los 1 java json nested apache-spark-sql spark-dataframe

我试图通过DataFrames从嵌套的JSON中获取列名.架构如下:

root
 |-- body: struct (nullable = true)
 |    |-- Sw1: string (nullable = true)
 |    |-- Sw2: string (nullable = true)
 |    |-- Sw3: string (nullable = true)
 |    |-- Sw420: string (nullable = true)
 |-- headers: struct (nullable = true)
 |    |-- endDate: string (nullable = true)
 |    |-- file: string (nullable = true)
 |    |-- startDate: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)

我可以使用df.columns()获取列名"body"和"header"但是当我尝试使用df.select("body")从正文中获取列名(例如:Sw1,Sw2,...) ).columns它总是给我身体专栏.

有什么建议吗?:)

Mic*_*ust 5

如果问题是如何查找嵌套列名称,则可以通过检查schemaDataFrame 来执行此操作.模式表示为StructType可以DataType包含其他对象的字段(包括其他嵌套结构).如果你想发现所有的字段,你必须递归地走这棵树.例如:

import org.apache.spark.sql.types._
def findFields(path: String, dt: DataType): Unit = dt match {
  case s: StructType => 
    s.fields.foreach(f => findFields(path + "." + f.name, f.dataType))
  case other => 
    println(s"$path: $other")
}
Run Code Online (Sandbox Code Playgroud)

它遍历树并打印出所有叶子字段及其类型:

val df = sqlContext.read.json(sc.parallelize("""{"a": {"b": 1}}""" :: Nil))
findFields("", df.schema)

prints: .a.b: LongType
Run Code Online (Sandbox Code Playgroud)