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

Scala Spark:如何提取Schema中数组类型字段的名称

解答

现有Schema结构:

|-- test: struct (nullable = true)
|    |-- MOB: array (nullable = true)

能否从该Schema中提取出数组类型字段的名称MOB?

完全可以,核心思路是遍历Schema的层级结构做类型筛选,具体逻辑如下:

  • 首先找到根层级的test字段,确认其数据类型为Struct结构体类型
  • 遍历test结构体下的所有子字段,筛选出数据类型为Array数组类型的字段
  • 直接读取符合条件的字段的名称属性,即可得到MOB

以PySpark为例,参考实现代码如下:

from pyspark.sql.types import ArrayType, StructType

# 入参为DataFrame的schema,返回所有数组类型的字段名
def get_array_field_names(schema):
    array_fields = []
    for field in schema.fields:
        if isinstance(field.dataType, ArrayType):
            array_fields.append(field.name)
        # 嵌套结构体的话递归遍历
        elif isinstance(field.dataType, StructType):
            array_fields.extend(get_array_field_names(field.dataType))
    return array_fields

# 调用示例,假设你的DataFrame名为df
result = get_array_field_names(df.schema)
# 输出结果就是 ['MOB']

其他语言的Spark API实现逻辑完全一致,只要遍历结构体下的字段匹配数组类型后取名称即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:45:07