【问题标题】:Schema Conversion from String datatype to Array(Map(Array)) datatype in PysparkPyspark 中从字符串数据类型到数组(映射(数组))数据类型的模式转换
【发布时间】:2019-10-07 13:00:18
【问题描述】:

我们正在从 dynamo db 读取数据,因此我们将数据类型作为字符串,但我们希望将字符串数据类型写入数组(映射(数组))

字符串数据:

{"policy_details":[{"cdhid":"123","p2cid":"NA", "roleDesc":"NA","positionnum":"NA"}, {"cdhid":" 1234 ","p2cid":"NA", "roleDesc":"NA","positionnum":"NA"}]}

需要输出: 字符串数据类型需要转换为ARRAY(MAP(ARRAY))

我们尝试了以下架构:

ArrayType([
    StructField("policy_num", MapType(ArrayType([
        StructField("cdhid", StringType(), True), 
        StructField("role_id", StringType(), True),
        StructField("role_desc", StringType(), True)
    ])))
])

遇到以下问题:

elementType [StructField(cdhid,StringType,true), StructField(role_id,StringType,true), StructField(role_desc,StringType,true)] 应该是

的实例

【问题讨论】:

  • 您使用哪个版本的 spark ?你试过什么?您当前的“架构”不适合您的数据。用您当前的数据解释预期的输出。你当前的数据结构是map(array(map))

标签: dataframe pyspark schema pyspark-sql


【解决方案1】:

关于您的数据,您想要的架构并不适合。 你的数据架构是:

from pyspark.sql import types as T

schm = T.StructType([T.StructField("policy_details",T.ArrayType(T.StructType([ 
        T.StructField("cdhid", T.StringType(), True), 
        T.StructField("p2cid", T.StringType(), True), 
        T.StructField("roleDesc", T.StringType(), True),  
        T.StructField("positionnum", T.StringType(), True), 
    ])), True)])

然后,您只需要使用from_json 函数。

from pyspark.sql import functions as F

df.show()                                                                                                         
+--------------------+                                                          
|             db_data|
+--------------------+
|{"policy_details"...|
+--------------------+

new_df = df.select(F.from_json("db_data", schm).alias("data"))

new_df.printSchema()                                                                                              
root
 |-- data: struct (nullable = true)
 |    |-- policy_details: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- cdhid: string (nullable = true)
 |    |    |    |-- p2cid: string (nullable = true)
 |    |    |    |-- roleDesc: string (nullable = true)
 |    |    |    |-- positionnum: string (nullable = true)

编辑:如果你想使用MapType,你可以用:

替换架构
schm = T.StructType([
    T.StructField(
        "policy_details",
        T.ArrayType(T.MapType(
            T.StringType(), 
            T.StringType()
        )), 
        True
    )
]) 

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 1970-01-01
    • 2015-02-08
    • 2021-10-03
    • 1970-01-01
    • 2022-10-13
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多