你可以这样做:
- 定义架构,并使用架构将平面 json 转换为数据框。
- 注册几个 UDF 以构建用户和事件映射。
- 使用 #2 中的 UDF 寄存器在数据框中添加新列(用户和事件)
- 删除多余的列
完整代码如下:
from pyspark.sql.types import (
StringType,
StructField,
StructType,
MapType
)
from pyspark.sql.functions import udf
events_schema = StructType([
StructField('event_type', StringType(), True),
StructField('id', StringType(), True),
StructField('person_id', StringType(), True),
StructField('category', StringType(), True),
StructField('approved_content', StringType(), True),
])
events = [{
'event_type': 'click',
'id': '223',
'person_id': 201031940,
'category': 'Chronicles',
'approved_content': 1
}]
df = spark.createDataFrame(events, schema=events_schema)
build_user_udf = udf(lambda id, person_id: {
'id': id,
'person_id': person_id
}, MapType(StringType(), StringType()))
build_event_udf = udf(lambda category, approved_content: {
'category': category,
'approved_content': approved_content
}, MapType(StringType(), StringType()))
nested_event_df = (
df
.withColumn('user', build_user_udf(df['id'], df['person_id']))
.withColumn('event', build_event_udf(df['category'], df['approved_content']))
.drop('id')
.drop('person_id')
.drop('category')
.drop('approved_content')
)
nested_event_df.toJSON().first()
'{"event_type":"click","user":{"id":"223","person_id":"201031940"},"event":{"approved_content":"1","category ":"编年史"}}'
nested_event_df.take(1)
[Row(event_type='click', user={'id': '223', 'person_id': '201031940'}, event={'approved_content': '1', 'category': 'Chronicles' })]
这是一个非常基础的版本,但如果你愿意,你可以做更多的优化。