连通分量
连通分量是一个子图,其中任何两个顶点通过一条边或一系列边相互连接,其顶点是原始图顶点集的子集,其边是原始图边集的子集
def connectedComponents(): Graph[VertexID, ED]
示例:
数据准备
//reference.txt
1,2,friend
1,3,sister
2,4,brother
3,2,boss
4,5,client
1,9,friend
6,7,cousin
7,9,coworker
8,9,father
10,11,colleague
10,12,colleague
11,12,colleague
//p.txt
4,Dave,25
6,Faith,21
8,Harvey,47
2,Bob,18
1,Alice,20
3,Charlie,30
7,George,34
9,Ivy,21
5,Eve,30
10,Lily,35
11,Helen,35
12,Ann,35
关系图
spark-shell操作
case class Person(name:String,age:Int)
val people = sc.textFile("file:///opt/file/p.txt")
val re = sc.textFile("file:///opt/file/reference.txt")
val peopleRdd = people.map(_.split(",")).map(x=>(x(0).toLong,Person(x(1),x(2).toInt)))
val reRdd = re.map(_.split(",")).map(x=>Edge(x(0).toInt.x(1).toInt,x(2)))
val graph = Graph(peopleRdd,reRdd)
val cc = graph.connectedComponents
cc.vertices.collect.foreach(println)
输出:
(4,1)
(11,10)
(1,1)
(6,1)
(8,1)
(3,1)
(9,1)
(7,1)
(12,10)
(10,10)
(5,1)
(2,1)
从结果可看出,每个顶点多了一个属性,即每个连通图最小顶点的 id
扩展部分
将每个连通图拆解出来
val newGraph = cc.outerJoinVertices(peopleRdd)((id,cc,p)=>(cc,p.get.name,p.get.age))
cc.vertices.collect.map(_._2).distinct.foreach(
id =>{
val sub = newGraph.subgraph(vpred=(id1,v)=>v._1 == id)
sub.vertices.collect.foreach(println)
//一张子图打印完成后换行
println()
})
过程分析:
-
通过connectedComponents得到的新图的顶点属性
-
通过join加入原顶点数据
原因是经过连通分量后顶点数据会更改,如下图:
-
通过distinct会得到所有连通图中id最小的顶点编号,使用subgraph方法得到每个连通子图