首页 > 解决方案 > 数组类型列中元素的数据类型修改

问题描述

我有一个具有以下模式的数据框,用于列 col。

col:array
    element:struct
      Id:string
      Seq:int
      Pct:double
      Amt:long

当数据不可用时,下面是结构

col:array
   element:string

该列可以包含数据并且可以为空。

当数据可用时,它的来源格式如下:

{"Id": "123456-1", "Seq": 1, "Pct": 0.1234, "Amt": 3000}

当数据不可用时,我将默认设置如下:

.withColumn("col", when (size($"col") === 0, array(lit("A").cast("string"), lit(0).cast("int"), lit(0.0).cast("double"))).otherwise($"col")

对于我得到的空数据,数据似乎被转换为字符串:

["A", "0", "0.0", "0.0"]

如何获得以下输出:

{"Id": "A", "Seq": 0, "Pct": 0.0}

当数据在以下源中可用时是输出:

+----------------------------------------------------+
|   Data                                             |
+----------------------------------------------------+
|[[236711-1, 0.14, 1.5, 1], [236711-1, 0.14, 2.0, 2]]|
|[[1061605-1, 0.011, 1.0, 1]]                        |
+----------------------------------------------------+

数据不可用时

| Data |
+------+
|[]    |
+------+

标签: scalaapache-sparkapache-spark-sql

解决方案


您可以创建一个结构的数组而不是数组:

val df2 = df.withColumn(
    "col",     
    df.schema("col").dataType match {
        case ArrayType(StringType, _) =>
            array(
                struct(
                    lit("A").cast("string").as("Id"), 
                    lit(0).cast("int").as("Seq"), 
                    lit(0.0).cast("double").as("Pct")
                )
            )
        case ArrayType(StructType(_), _) => $"col"
    }
)

推荐阅读