2017-04-04 88 views
0

我想將JSON文檔轉換爲來自我無法控制的源的Parquet。該模式是自我描述和演變的。如何從Spark中的嵌套JSON節點中刪除空格

需要從嵌套節點中的字段名稱中刪除空格,以便從spark數據框轉換/寫入Parquet。

Spark(在python上)如何從嵌套模式中的字段名稱中刪除空格?

以下似乎工作在一個平面模式,但似乎不適用於嵌套樹。

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) 

回答

1

我可以在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: _*)