如何遍历Glue DynamicFrame并定位存在ChoiceType类型的字段
遍历Glue DynamicFrame提取所有ChoiceType类型键名的实现方法
核心思路是直接读取DynamicFrame的schema属性,递归遍历所有字段(含嵌套结构、数组结构的内部字段),判断类型是否为ChoiceType即可。
实现代码
from awsglue.types import ChoiceType def find_choice_type_keys(schema, parent_path=""): choice_keys = [] for field in schema.fields: # 拼接完整字段路径,嵌套结构会自动带上父级路径 current_path = f"{parent_path}.{field.name}" if parent_path else field.name # 判断当前字段是否为ChoiceType if isinstance(field.dataType, ChoiceType): choice_keys.append(current_path) # 递归遍历Struct嵌套结构 elif hasattr(field.dataType, "fields"): choice_keys.extend(find_choice_type_keys(field.dataType, current_path)) # 递归遍历Array数组的元素类型 elif hasattr(field.dataType, "elementType"): element_type = field.dataType.elementType if isinstance(element_type, ChoiceType): choice_keys.append(f"{current_path}[*]") elif hasattr(element_type, "fields"): choice_keys.extend(find_choice_type_keys(element_type, f"{current_path}[*]")) return choice_keys
调用示例
# 你已创建的DynamicFrame file = glueContext.create_dynamic_frame.from_options(...) # 提取所有ChoiceType的键名 choice_type_keys = find_choice_type_keys(file.schema) # 打印结果 print(choice_type_keys)
结果说明
返回的列表会包含所有带完整路径的ChoiceType字段:
- 顶层字段直接返回字段名,示例:
["user_id", "order_amount"] - 嵌套结构体字段返回层级路径,示例:
["user_info.address.postcode"] - 数组元素的ChoiceType会带数组标识,示例:
["order_list[*].price"]
如果你后续需要统一ChoiceType的类型消除歧义,可以用如下代码批量处理:
resolved_dyf = file.resolveChoice(specs = [(key, "cast:long") for key in choice_type_keys])
内容的提问来源于stack exchange,提问作者eeeVillain
相关产品推荐
相关产品推荐

