当前位置:   article > 正文

头歌Spark GraphX—构建图及相关操作_第1关:graphx-构建图及相关基本操作

第1关:graphx-构建图及相关基本操作

第一关

  1. import org.apache.log4j.{Level, Logger}
  2. import org.apache.spark.graphx._
  3. import org.apache.spark.rdd.RDD
  4. import org.apache.spark.{SparkConf, SparkContext}
  5. object GraphX_Test_stu{
  6. def main(args:Array[String]): Unit ={
  7. //屏蔽日志
  8. Logger.getLogger("org.apache.spark").setLevel(Level.WARN)
  9. Logger.getLogger("org.eclipse.jetty.server").setLevel(Level.OFF)
  10. //设置运行环境
  11. val conf = new SparkConf().setAppName("SimpleGraph").setMaster("local")
  12. val sc = new SparkContext(conf)
  13. //设置顶点和边,注意顶点和边都是用元组定义的Array
  14. //顶点的数据类型是VD:(String,Int)
  15. val vertexArray = Array(
  16. (1L,("Bob",89)),
  17. (2L,("Sunny",70)),
  18. (3L,("Tony",99)),
  19. (4L,("Helen",58)),
  20. (5L,("John",55)),
  21. (6L,("Tom",83)),
  22. (7L,("Marry",94)),
  23. (8L,("Cook",76)),
  24. (9L,("Linda",84))
  25. )
  26. //边的数据类型ED:Int
  27. val edgeArray = Array(
  28. Edge(1L,2L,5),
  29. Edge(1L,3L,9),
  30. Edge(2L,4L,4),
  31. Edge(3L,4L,6),
  32. Edge(3L,6L,8),
  33. Edge(3L,7L,4),
  34. Edge(4L,5L,7),
  35. Edge(4L,8L,6),
  36. Edge(8L,3L,7),
  37. Edge(8L,7L,2),
  38. Edge(8L,9L,1)
  39. )
  40. //构造vertexRDD和edgeRDD
  41. val vertexRDD:RDD[(Long,(String,Int))] = sc.parallelize(vertexArray)
  42. val edgeRDD:RDD[Edge[Int]] = sc.parallelize(edgeArray)
  43. //构造Graph[VD,ED]
  44. val graph:Graph[(String,Int),Int] = Graph(vertexRDD, edgeRDD)
  45. //*********************图的属性
  46. //找出图中成绩大于60的顶点
  47. println("Find the vertices with scores greater than 60 in the graph")
  48. graph.vertices.filter{case (id,(name,grade)) => grade > 60}.collect.foreach{
  49. case (id,(name,grade)) => println(s"$name $grade")
  50. }
  51. println
  52. //边操作,找出图中边属性大于5的边
  53. println("Find the edge of the graph whose edge attribute is greater than 5")
  54. graph.edges.filter(e => e.attr > 5).collect.foreach(e => println(s"${e.srcId} to ${e.dstId} att ${e.attr}"))
  55. println
  56. //triplets操作.((srcId,srcAttr),(dstID,dstAttr),attr)
  57. //列出边属性>5的tripltes
  58. println("Find the tripltes with edge attributes greater than 5")
  59. for (triplet <- graph.triplets.filter(t => t.attr > 5).collect){
  60. println(s"${triplet.srcAttr._1} ${triplet.dstAttr._1}")
  61. }
  62. println
  63. //Degrees操作
  64. //找出图中最大的出度、入度、度数
  65. println("Find the maximum outDegrees, inDegrees, and Degrees in the graph")
  66. def max(a:(VertexId,Int),b:(VertexId,Int)):(VertexId,Int) = {
  67. if(a._2 > b._2) a else b
  68. }
  69. println("max of outDegrees" + graph.outDegrees.reduce(max) + " max of inDegrees" + graph.inDegrees.reduce(max) + " max of Degrees" + graph.degrees.reduce(max))
  70. //********************转换操作
  71. //顶点的转换操作,顶点成绩+10
  72. println("Vertex conversion operation vertex scores added 10")
  73. graph.mapVertices{ case (id, (name, age)) => (id, (name,age+10))}.vertices.collect.foreach(v => println(s"${v._2._1} is ${v._2._1}"))
  74. println
  75. //边的转换操作,边的属性
  76. println("Edge conversion operation multiplying the attribute of the edge by 2")
  77. graph.mapEdges(e => e.attr*2).edges.collect.foreach(e => println(s"${e.srcId} to ${e.dstId} att ${e.attr}"))
  78. println
  79. //********************结构操作
  80. //找出顶点成绩>60的子图
  81. println("Find subgraphs with vertex scores greater than 60")
  82. val subGraph = graph.subgraph(vpred = (id, vd) => vd._2 >= 60)
  83. //找出子图所有顶点
  84. println("Find all the vertices of the subgraph:")
  85. subGraph.vertices.collect.foreach(v => println(s"${v._2._1} is ${v._2._2}"))
  86. println
  87. //找出子图所有边
  88. println("Find all sides of the subgraph:")
  89. subGraph.edges.collect.foreach(e => println(s"${e.srcId} to ${e.dstId} att ${e.attr}"))
  90. println
  91. //********************结构操作
  92. //连接操作
  93. val inDegrees:VertexRDD[Int] = graph.inDegrees
  94. case class User(name:String,grade:Int,inDeg:Int,outDeg:Int)
  95. //创建一个新图,顶点VD的数据类型为User,并从graph做类型转换
  96. val initialUserGraph:Graph[User,Int] = graph.mapVertices{case (id,(name,grade)) => User(name,grade,0,0)}
  97. //initialUserGraph与inDegrees、outDegrees(RDD)进行连接
  98. //并修改initialUserGraph中inDeg值、outDeg值
  99. val userGraph = initialUserGraph.outerJoinVertices(initialUserGraph.inDegrees){
  100. case(id, u, inDegOpt) => User(u.name, u.grade, inDegOpt.getOrElse(0), u.outDeg)}.outerJoinVertices(initialUserGraph.outDegrees){
  101. case(id, u, outDegOpt) => User(u.name, u.grade, u.inDeg, outDegOpt.getOrElse(0))
  102. }
  103. //连接图的属性
  104. userGraph.vertices.collect.foreach(v => println(s"${v._2.name} inDeg: ${v._2.inDeg} outDeg:${v._2.outDeg}"))
  105. println
  106. //找出出度和入度相同的顶点
  107. println("Find the same vertex with the same degree of penetration")
  108. userGraph.vertices.filter{
  109. case (id,u) => u.inDeg == u.outDeg
  110. }.collect.foreach{
  111. case (id,property) => println(property.name)
  112. }
  113. println
  114. sc.stop()
  115. }
  116. }

