我正在尝试将JSON文档从我无法控制的源转换为Parquet。模式是自我描述和进化的。
需要从嵌套节点中的字段名中移除空格,以便将火花数据格式转换/写入到Parquet。
如何在嵌套模式中从字段名中删除空格?
下面的内容似乎适用于平面模式,但似乎不适用于嵌套树。
exprs = [col(column).alias(column.replace(' ', '_')) for column in jsonDF.columns]
newDF = jsonDF.select(*exprs)
newDF.write \
.format("parquet") \
.mode("overwrite") \
.save("/path/to/parquet_test1")这是一个代表组成的模式。注意节点树不同深度的字段名中的空格。
root
|-- Browser Info: struct (nullable = true)
| |-- Operating System: struct (nullable = true)
| | |-- Android: double (nullable = true)
| | |-- BlackBerryOS: double (nullable = true)
| | |-- ChromeOS: double (nullable = true)
| | |-- Linux: double (nullable = true)
| | |-- Mac OS X: double (nullable = true)
| | |-- Windows: double (nullable = true)
| | |-- iOS: double (nullable = true)
| |-- Browser Types: struct (nullable = true)
| | |-- Chrome: double (nullable = true)
| | |-- Firefox: double (nullable = true)
| | |-- IE 10: double (nullable = true)
| | |-- IE 8: double (nullable = true)
| | |-- IE 9: double (nullable = true)
| | |-- Opera: double (nullable = true)
| | |-- Safari 5: double (nullable = true)
| | |-- Safari 6: double (nullable = true)
| | |-- Safari 7: double (nullable = true)发布于 2017-04-05 14:27:54
我可以在Scala中提供代码,我希望这会有所帮助。这是一种有点肮脏的方式来实现您所要求的,但它会达到目的。
import sqlContext.implicits._
import scala.collection.mutable.ListBuffer
val jsonDF = sqlContext.read.json("path")
val oldSchema = jsonDF.columns.toIterator
val newSchema = oldSchema.map(x => x.replaceAll(" ", "")).toIterator
val schema = new ListBuffer[String]()
while (oldSchema.hasNext) {
val oldSchemValue = oldSchema.next()
val newSchemaValue = newSchema.next()
schema += s"${oldSchemValue} as ${newSchemaValue}"
}
val newJsonDF = jsonDF.selectExpr(schema.toList.head, schema.toList.tail: _*)https://stackoverflow.com/questions/43219440
复制相似问题