根据pyspark collect_set or collect_list with groupby中的最佳答案,当您对某一列进行
为了符合上述嵌套映射,我转换了我的数据框,以便于每个eId和cId的组合,我都有一个像这样的交易数组:
将
如您所见-当
然而,当我尝试使用上述索引将
collect_list
操作时,该列中的null
值将被删除。我已经验证了这一点。
但在我的情况下,我需要保留空列--怎样实现这个需求呢?
我没有找到任何有关这种变体collect_list
函数的信息。
背景说明为什么我要使用空列:
我有一个数据框df
如下:
cId | eId | amount | city
1 | 2 | 20.0 | Paris
1 | 2 | 30.0 | Seoul
1 | 3 | 10.0 | Phoenix
1 | 3 | 5.0 | null
我希望将以下内容写入一个Elasticsearch索引,并使用以下映射:
"mappings": {
"doc": {
"properties": {
"eId": { "type": "keyword" },
"cId": { "type": "keyword" },
"transactions": {
"type": "nested",
"properties": {
"amount": { "type": "keyword" },
"city": { "type": "keyword" }
}
}
}
}
}
为了符合上述嵌套映射,我转换了我的数据框,以便于每个eId和cId的组合,我都有一个像这样的交易数组:
df_nested = df.groupBy('eId','cId').agg(collect_list(struct('amount','city')).alias("transactions"))
df_nested.printSchema()
root
|-- cId: integer (nullable = true)
|-- eId: integer (nullable = true)
|-- transactions: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- amount: float (nullable = true)
| | |-- city: string (nullable = true)
将
df_nested
保存为json文件后,我得到了以下json记录:{"cId":1,"eId":2,"transactions":[{"amount":20.0,"city":"Paris"},{"amount":30.0,"city":"Seoul"}]}
{"cId":1,"eId":3,"transactions":[{"amount":10.0,"city":"Phoenix"},{"amount":30.0}]}
如您所见-当
cId=1
和eId=3
时,我的一个数组元素中amount=30.0
的元素没有city
属性,因为这在我的原始数据(df
)中是null
。使用collect_list
函数时,空值被删除了。然而,当我尝试使用上述索引将
df_nested
写入elasticsearch时,会出现模式不匹配的错误。这基本上就是我希望在应用collect_list
函数后保留我的空值的原因。
null
值,比如字符串'null'
? - pault