首页 > 解决方案 > 使用 ALTER TABLE 将新列添加到 Databricks 上的 Array(Struct) 列中

问题描述

我有一个 DeltaTable,其中有几列是 ArrayTypes,包含 StructTypes。

我正在尝试在 StructType 中添加一个额外的列,但我遇到了问题,因为它包含在 ArrayType 中。

希望有人有办法做到这一点,或者类似的方法不涉及我备份表,从头开始重新创建表并从备份中恢复数据。

我目前正在使用这个命令:

spark.sql(f"ALTER TABLE {db}.ads ADD COLUMNS (response.monkey boolean AFTER dq_conveyed)")

如果它只是一个 StructType 会起作用,但因为它是一个数组而失败

这是我正在尝试更改的当前架构:

StructField(response,ArrayType(StructType(
    StructField(encounter_uid,StringType,true),
    StructField(patient_uid,StringType,true),
    StructField(call_sign,StringType,true),
    StructField(time_resource_allocated,StringType,true),
    StructField(time_resource_arrived_at_receiving_location,StringType,true),
    StructField(time_of_patient_handover,StringType,true),
    StructField(time_clear,StringType,true),
    StructField(response_type,StringType,true),
    StructField(time_resource_mobilised,StringType,true),
    StructField(time_resource_arrived_on_scene,StringType,true),
    StructField(time_stood_down,StringType,true),
    StructField(time_resource_left_scene,StringType,true),
    StructField(highest_skill_level_on_vehicle,StringType,true),
    StructField(responding_organisation_type,StringType,true),
    StructField(dq_conveyed,BooleanType,true)),
true),true)

我正在关注此文档:

https://docs.databricks.com/spark/latest/spark-sql/language-manual/sql-ref-syntax-ddl-alter-table.html

标签: apache-sparkdatabricksdelta-lake

解决方案


你可以做:

spark.sql(f"ALTER TABLE {db}.ads ADD COLUMNS (response.element.monkey boolean AFTER dq_conveyed)")

注意element关键字。如果这对您不起作用,请告诉我!


推荐阅读