💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
* 构建用户合作关系属性图 * 顶点属性:用户名、职业 * 边属性:表示合作关系 ![](https://img.kancloud.cn/95/b5/95b524454711401f2b191cc70935ddc5_785x409.png) ```scala import org.apache.spark.SparkContext import org.apache.spark.graphx.{Edge, Graph} import org.apache.spark.rdd.RDD import org.apache.spark.sql.SparkSession object PartnershipGraphx { def main(args: Array[String]): Unit = { val spark:SparkSession = SparkSession.builder() .master("local[4]") .appName(this.getClass.getName) .getOrCreate() val sc:SparkContext = spark.sparkContext import spark.implicits._ // 1. 构建表示用户的点集合 val users:RDD[(Long, (String, String))] = sc.parallelize(Array( // (点Id, (点名, 点值)) (3L, ("rxin", "student")), (7L, ("jgonzal", "postdoc")), (5L, ("franklin", "professor")), (2L, ("istoica", "professor")) )) // 2. 构建表示点与点关系的边的集合 val relationships:RDD[Edge[String]] = sc.parallelize(Array( // Edge(srcId, dstId, edgeAttr) (Edge(3L, 7L, "collaborator")), (Edge(5L, 3L, "advisor")), (Edge(2L, 5L, "colleague")), (Edge(5L, 7L, "PI")) )) // 3. 使用点集合与边集合构建图 // Graph[(点值类型), 边值类型] val graph:Graph[(String, String), String] = Graph(users, relationships) // 图所有的顶点 graph.vertices.foreach(x=>println(s"(Id:${x._1}, Attr:${x._2})")) // (Id:2, Attr:(istoica,professor)) // (Id:3, Attr:(rxin,student)) // (Id:5, Attr:(franklin,professor)) // (Id:7, Attr:(jgonzal,postdoc)) // 图的所有边 graph.edges.foreach(x=>println(s"(srcId:${x.srcId}, distId:${x.dstId}, edgeAttr:${x.attr})")) // (srcId:2, dstId:5, edgeAttr:colleague) // (srcId:5, dstId:7, edgeAttr:PI) // (srcId:3, dstId:7, edgeAttr:collaborator) // (srcId:5, dstId:3, edgeAttr:advisor) // triplets带有属性的点和边 graph.triplets.foreach(x=>println(x.toString())) // ((srcId, (srcAttr)), (dstID, (dstAttr)), edgeAttr) // ((5,(franklin,professor)),(3,(rxin,student)),advisor) // ((2,(istoica,professor)),(5,(franklin,professor)),colleague) // ((3,(rxin,student)),(7,(jgonzal,postdoc)),collaborator) // ((5,(franklin,professor)),(7,(jgonzal,postdoc)),PI) } } ```