Spark scala重命名地图列

gay*_*hri -1 scala apache-spark

我想将重命名key下图作为name,_1rownum,_2status

  root
  |-- id: string (nullable = true)
  |-- info: map (nullable = true)
  |    |-- key: string
  |    |-- value: struct (valueContainsNull = true)
  |    |    |-- _1: long (nullable = false)
  |    |    |-- _2: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)

请帮忙

use*_*411 6

最便宜和最简单的解决方案是cast使用新架构:

val df = Seq(("1", Map("foo" -> (1L, "bar")))).toDF("id", "info")

df.withColumn(
  "info",
  $"info".cast("map<string,struct<rownum:long,status:string>>")
).printSchema
Run Code Online (Sandbox Code Playgroud)
root
 |-- id: string (nullable = true)
 |-- info: map (nullable = true)
 |    |-- key: string
 |    |-- value: struct (valueContainsNull = true)
 |    |    |-- rownum: long (nullable = true)
 |    |    |-- status: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)

如果您愿意,可以使用DataType对象代替字符串描述,但这更加冗长.

key(和value)因为没有模式的一部分而无法重命名.

udf可以提供另一个选项,但它在性能方面低于标准,并且需要一个Product类型来表示值: