原文地址:https://www.jianshu.com/p/8b0a4ce52703
Connected Components介绍
- Connected Components算法是计算Graph图中每个顶点所连接的最小顶点值,通过这个算法可以清晰的看到Graph图中有几个连通图
示例图
- 可以看到这个Graph图中存在两个连通图
测试数据
- links.csv
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
- people.csv
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
使用Connected Components
object ConnectedComponents {
def main(args: Array[String]): Unit = {
val conf: SparkConf = new SparkConf().setAppName("cc").setMaster("local")
val sc = new SparkContext(conf)
//定义样例类Person
case class Person(name:String,age:Int)
//首先读取people.csv文件
//将读取的数据以”,“拆分,每行拆分的数据形成一个字符串数组
//在对数组进行操作,最后形成RDD[(Long,Person)]的类型
val verticesRDD: RDD[(Long, Person)] = sc.textFile("in/people.csv").map(x=>x.split(",")).map(row=>(row(0).toLong,Person(row(1),row(2).toInt)))
//首先读取links.csv文件
//将读取的数据以”,“拆分,在对拆分后形成的数组进行操作,生成对应的Edge
val edgeRDD: RDD[Edge[String]] = sc.textFile("in/links.csv").map(x=>{val row=x.split(",");Edge(row(0).toInt,row(1).toInt,row(2))})
//创建Graph
val graph=Graph(verticesRDD,edgeRDD)
//使用connectedComponents
val ccGraph: Graph[VertexId, String] = graph.connectedComponents()
//得到ccGraph顶点数据并转成List集合输出
println(ccGraph.vertices.collect.toList)
}
}
输出结果:
List((4,1), (11,10), (1,1), (6,1), (8,1), (3,1), (9,1), (7,1), (12,10), (10,10), (5,1), (2,1))
PS:从结果可以看出顶点的最小连接点有两个,1和10所有该图存在两个连通图