hive表中有某一列是struct类型,现在的需求是将这个struct类型中的某一子列抽取出来,并且转换成字符串类型之后,添加成与struct类型的列同一级别的列。
然后网上搜了一下答案,发现使用scala操作子列很方便,但是我们组使用语言还是python,然后搜到此方法方法:drop nested columns https://stackoverflow.com/questions/45061190/dropping-nested-column-of-dataframe-with-pyspark/48906217#48906217。我参照此方法针对我的需求做了修改。
exclude_nested_field方法中将去掉不需要的field.name,及其对应的StructType包装成的StructField,这样从schema上看就是移除了某一子列。
1 | def exclude_nested_field(schema, unwanted_fields, parent=""): |
exclude_nested_field_name方法中将去掉不需要的StructField中的field.name,只保留对应的StructType。
1 | def exclude_nested_field_name(schema, unwanted_field_name, parent=""): |
使用示例:
1 | # charge_data为struct类型,过滤掉charge_data这个field name对应的StructType中的details StructField |