【问题标题】:Convert datatype of cloumn from StringType to StructType in dataframe in spark scala将列的数据类型从 StringType 转换为 Spark Scala 中数据框中的 StructType
【发布时间】:2019-08-25 20:48:16
【问题描述】:
|     ID|CO_ID|                           DATA|
+--------------------+--------------------+----+
|ABCD123|abc12|[{"month":"Jan","day":"monday"}] |
|BCHG345|wed34|[{"month":"Jul","day":"tuessay"}]|

我有上面的数据框,其中 DATA 列是 StringType。我希望它转换为 StructType。我该怎么做?

【问题讨论】:

    标签: apache-spark dataframe apache-spark-sql bigdata


    【解决方案1】:

    使用from_json

    df.withColumn("data_struct",from_json($"data",StructType(Array(StructField("month", StringType),StructField("day", StringType)))))
    

    在 Spark 2.4.0 上,我得到以下信息

    import org.apache.spark.sql.types.{StructType, StructField, StringType}
    
    val df = List ( ("[{\"month\":\"Jan\",\"day\":\"monday\"}]")).toDF("data")
    
    val df2 = df.withColumn("data_struct",from_json($"data",StructType(Array(StructField("month", StringType),StructField("day", StringType)))))
    
    df2.show
    
    +--------------------+-------------+
    |                data|  data_struct|
    +--------------------+-------------+
    |[{"month":"Jan","...|[Jan, monday]|
    +--------------------+-------------+
    
    df2.printSchema
    
    root
     |-- data: string (nullable = true)
     |-- data_struct: struct (nullable = true)
     |    |-- month: string (nullable = true)
     |    |-- day: string (nullable = true)
    

    【讨论】:

    • 我在 data_struct 列中得到所有空值
    • 你用的是什么版本的spark?
    • 我使用的是 2.4.0
    • 好吧,我也使用 2.4.0 并且它可以工作。看看我更新的答案。
    • root |-- ID: 字符串 (nullable = true) |-- CO_ID: string (nullable = true) |-- data_struct: struct (nullable = true) | |-- 月份:字符串(可为空=真)| |-- day: string (nullable = true) 我需要这个
    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多