【问题标题】:Convert Struct data type to Map data type in Scala在 Scala 中将 Struct 数据类型转换为 Map 数据类型
【发布时间】:2019-07-31 05:27:38
【问题描述】:

如何将数据类型为 struct 的列转换为 Map 或 String。这是架构:

root
 |-- Col1: string (nullable = true)
 |-- Col2: struct (nullable = true)
 |    |-- _1: string (nullable = true)
 |    |-- _2: integer (nullable = false)

当我想将数据框转储到文件中时,第二列会出现问题。我尝试了许多不同的方法,例如转换为字符串,但它改变了第二列中的值。我也尝试将 Col2 转换为地图,但没有成功。

我试图通过 udf 获取 struct(_1) 中的第一个值,但它有错误:

执行用户定义函数失败($anonfun$1: (struct) => string)

【问题讨论】:

    标签: scala dataframe struct type-conversion user-defined-functions


    【解决方案1】:
    Select Col1, Col2._1, Col2._2 from <your table>
    

    通过 spark.sql,你可以试试这个并将其保存到另一个数据帧,然后写入 CSV。

    【讨论】:

    • 谢谢!这是我在 Scala 中使用您的建议的方式: var df_new = df_old.select($"col1", $"col2._1", $"col2._2")
    【解决方案2】:

    在 Scala 中我们可以这样做:

    val df_new = df_old.select($"Col1", $"Col2._1", $"Col3._2")
    

    【讨论】:

    • 在 scala 中使用 var 不是一个好习惯,除非您打算使 df_new 可变
    【解决方案3】:

    您还可以使用 * 表示法来扩展 Struct 数据类型中的所有列。

    架构

    root
    |-- address: struct (nullable = false)
    |    |-- street: string (nullable = true)
    |    |-- city: string (nullable = true)
    |    |-- state: string (nullable = true)
    

    扩展 SQL

    val df1 = df.select("address.*").show(false)
    df1.printSchema
    root
     |-- street: string (nullable = true)
     |-- city: string (nullable = true)
     |-- state: string (nullable = true)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 2012-11-09
      • 2021-03-02
      • 2022-07-06
      • 2019-07-15
      相关资源
      最近更新 更多