以下代码在 scala 中,但应该演示这个想法。
返回的图会包含所有的顶点,但是每个顶点的属性都被替换为一个VertexId(实际上只是一个Long),可以解释为该顶点所属的连通组件的id。它也是属于该连接组件的“最低顶点 id”。
import org.apache.spark.graphx._
import org.apache.spark.rdd.RDD
val vertexArray = Array(
(1L, ("A", 28)),
(2L, ("B", 27)),
(3L, ("C", 65)),
(4L, ("D", 42)),
(5L, ("E", 55)),
(6L, ("F", 50)),
(7L, ("G", 53)),
(8L, ("H", 66))
)
// Vertices 1 - 6 are connected, 7 and 8 are connected.
val edgeArray = Array(
Edge(2L, 1L, 7),
Edge(2L, 4L, 2),
Edge(3L, 2L, 4),
Edge(3L, 6L, 3),
Edge(4L, 1L, 1),
Edge(5L, 2L, 2),
Edge(5L, 3L, 8),
Edge(5L, 6L, 3),
Edge(7L, 8L, 3)
)
val vertexRDD: RDD[(Long, (String, Int))] = sc.parallelize(vertexArray)
val edgeRDD: RDD[Edge[Int]] = sc.parallelize(edgeArray)
val graph: Graph[(String, Int), Int] = Graph(vertexRDD, edgeRDD)
val cc = graph.connectedComponents().vertices.collectAsMap()
cc.foreach {
case (vertexId, clusterId) =>
println(s"Vertex $vertexId belongs to cluster $clusterId")
}
输出:
Vertex 8 belongs to cluster 7
Vertex 2 belongs to cluster 1
Vertex 5 belongs to cluster 1
Vertex 4 belongs to cluster 1
Vertex 7 belongs to cluster 7
Vertex 1 belongs to cluster 1
Vertex 3 belongs to cluster 1
Vertex 6 belongs to cluster 1