Update structured values of a map type column in Pyspark

Viewed 1091

I am trying to modify a Dataframe column of type Map the values of which are in turn of type Struct:

root
 |-- name: string (nullable = true)
 |-- age: long (nullable = true)
 |-- MapName: map (nullable = true)
 |    |-- key: string
 |    |-- value: struct (valueContainsNull = true)
 |    |    |-- field1: double (nullable = true)
 |    |    |-- field2: double (nullable = true)

I created the DataFrame in a way MapName column is initialised to None as I will need to fill infos in later stages. The code I used is as follows:

from pyspark.sql import SparkSession, DataFrame
from pyspark.sql.functions import col, udf, lit
from pyspark.sql.types import StructType, StringType, LongType, DoubleType, MapType

spark = SparkSession.builder.appName("testMapType").getOrCreate()

data = [('Alice', 1)]
df = spark.createDataFrame(data, ['name','age'])

def value_struct():
    schema = StructType([
        StructField('field1', DoubleType(), True),
        StructField('field2', DoubleType(), True)])

    return schema

myschema = StructType([
        StructField('name', StringType(), True),
        StructField('age', LongType(), True),
        StructField('MapName', MapType(StringType(), value_struct()), True)])

df = df.withColumn('MapName',lit(None).cast(MapType(StringType(), value_struct())))
df = spark.createDataFrame(df.rdd, schema=myschema)
df.printSchema()

Now when I try to update the MapName column using a udf like this:

my_update_udf = udf(lambda x: {**x, **{'a_map_key':{'field1':3.2,'field2':2.6}}}, MapType(StringType(), value_struct()))
df2 = df.withColumn('MapName', my_update_udf(col('MapName')))
df2.collect()

I get the following error:

TypeError: 'NoneType' object is not a mapping

I cannot find any suggestion from past inquires, any help here?

1 Answers

You don't need a UDF for this. You can use the relevant Spark SQL functions for creating maps and structs.

import pyspark.sql.functions as F

new_map = F.create_map(
    F.lit('a_map_key'),
    F.struct(
        F.lit(3.2).alias('field1'),
        F.lit(2.6).alias('field2')
    )
)

df2 = df.withColumn(
    'MapName',
    F.when(
        F.col('MapName').isNotNull(),      # need to check null because 
        F.map_concat('MapName', new_map)   # map_concat doesn't work if map is null
    ).otherwise(new_map)
)

df2.show(truncate=False)
+-----+---+-------------------------+
|name |age|MapName                  |
+-----+---+-------------------------+
|Alice|1  |[a_map_key -> [3.2, 2.6]]|
+-----+---+-------------------------+
Related