有效地计算pyspark中的连通组件

时间:2017-09-25 01:59:27

标签: graph spark-dataframe spark-graphx connected-components graphframes

我试图为城市中的朋友找到连接的组件。我的数据是具有城市属性的边缘列表。

城市| SRC | DEST

Houston Kyle - >尼

Houston Benny - >查尔斯

Houston Charles - >丹尼

奥马哈卡罗尔 - >布赖恩

等。

我知道pyspark的GraphX库的connectedComponents函数将迭代图形的所有边缘以找到连接的组件,我想避免这种情况。我该怎么做?

编辑: 我以为我可以做像

这样的事情

从dataframe中选择connected_components(*) groupby city

其中connected_components生成项目列表。

1 个答案:

答案 0 :(得分:1)

假设您的数据是这样的

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")

现在在城市列中为城市列表中的每个城市运行一个过滤器,然后从结果数据框中创建边和顶点数据框。从这些边和顶点数据帧创建一个图形框架并运行连通组件算法

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|
+------+------------+
相关问题