🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
Graph有一个隐式的函数来调用GraphOps类,图的属性不是在Graph,而是在GraphOps类中,如下 ```scala object Graph extends scala.AnyRef with scala.Serializable { implicit def graphToGraphOps[VD, ED] class GraphOps[VD, ED]{ lazy val numEdges : scala.Long = { // 边的数量 lazy val numVertices : scala.Long = { // 顶点数量 lazy val inDegrees : org.apache.spark.graphx.VertexRDD // 入度 lazy val outDegrees : org.apache.spark.graphx.VertexRDD // 出度 lazy val degrees : org.apache.spark.graphx.VertexRDD // 度 ``` ![](https://img.kancloud.cn/fc/92/fc92b71f52c778519fbd1cbb3b2b0fbc_1009x396.png) 获取上面这个图的属性。 ```scala import org.apache.spark.SparkContext import org.apache.spark.graphx.{Edge, Graph, VertexId} import org.apache.spark.rdd.RDD import org.apache.spark.sql.SparkSession object GraphxAttr { 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, Int))] = sc.parallelize(Array( (1L, ("Alice", 28)), (2L, ("Bob", 27)), (3L, ("Charlie", 65)), (4L, ("David", 42)), (5L, ("Ed", 55)), (6L, ("Fran", 50)) )) // 2. 构建边集合 val cntCall:RDD[Edge[Int]] = sc.parallelize(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) )) // 3. 构图 val graph:Graph[(String, Int), Int] = Graph(users, cntCall) /*****************图的属性**********************/ // 边数量 println(s"edgesNum: ${graph.numEdges}") // edgesNum: 8 // 顶点数量 println(s"vertexNum: ${graph.numVertices}") // vertexNum: 6 // 图的入度 graph.inDegrees.foreach(x => println(s"(vertexId, inDegreesNum)=${x.toString()}")) // (vertexId, inDegreesNum)=(1,2) // (vertexId, inDegreesNum)=(4,1) // (vertexId, inDegreesNum)=(3,1) // (vertexId, inDegreesNum)=(6,2) // (vertexId, inDegreesNum)=(2,2) // 图的出度 graph.outDegrees.foreach(x => println(s"(vertexId, outDegreesNum)=${x.toString()}")) // (vertexId, outDegreesNum)=(2,2) // (vertexId, outDegreesNum)=(4,1) // (vertexId, outDegreesNum)=(5,3) // (vertexId, outDegreesNum)=(3,2) // 图的度 graph.degrees.foreach(x => println(s"(vertexId, degreesNum)=${x.toString()}")) // (vertexId, degreesNum)=(4,2) // (vertexId, degreesNum)=(3,3) // (vertexId, degreesNum)=(6,2) // (vertexId, degreesNum)=(2,4) // (vertexId, degreesNum)=(1,2) // (vertexId, degreesNum)=(5,3) } } ```