重命名spark dataframe structtype字段

r3i60tvu  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(397)

给定一个动态结构类型。这里structtype名称未知。它是动态的,因此它的名字正在改变。
名称是可变的。所以不要在模式中预先假定“main\ col”。

root
 |-- MAIN_COL: struct (nullable = true)
 |    |-- a: string (nullable = true)
 |    |-- b: string (nullable = true)
 |    |-- c: string (nullable = true)
 |    |-- d: string (nullable = true)
 |    |-- f: long (nullable = true)
 |    |-- g: long (nullable = true)
 |    |-- h: long (nullable = true)
 |    |-- j: long (nullable = true)

我们如何编写一个动态代码来重命名structtype的字段,并将其名称作为前缀。

root
 |-- MAIN_COL: struct (nullable = true)
 |    |-- MAIN_COL_a: string (nullable = true)
 |    |-- MAIN_COL_b: string (nullable = true)
 |    |-- MAIN_COL_c: string (nullable = true)
 |    |-- MAIN_COL_d: string (nullable = true)
 |    |-- MAIN_COL_f: long (nullable = true)
 |    |-- MAIN_COL_g: long (nullable = true)
 |    |-- MAIN_COL_h: long (nullable = true)
 |    |-- MAIN_COL_j: long (nullable = true)
j7dteeu8

j7dteeu81#

您可以使用dsl来更新嵌套列的模式。

import org.apache.spark.sql.types._

val schema: StructType = df.schema.fields.head.dataType.asInstanceOf[StructType]

val updatedSchema = StructType.apply(
       schema.fields.map(sf => StructField.apply("MAIN_COL_" + sf.name, sf.dataType))
)

val resultDF = df.withColumn("MAIN_COL", $"MAIN_COL".cast(updatedSchema))

更新的架构:

root
 |-- MAIN_COL: struct (nullable = false)
 |    |-- MAIN_COL_a: string (nullable = true)
 |    |-- MAIN_COL_b: string (nullable = true)
 |    |-- MAIN_COL_c: string (nullable = true)

相关问题