In PySpark, we can use withField:
from pyspark.sql import functions as F
df = spark.createDataFrame([((1,),)], ['mystruct'])
df = df.withColumn('mystruct', F.col('mystruct').withField('n', F.lit(3)))
df.printSchema()
# root
# |-- mystruct: struct (nullable = true)
# | |-- _1: long (nullable = true)
# | |-- n: integer (nullable = false)
How to use this in Spark SQL?
I've tried looking at the logical plan and applying the result to expr:
df.explain(True)
# == Parsed Logical Plan ==
# 'Project [update_fields('mystruct, WithField(n, 3)) AS mystruct#84]
# +- LogicalRDD [mystruct#82], false
# ...
df = spark.createDataFrame([((1,),)], ['mystruct'])
df = df.withColumn('mystruct', F.expr("update_fields(mystruct, WithField(n, 3))"))
Undefined function: update_fields. This function is neither a built-in/temporary function, nor a persistent function that is qualified as spark_catalog.default.update_fields.; line 1 pos 0