我一直在试图解决这个问题,但实际上无法将它与任何解决方案联系起来。我有以下数据集:
[
{"name": "sam", "hobbies": ["Books", "Music", "Gym"]},
{"name": "Steve", "hobbies": ["Books", "Swimming"]},
{"name": "Alex", "hobbies": ["Gym", "Music"]}
]
我试图生成输出数据集,可以结合人们的爱好。所以输出应该是这样的:
[
{"names": ["sam", "Steve"], "hobbies": ["Books"]},
{"names": ["sam", "Alex"], "hobbies": ["Music", "Gym"]},
{"names": ["Steve"], "hobbies": ["Swimming"]}
]
这是一个很大的数据集,所以我尝试使用spark。
我尝试过的事情:
起初,我想看看这是否是一个图形问题,我可以使用强连接组件之类的东西,但看起来这并不能解决问题。
每个输出行看起来都像一个二部图,但我没有找到一种方法来生成它。
另一种方法是集群,但我认为它不会是确定性的。如果我错了,请告诉我。我对它不太熟悉。
如果我遗漏了一些明显的东西,请告诉我。谢谢。
1条答案
按热度按时间7kqas0il1#
检查以下代码。
使用
groupBy
&collect_list
分组依据hobbies
&收集names
分组依据names
&收集hobbies
```scala> :paste
// Entering paste mode (ctrl-D to finish)
df
.withColumn("hobbies",explode($"hobbies"))
.groupBy($"hobbies").agg(collect_list($"name").as("names")) // For Hobbies List
.groupBy($"name").agg(collect_list($"hobbies").as("hobbies")) // For Name List
.select(collect_list(to_json(struct($"hobbies",$"names"))).as("data")) // Final Json Output
.show(false)
// Exiting paste mode, now interpreting.
+--------------------------------------------------------------------------------------------------------------------------------------------+
|data |
+--------------------------------------------------------------------------------------------------------------------------------------------+
|[{"hobbies":["Swimming"],"names":["Steve"]}, {"hobbies":["Books"],"names":["sam","Steve"]}, {"hobbies":["Music","Gym"],"names":["sam","Alex"]}]|
+--------------------------------------------------------------------------------------------------------------------------------------------+
[
{ "hobbies": ["Swimming"],"names": ["Steve"]},
{"hobbies": ["Books"],"names": ["sam","Steve"]},
{"hobbies": ["Music","Gym"],"names": ["sam","Alex"]}
]