有效计算pyspark中的连接组件
问题描述:
我正在尝试在城市中找到朋友的连接组件。我的数据是具有城市属性的边缘列表。有效计算pyspark中的连接组件
城市| SRC | DEST
火箭的凯尔 - >尼
休斯敦班尼 - >查尔斯
休斯顿查尔斯 - >丹尼
奥马哈卡罗尔 - >布赖恩
等
我知道pyspark的GraphX库的connectedComponents函数将遍历图的所有边以找到连接的组件,并且我想避免这一点。我会怎么做?
编辑: 我想我可以做这样的事情,从数据帧 GROUPBY城市
其中connected_components生成的项目列表
选择connected_components(*)。
答
假设你的数据是这样的
import org.apache.spark._
import org.graphframes._
val l = List(("Houston","Kyle","Benny"),("Houston","Benny","charles"),
("Houston","Charles","Denny"),("Omaha","carol","Brian"),
("Omaha","Brian","Daniel"),("Omaha","Sara","Marry"))
var df = spark.createDataFrame(l).toDF("city","src","dst")
创建要运行连接部件 cities = List("Houston","Omaha")
现在,在城市名单上运行的城市列的过滤器对每个城市的城市名单,然后从结果数据框中创建边和顶点数据帧。创建从这些边缘和顶点dataframes一个graphframe和运行连接组件的算法
val cities = List("Houston","Omaha")
for(city <- cities){
val edges = df.filter(df("city") === city).drop("city")
val vert = edges.select("src").union(edges.select("dst")).
distinct.select(col("src").alias("id"))
val g = GraphFrame(vert,edges)
val res = g.connectedComponents.run()
res.select("id", "component").orderBy("component").show()
}
输出
| id| component|
+-------+------------+
| Kyle|249108103168|
|charles|249108103168|
| Benny|249108103168|
|Charles|721554505728|
| Denny|721554505728|
+-------+------------+
+------+------------+
| id| component|
+------+------------+
| Marry|858993459200|
| Sara|858993459200|
| Brian|944892805120|
| carol|944892805120|
|Daniel|944892805120|
+------+------------+
+0
谢谢你的工作! 好吧,喂。我认为可能会比金属更接近一点,而不是循环访问我想阻止的值,但我仍然感谢您的回答 – oliver
避免问同样的问题两次:https://stackoverflow.com/questions/46386182/how-would -i-phrase-this-python-code-in-pyspark-sql-or-sql – Mariusz
删除旧的,这个有更好的措辞。 – oliver