You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Databricks使用when-otherwise处理混合类型列时AnalysisException报错问题

解决Databricks中explode_outer后JSON列类型推断错误的问题

方法1:提前指定Schema解析JSON

自动类型推断在无数据时会误将JSON列识别为string,最可靠的方式是手动定义struct类型的Schema,在解析JSON时强制使用该Schema,确保无论是否有数据,列类型都是struct。

示例代码:

from pyspark.sql.types import StructType, StructField, StringType
from pyspark.sql.functions import from_json, explode_outer, col

# 定义LeadOrganisation的结构体Schema
lead_org_schema = StructType([
    StructField("Code", StringType(), nullable=True)
])

# 先将原始JSON列解析为指定Schema的struct类型,再执行explode_outer
df = df.withColumn("LeadOrganisation", from_json(col("LeadOrganisation"), lead_org_schema))
df = df.withColumn("LeadOrganisation", explode_outer(col("LeadOrganisation")))

# 安全提取Code字段
df = df.withColumn("LeadOrgCode", col("LeadOrganisation.Code"))

方法2:强制转换列类型为struct

如果已经完成explode_outer操作,可直接将误判为string的列强制转换为指定的struct类型,再提取字段:

示例代码:

from pyspark.sql.types import StructType, StructField, StringType
from pyspark.sql.functions import col, when

lead_org_schema = StructType([
    StructField("Code", StringType(), nullable=True)
])

# 将列强制转换为struct类型
df = df.withColumn("LeadOrganisation", col("LeadOrganisation").cast(lead_org_schema))

# 提取Code字段,空值时返回null
df = df.withColumn("LeadOrgCode", when(col("LeadOrganisation").isNotNull(), col("LeadOrganisation.Code")).otherwise(None))

方法3:替换空值为合法的空struct JSON

若原始数据中存在空字符串或null的JSON列,可先将这些空值替换为符合struct格式的空JSON字符串,再解析为struct类型:

示例代码:

from pyspark.sql.types import StructType, StructField, StringType
from pyspark.sql.functions import from_json, to_json, struct, lit, when, col

lead_org_schema = StructType([
    StructField("Code", StringType(), nullable=True)
])

# 将空值/空字符串替换为包含空Code的JSON字符串
df = df.withColumn("LeadOrganisation", 
    when(
        col("LeadOrganisation").isNull() | (col("LeadOrganisation") == ""),
        to_json(struct(lit(None).alias("Code")))
    ).otherwise(col("LeadOrganisation"))
)

# 解析为struct类型后提取字段
df = df.withColumn("LeadOrganisation", from_json(col("LeadOrganisation"), lead_org_schema))
df = df.withColumn("LeadOrgCode", col("LeadOrganisation.Code"))

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 22:21:36