使用spark dataframe重命名数组中的嵌套列

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

给定下面的json片段和模式,是否可以重命名 child 1 在Dataframe中?
有很多重命名嵌套字段的示例( withColumn ),但没有关于在数组中重命名复杂类型的内容。
json文件

{
    "parentArray": [
        {
            "child 1": 0
        },
        {
            "child 1": 1
        }
    ]
}

架构

{
    "fields": [
        {
            "metadata": {},
            "name": "parentArray",
            "nullable": true,
            "type": {
                "containsNull": true,
                "elementType": {
                    "fields": [
                        {
                            "metadata": {},
                            "name": "child 1",
                            "nullable": true,
                            "type": "long"
                        }
                    ],
                    "type": "struct"
                },
                "type": "array"
            }
        }
    ],
    "type": "struct"
}
ocebsuys

ocebsuys1#

试试这个-

加载测试数据

val data =
      """
        |{
        |    "parentArray": [
        |        {
        |            "child 1": 0
        |        },
        |        {
        |            "child 1": 1
        |        }
        |    ]
        |}
      """.stripMargin
    val df = spark.read.option("multiLine", true)
      .json(Seq(data).toDS())
    df.show(false)
    df.printSchema()
    /**
      * +-----------+
      * |parentArray|
      * +-----------+
      * |[[0], [1]] |
      * +-----------+
      *
      * root
      * |-- parentArray: array (nullable = true)
      * |    |-- element: struct (containsNull = true)
      * |    |    |-- child 1: long (nullable = true)
      */

更改数组中的列名

val p = df.withColumn("parentArray", col("parentArray").cast("array<struct<new_col: long>>"))
    p.show(false)
    p.printSchema()

    /**
      * +-----------+
      * |parentArray|
      * +-----------+
      * |[[0], [1]] |
      * +-----------+
      *
      * root
      * |-- parentArray: array (nullable = true)
      * |    |-- element: struct (containsNull = true)
      * |    |    |-- new_col: long (nullable = true)
      */

相关问题