【问题标题】:To change table schema in Databricks在 Databricks 中更改表架构
【发布时间】:2022-10-14 22:12:28
【问题描述】:
有没有办法改变表中结构列内的数据类型?
例子:
emp_details: struct
emp_id: integer
emp_name: string
如果emp_details 是表中的列,该列是严格类型的,并且在其中存在emp_id 和emp_name,我想将emp_id 更改为字符串。
【问题讨论】:
标签:
pyspark
schema
databricks
alter
drop
【解决方案1】:
是的你可以。您应该显式地转换列并使用转换的列构建新的emp_details。创建所需的数据框后,您可以覆盖 Databricks 中的表以使用所需的模式存储它。
这应该看起来像这样:
# For code readability, let's first create the correct casted column
original_df_with_casted_column_df = original_df.withColumn("casted_emp_id", col("emp_details.emp_id").cast("string"))
# We generate the new struct field using the original emp_name column and the newly created column after renaming it.
final_df = original_df.select(struct(col("casted_emp_id").alias("emp_id"), col("emp_name")).alias("emp_details"))