第二关

  1. import org.apache.log4j.{Level,Logger}
  2. import org.apache.spark.{SparkContext,SparkConf}
  3. import org.apache.spark.graphx._
  4. import org.apache.spark.rdd.RDD
  5. object GraphX_Test_2_stu{
  6. def main(args:Array[String]): Unit ={
  7. //屏蔽日志
  8. Logger.getLogger("org.apache.spark").setLevel(Level.WARN)
  9. Logger.getLogger("org.eclipse.jetty.server").setLevel(Level.OFF)
  10. //设置运行环境
  11. val conf = new SparkConf().setAppName("SimpleGraph").setMaster("local")
  12. val sc = new SparkContext(conf)
  13. //设置顶点和边,注意顶点和边都是用元组定义的Array
  14. //顶点的数据类型是VD:(String,Int)
  15. val vertexArray = Array(
  16. (1L,("Bob",89)),
  17. (2L,("Sunny",70)),
  18. (3L,("Tony",99)),
  19. (4L,("Helen",58)),
  20. (5L,("John",55)),
  21. (6L,("Tom",83)),
  22. (7L,("Marry",94)),
  23. (8L,("Cook",76)),
  24. (9L,("Linda",84))
  25. )
  26. //边的数据类型ED:Int
  27. val edgeArray = Array(
  28. Edge(1L,2L,5),
  29. Edge(1L,3L,9),
  30. Edge(2L,4L,4),
  31. Edge(3L,4L,6),
  32. Edge(3L,6L,8),
  33. Edge(3L,7L,4),
  34. Edge(4L,5L,7),
  35. Edge(4L,8L,6),
  36. Edge(8L,3L,7),
  37. Edge(8L,7L,2),
  38. Edge(8L,9L,1)
  39. )
  40. //构造vertexRDD和edgeRDD
  41. val vertexRDD:RDD[(Long,(String,Int))] = sc.parallelize(vertexArray)
  42. val edgeRDD:RDD[Edge[Int]] = sc.parallelize(edgeArray)
  43. //构造Graph[VD,ED]
  44. val graph:Graph[(String,Int),Int] = Graph(vertexRDD, edgeRDD)
  45. //********************实用操作
  46. //找出顶点1到各顶点的最短距离
  47. println("Find the shortest distance from vertex 1 to each vertex")
  48. val sourceId:VertexId = 1L //定义远点
  49. val initialGraph = graph.mapVertices((id,_) => if (id == sourceId) 0.0 else Double.PositiveInfinity)
  50. val sssp = initialGraph.pregel(Double.PositiveInfinity)(
  51. (id,dist,newDist) => math.min(dist,newDist),
  52. triplet => {//计算权重
  53. if(triplet.srcAttr + triplet.attr < triplet.dstAttr){
  54. Iterator((triplet.dstId,triplet.srcAttr + triplet.attr))
  55. }else{
  56. Iterator.empty
  57. }
  58. },
  59. (a,b) => math.min(a,b)
  60. )
  61. println(sssp.vertices.collect.mkString("\n"))
  62. println
  63. def sendMsgFunc(edge:EdgeTriplet[Int, Int]) = {
  64. if(edge.srcAttr <= 0){
  65. if(edge.dstAttr <= 0){
  66. // 如果双方都小于0,则不发送信息
  67. Iterator.empty
  68. }else{
  69. // srcAttr小于0,dstAttr大于零,则将dstAttr-1后发送
  70. Iterator((edge.srcId, edge.dstAttr - 1))
  71. }
  72. }else{
  73. if(edge.dstAttr <= 0){
  74. // srcAttr大于0,dstAttr<0,则将srcAttr-1后发送
  75. Iterator((edge.dstId, edge.srcAttr - 1))
  76. }else{
  77. // 双方都大于零,则将属性-1后发送
  78. val toSrc = Iterator((edge.srcId, edge.dstAttr - 1))
  79. val toDst = Iterator((edge.dstId, edge.srcAttr - 1))
  80. toDst ++ toSrc
  81. }
  82. }
  83. }
  84. val friends = Pregel(
  85. graph.mapVertices((vid, value)=> if(vid == 1) 2 else -1),
  86. // 发送初始值
  87. -1,
  88. // 指定阶数
  89. 2,
  90. // 双方向发送
  91. EdgeDirection.Either
  92. )(
  93. // 将值设为大的一方
  94. vprog = (vid, attr, msg) => math.max(attr, msg),
  95. //
  96. sendMsgFunc,
  97. //
  98. (a, b) => math.max(a, b)
  99. ).subgraph(vpred = (vid, v) => v >= 0)
  100. println("Confirm Vertices of friends ")
  101. friends.vertices.collect.foreach(println(_))
  102. sc.stop()
  103. }
  104. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/666743
推荐阅读
相关标签
  

闽ICP备14008679号