Apache Spark 3.0 GraphX编程指南

 学习地址:https://spark.apache.org/docs/latest/graphx-programming-guide.html

目录

总览

入门

属性图

属性图示例

图运算符

运营商摘要列表

物业经营者

结构算子

加盟运营商

邻里聚集

汇总消息(a​​ggregateMessages)

Map Reduce三元组转换指南(旧版)

计算学位信息

收集邻居

缓存和取消缓存

Pregel API

图构建器

顶点和边缘RDD

顶点RDD

边缘RDD

优化表示

图算法

网页排名

连接的组件

三角计数

例子


GraphX

总览

GraphX是Spark中用于图形和图形并行计算的新组件。在较高的层次上,GraphX 通过引入新的Graph抽象来扩展Spark RDD:一个有向多重图,其属性附加到每个顶点和边上。为了支持图计算,GraphX公开了一组基本的操作符(例如,子图joinVertices和 aggregateMessages),以及所述的优化的变体预凝胶 API。此外,GraphX包括越来越多的图形算法和 构建器集合,以简化图形分析任务。

入门

首先,首先需要将Spark和GraphX导入项目,如下所示:

import org.apache.spark._
import org.apache.spark.graphx._
// To make some of the examples work we will also need RDD
import org.apache.spark.rdd.RDD

如果您不使用Spark Shell,则还需要一个SparkContext。要了解有关Spark入门的更多信息,请参考《Spark快速入门指南》

属性图

属性曲线图是一个有向多重图与连接到每个顶点和边缘的用户定义的对象。有向多重图是有向图,其中潜在的多个平行边共享相同的源和目标顶点。支持平行边的功能简化了在相同顶点之间可能存在多个关系(例如,同事和朋友)的建模场景。每个顶点均由唯一的 64位长标识符(VertexId)设置密钥 。GraphX对顶点标识符没有施加任何排序约束。同样,边具有相应的源和目标顶点标识符。

在顶点(VD)和边(ED)类型上对属性图进行了参数化。这些是分别与每个顶点和边关联的对象的类型。

当顶点和边类型是原始数据类型(例如int,double等)时,GraphX可以优化它们的表示形式,通过将它们存储在专用数组中来减少内存占用。

在某些情况下,可能希望在同一图形中具有具有不同属性类型的顶点。这可以通过继承来实现。例如,要将用户和产品建模为二部图,我们可以执行以下操作:

class VertexProperty()
case class UserProperty(val name: String) extends VertexProperty
case class ProductProperty(val name: String, val price: Double) extends VertexProperty
// The graph might then have the type:
var graph: Graph[VertexProperty, String] = null

像RDD一样,属性图是不可变的,分布式的和容错的。图的值或结构的更改是通过生成具有所需更改的新图来完成的。注意,原始图的实质部分(即不受影响的结构,属性和索引)在新图中被重用,从而降低了这种固有功能数据结构的成本。使用一系列顶点分区试探法在执行程序之间划分图。与RDD一样,发生故障时,可以在不同的计算机上重新创建图形的每个分区。

逻辑上,属性图对应于一对类型化集合(RDD),它们对每个顶点和边的属性进行编码。结果,图类包含访问图的顶点和边的成员:

class Graph[VD, ED] {
  val vertices: VertexRDD[VD]
  val edges: EdgeRDD[ED]
}

的类VertexRDD[VD]EdgeRDD[ED]延伸,并且被优化的版本RDD[(VertexId, VD)]RDD[Edge[ED]]分别。双方VertexRDD[VD]EdgeRDD[ED]提供围绕图形计算,并利用内部优化内置附加功能。我们将在有关顶点和边缘RDD的部分中更详细地讨论 VertexRDDVertexRDDEdgeRDDEdgeRDD API,但现在可以将它们简单地视为形式为和的RDD 。RDD[(VertexId, VD)]RDD[Edge[ED]]

属性图示例

假设我们要构造一个由GraphX项目中的各个协作者组成的属性图。顶点属性可能包含用户名和职业。我们可以用描述协作者之间关系的字符串注释边缘:

属性图

结果图将具有类型签名:

val userGraph: Graph[(String, String), String]

有多种方法可以从原始文件,RDD甚至是合成生成器构造属性图,有关这些图的详细信息,请参见图生成 。可能最通用的方法是使用 Graph对象。例如,以下代码从RDD集合构造一个图形:

// Assume the SparkContext has already been constructed
val sc: SparkContext
// Create an RDD for the vertices
val users: RDD[(VertexId, (String, String))] =
  sc.parallelize(Seq((3L, ("rxin", "student")), (7L, ("jgonzal", "postdoc")),
                       (5L, ("franklin", "prof")), (2L, ("istoica", "prof"))))
// Create an RDD for edges
val relationships: RDD[Edge[String]] =
  sc.parallelize(Seq(Edge(3L, 7L, "collab"),    Edge(5L, 3L, "advisor"),
                       Edge(2L, 5L, "colleague"), Edge(5L, 7L, "pi")))
// Define a default user in case there are relationship with missing user
val defaultUser = ("John Doe", "Missing")
// Build the initial Graph
val graph = Graph(users, relationships, defaultUser)

在上面的示例中,我们使用了Edgecase类。边缘具有srcId和,分别 dstId对应于源和目标顶点标识符。另外,Edge 该类具有attr存储edge属性的成员。

我们可以分别使用graph.vertices 和graph.edges成员将图解构为相应的顶点和边缘视图。

val graph: Graph[(String, String), String] // Constructed from above
// Count all users which are postdocs
graph.vertices.filter { case (id, (name, pos)) => pos == "postdoc" }.count
// Count all the edges where src > dst
graph.edges.filter(e => e.srcId > e.dstId).count

请注意,graph.vertices返回VertexRDD[(String, String)]扩展了的 RDD[(VertexId, (String, String))],因此我们使用scala case表达式解构元组。另一方面,graph.edges返回一个EdgeRDD包含Edge[String]对象。我们还可以使用case类类型构造函数,如下所示:

graph.edges.filter { case Edge(src, dst, prop) => src > dst }.count

除了属性图的顶点和边缘视图外,GraphX还公开了一个三元组视图。三元组视图在逻辑上连接顶点和边属性,从而产生一个 RDD[EdgeTriplet[VD, ED]]包含EdgeTriplet类的实例。可以用以下SQL表达式表示此 连接

SELECT src.id, dst.id, src.attr, e.attr, dst.attr
FROM edges AS e LEFT JOIN vertices AS src, vertices AS dst
ON e.srcId = src.Id AND e.dstId = dst.Id

或图形化为:

边缘三胞胎

EdgeTriplet类扩展Edge通过添加类srcAttr和 dstAttr分别包含源和目的地属性成员。我们可以使用图形的三元组视图来呈现描述用户之间关系的字符串集合。

val graph: Graph[(String, String), String] // Constructed from above
// Use the triplets view to create an RDD of facts.
val facts: RDD[String] =
  graph.triplets.map(triplet =>
    triplet.srcAttr._1 + " is the " + triplet.attr + " of " + triplet.dstAttr._1)
facts.collect.foreach(println(_))

图运算符

正如RDD具有,,和之类的基本运算一样map,属性图也具有一组基本运算符,这些运算符采用用户定义的函数并生成具有转换后的特性和结构的新图。在中定义了具有优化实现的核心运算符,并在中定义了表示为核心运算符组成的便捷运算符。但是,由于使用Scala隐式,in 中的运算符可以自动用作的成员。例如,我们可以通过以下方法计算每个顶点(在中定义)的度数:filterreduceByKeyGraphGraphOpsGraphOpsGraphGraphOps

val graph: Graph[(String, String), String]
// Use the implicit GraphOps.inDegrees operator
val inDegrees: VertexRDD[Int] = graph.inDegrees

区分核心图形操作的原因,GraphOps是将来能够支持不同的图形表示形式。每个图表示必须提供核心操作的实现,并重用中定义的许多有用的操作 GraphOps

运营商摘要列表

下面是在这两个定义的功能的快速摘要Graph和 GraphOps而是呈现为为简单起见图的成员。请注意,某些函数签名已得到简化(例如,删除了默认参数和类型约束),并删除了一些更高级的功能,因此请查阅API文档以获取正式的操作列表。

/** Summary of the functionality in the property graph */
class Graph[VD, ED] {
  // Information about the Graph ===================================================================
  val numEdges: Long
  val numVertices: Long
  val inDegrees: VertexRDD[Int]
  val outDegrees: VertexRDD[Int]
  val degrees: VertexRDD[Int]
  // Views of the graph as collections =============================================================
  val vertices: VertexRDD[VD]
  val edges: EdgeRDD[ED]
  val triplets: RDD[EdgeTriplet[VD, ED]]
  // Functions for caching graphs ==================================================================
  def persist(newLevel: StorageLevel = StorageLevel.MEMORY_ONLY): Graph[VD, ED]
  def cache(): Graph[VD, ED]
  def unpersistVertices(blocking: Boolean = false): Graph[VD, ED]
  // Change the partitioning heuristic  ============================================================
  def partitionBy(partitionStrategy: PartitionStrategy): Graph[VD, ED]
  // Transform vertex and edge attributes ==========================================================
  def mapVertices[VD2](map: (VertexId, VD) => VD2): Graph[VD2, ED]
  def mapEdges[ED2](map: Edge[ED] => ED2): Graph[VD, ED2]
  def mapEdges[ED2](map: (PartitionID, Iterator[Edge[ED]]) => Iterator[ED2]): Graph[VD, ED2]
  def mapTriplets[ED2](map: EdgeTriplet[VD, ED] => ED2): Graph[VD, ED2]
  def mapTriplets[ED2](map: (PartitionID, Iterator[EdgeTriplet[VD, ED]]) => Iterator[ED2])
    : Graph[VD, ED2]
  // Modify the graph structure ====================================================================
  def reverse: Graph[VD, ED]
  def subgraph(
      epred: EdgeTriplet[VD,ED] => Boolean = (x => true),
      vpred: (VertexId, VD) => Boolean = ((v, d) => true))
    : Graph[VD, ED]
  def mask[VD2, ED2](other: Graph[VD2, ED2]): Graph[VD, ED]
  def groupEdges(merge: (ED, ED) => ED): Graph[VD, ED]
  // Join RDDs with the graph ======================================================================
  def joinVertices[U](table: RDD[(VertexId, U)])(mapFunc: (VertexId, VD, U) => VD): Graph[VD, ED]
  def outerJoinVertices[U, VD2](other: RDD[(VertexId, U)])
      (mapFunc: (VertexId, VD, Option[U]) => VD2)
    : Graph[VD2, ED]
  // Aggregate information about adjacent triplets =================================================
  def collectNeighborIds(edgeDirection: EdgeDirection): VertexRDD[Array[VertexId]]
  def collectNeighbors(edgeDirection: EdgeDirection): VertexRDD[Array[(VertexId, VD)]]
  def aggregateMessages[Msg: ClassTag](
      sendMsg: EdgeContext[VD, ED, Msg] => Unit,
      mergeMsg: (Msg, Msg) => Msg,
      tripletFields: TripletFields = TripletFields.All)
    : VertexRDD[A]
  // Iterative graph-parallel computation ==========================================================
  def pregel[A](initialMsg: A, maxIterations: Int, activeDirection: EdgeDirection)(
      vprog: (VertexId, VD, A) => VD,
      sendMsg: EdgeTriplet[VD, ED] => Iterator[(VertexId, A)],
      mergeMsg: (A, A) => A)
    : Graph[VD, ED]
  // Basic graph algorithms ========================================================================
  def pageRank(tol: Double, resetProb: Double = 0.15): Graph[Double, Double]
  def connectedComponents(): Graph[VertexId, ED]
  def triangleCount(): Graph[Int, ED]
  def stronglyConnectedComponents(numIter: Int): Graph[VertexId, ED]
}

物业经营者

与RDD map运算符一样,属性图包含以下内容:

class Graph[VD, ED] {
  def mapVertices[VD2](map: (VertexId, VD) => VD2): Graph[VD2, ED]
  def mapEdges[ED2](map: Edge[ED] => ED2): Graph[VD, ED2]
  def mapTriplets[ED2](map: EdgeTriplet[VD, ED] => ED2): Graph[VD, ED2]
}

这些运算符中的每一个都会产生一个新图,其顶点或边线属性由用户定义的map函数修改。

请注意,在每种情况下,图结构均不受影响。这是这些运算符的关键功能,它允许生成的图重用原始图的结构索引。以下代码段在逻辑上是等效的,但第一个代码段不会保留结构索引,也不会从GraphX系统优化中受益:

val newVertices = graph.vertices.map { case (id, attr) => (id, mapUdf(id, attr)) }
val newGraph = Graph(newVertices, graph.edges)

而是使用mapVertices保留索引:

val newGraph = graph.mapVertices((id, attr) => mapUdf(id, attr))

这些运算符通常用于为特定计算初始化图或投影出不必要的属性。例如,给定一个以out度作为顶点属性的图(我们稍后将描述如何构造这种图),我们将其初始化为PageRank:

// Given a graph where the vertex property is the out degree
val inputGraph: Graph[Int, String] =
  graph.outerJoinVertices(graph.outDegrees)((vid, _, degOpt) => degOpt.getOrElse(0))
// Construct a graph where each edge contains the weight
// and each vertex is the initial PageRank
val outputGraph: Graph[Double, Double] =
  inputGraph.mapTriplets(triplet => 1.0 / triplet.srcAttr).mapVertices((id, _) => 1.0)

结构算子

目前,GraphX仅支持一组简单的常用结构运算符,我们希望将来会增加更多。以下是基本结构运算符的列表。

class Graph[VD, ED] {
  def reverse: Graph[VD, ED]
  def subgraph(epred: EdgeTriplet[VD,ED] => Boolean,
               vpred: (VertexId, VD) => Boolean): Graph[VD, ED]
  def mask[VD2, ED2](other: Graph[VD2, ED2]): Graph[VD, ED]
  def groupEdges(merge: (ED, ED) => ED): Graph[VD,ED]
}

reverse运营商将返回逆转的所有边缘方向上的新图。例如,在尝试计算逆PageRank时,这将很有用。由于反向操作不会修改顶点或边的属性或更改边的数量,因此可以有效地实现它,而无需移动或复制数据。

subgraph操作者需要的顶点和边缘的谓词,并返回包含只有满足顶点谓词(评估为真)的顶点和满足边缘谓词边缘的曲线和满足顶点谓词连接顶点subgraph 可以在多种情况下使用该运算符,以将图形限制在感兴趣的顶点和边缘或消除断开的链接。例如,在下面的代码中,我们删除了断开的链接:

// Create an RDD for the vertices
val users: RDD[(VertexId, (String, String))] =
  sc.parallelize(Seq((3L, ("rxin", "student")), (7L, ("jgonzal", "postdoc")),
                       (5L, ("franklin", "prof")), (2L, ("istoica", "prof")),
                       (4L, ("peter", "student"))))
// Create an RDD for edges
val relationships: RDD[Edge[String]] =
  sc.parallelize(Seq(Edge(3L, 7L, "collab"),    Edge(5L, 3L, "advisor"),
                       Edge(2L, 5L, "colleague"), Edge(5L, 7L, "pi"),
                       Edge(4L, 0L, "student"),   Edge(5L, 0L, "colleague")))
// Define a default user in case there are relationship with missing user
val defaultUser = ("John Doe", "Missing")
// Build the initial Graph
val graph = Graph(users, relationships, defaultUser)
// Notice that there is a user 0 (for which we have no information) connected to users
// 4 (peter) and 5 (franklin).
graph.triplets.map(
  triplet => triplet.srcAttr._1 + " is the " + triplet.attr + " of " + triplet.dstAttr._1
).collect.foreach(println(_))
// Remove missing vertices as well as the edges to connected to them
val validGraph = graph.subgraph(vpred = (id, attr) => attr._2 != "Missing")
// The valid subgraph will disconnect users 4 and 5 by removing user 0
validGraph.vertices.collect.foreach(println(_))
validGraph.triplets.map(
  triplet => triplet.srcAttr._1 + " is the " + triplet.attr + " of " + triplet.dstAttr._1
).collect.foreach(println(_))

注意,在以上示例中,仅提供了顶点谓词。的subgraph操作者默认为true如果不设置顶点或边谓词。

mask操作者通过返回包含该顶点和边,它们也在输入图形中发现的曲线构造一个子图。可以与subgraph运算符结合使用, 以基于另一个相关图形中的属性来限制图形。例如,我们可能会使用缺少顶点的图来运行连接的组件,然后将答案限制为有效的子图。

// Run Connected Components
val ccGraph = graph.connectedComponents() // No longer contains missing field
// Remove missing vertices as well as the edges to connected to them
val validGraph = graph.subgraph(vpred = (id, attr) => attr._2 != "Missing")
// Restrict the answer to the valid subgraph
val validCCGraph = ccGraph.mask(validGraph)

groupEdges操作者合并平行边在多重图(即,顶点对之间的重复边缘)。在许多数值应用中,可以将平行边添加 (合并了它们的权重)到单个边中,从而减小了图形的大小。

加盟运营商

在许多情况下,有必要将外部集合(RDD)中的数据与图形连接起来。例如,我们可能有想要与现有图形合并的额外用户属性,或者可能希望将顶点属性从一个图拉到另一个图。这些任务可以使用联接运算符来完成。下面我们列出了关键的联接运算符:

class Graph[VD, ED] {
  def joinVertices[U](table: RDD[(VertexId, U)])(map: (VertexId, VD, U) => VD)
    : Graph[VD, ED]
  def outerJoinVertices[U, VD2](table: RDD[(VertexId, U)])(map: (VertexId, VD, Option[U]) => VD2)
    : Graph[VD2, ED]
}

joinVertices运算符连接与输入RDD顶点并返回与通过应用用户定义获得的顶点属性的新图形map函数到连接的顶点的结果。RDD中没有匹配值的顶点保留其原始值。

请注意,如果RDD对于给定的顶点包含多个值,则只会使用一个。因此,建议使用以下命令使输入RDD唯一,这也将对结果值进行预索引,以大大加快后续连接的速度。

val nonUniqueCosts: RDD[(VertexId, Double)]
val uniqueCosts: VertexRDD[Double] =
  graph.vertices.aggregateUsingIndex(nonUnique, (a,b) => a + b)
val joinedGraph = graph.joinVertices(uniqueCosts)(
  (id, oldCost, extraCost) => oldCost + extraCost)

除了将用户定义的函数应用于所有顶点并可以更改顶点属性类型外,其他outerJoinVertices行为与常规行为类似。由于并非所有顶点在输入RDD中都可能具有匹配值,因此该 函数采用一种类型。例如,我们可以通过使用初始化顶点属性来为PageRank设置图形。joinVerticesmapmapOptionoutDegree

val outDegrees: VertexRDD[Int] = graph.outDegrees
val degreeGraph = graph.outerJoinVertices(outDegrees) { (id, oldAttr, outDegOpt) =>
  outDegOpt match {
    case Some(outDeg) => outDeg
    case None => 0 // No outDegree means zero outDegree
  }
}

您可能已经注意到f(a)(b)以上示例中使用的多个参数列表(例如)咖喱函数模式。虽然我们可以同样地写f(a)(b)f(a,b)但这意味着对类型的推断b将不依赖a。结果,用户将需要为用户定义的函数提供类型注释:

val joinedGraph = graph.joinVertices(uniqueCosts,
  (id: VertexId, oldCost: Double, extraCost: Double) => oldCost + extraCost)
 

邻里聚集

许多图形分析任务中的关键步骤是聚合有关每个顶点邻域的信息。例如,我们可能想知道每个用户拥有的关注者数量或每个用户的关注者平均年龄。许多迭代图算法(例如,PageRank,最短路径和连接的组件)反复聚合相邻顶点的属性(例如,当前的PageRank值,到源的最短路径以及最小的可到达顶点ID)。

为了提高性能,主要聚合运算符从更改 graph.mapReduceTripletsgraph.AggregateMessages。尽管API的更改相对较小,但我们在下面提供了过渡指南。

汇总消息(a​​ggregateMessages)

GraphX中的核心聚合操作为aggregateMessages。该运算符将用户定义的sendMsg函数应用于图形中的每个边三元组,然后使用该mergeMsg函数在其目标顶点处聚合这些消息。

class Graph[VD, ED] {
  def aggregateMessages[Msg: ClassTag](
      sendMsg: EdgeContext[VD, ED, Msg] => Unit,
      mergeMsg: (Msg, Msg) => Msg,
      tripletFields: TripletFields = TripletFields.All)
    : VertexRDD[Msg]
}

用户定义的sendMsg函数采用EdgeContext,将公开源和目标属性以及边缘属性和函数(sendToSrcsendToDst),以将消息发送到源和目标属性。可以认为是 map-reduce中sendMsgmap函数。用户定义的mergeMsg函数接受两条发往同一顶点的消息,并产生一条消息。可以认为是map-reduce中mergeMsgreduce函数。的 aggregateMessages操作者返回一个VertexRDD[Msg] 包含该聚合消息(类型的Msg)发往每个顶点。未收到消息的顶点不包含在返回的VertexRDDVertexRDD中

另外,aggregateMessages采用一个可选参数 tripletsFields,该参数指示在中访问了哪些数据EdgeContext (即,源顶点属性,而不是目标顶点属性)。的可能选项在tripletsFields中定义,TripletFields默认值为TripletFields.All,指示用户定义的sendMsg函数可以访问中的任何字段EdgeContext。该tripletFields参数可用于通知GraphX仅需要的一部分, EdgeContext从而允许GraphX选择优化的联接策略。例如,如果我们正在计算每个用户的关注者的平均年龄,则仅需要源字段,因此我们可以TripletFields.Src用来表明我们仅需要源字段

在GraphX的早期版本中,我们使用字节码检查来推断, TripletFields但是我们发现字节码检查有些不可靠,而是选择了更明确的用户控制。

在以下示例中,我们使用aggregateMessages运算符来计算每个用户的高级追随者的平均年龄。

import org.apache.spark.graphx.{Graph, VertexRDD}
import org.apache.spark.graphx.util.GraphGenerators

// Create a graph with "age" as the vertex property.
// Here we use a random graph for simplicity.
val graph: Graph[Double, Int] =
  GraphGenerators.logNormalGraph(sc, numVertices = 100).mapVertices( (id, _) => id.toDouble )
// Compute the number of older followers and their total age
val olderFollowers: VertexRDD[(Int, Double)] = graph.aggregateMessages[(Int, Double)](
  triplet => { // Map Function
    if (triplet.srcAttr > triplet.dstAttr) {
      // Send message to destination vertex containing counter and age
      triplet.sendToDst((1, triplet.srcAttr))
    }
  },
  // Add counter and age
  (a, b) => (a._1 + b._1, a._2 + b._2) // Reduce Function
)
// Divide total age by number of older followers to get average age of older followers
val avgAgeOfOlderFollowers: VertexRDD[Double] =
  olderFollowers.mapValues( (id, value) =>
    value match { case (count, totalAge) => totalAge / count } )
// Display the results
avgAgeOfOlderFollowers.collect.foreach(println(_))
在Spark存储库中的“ examples / src / main / scala / org / apache / spark / examples / graphx / AggregateMessagesExample.scala”中找到完整的示例代码。

aggregateMessages当消息(和消息的总和)大小固定(例如,浮点数和加法而不是列表和串联)时,该操作将以最佳方式执行。

Map Reduce三元组转换指南(旧版)

在GraphX的早期版本中,邻域聚合是使用mapReduceTriplets运算符完成的 :

class Graph[VD, ED] {
  def mapReduceTriplets[Msg](
      map: EdgeTriplet[VD, ED] => Iterator[(VertexId, Msg)],
      reduce: (Msg, Msg) => Msg)
    : VertexRDD[Msg]
}

mapReduceTriplets操作者需要被施加到每个三联体,并且可以产生用户定义的映射函数的消息,其是使用用户定义的汇总的 reduce功能。但是,我们发现返回的迭代器的用户很昂贵,并且它抑制了我们应用其他优化功能的能力(例如,局部顶点重新编号)。在aggregateMessages我们介绍的EdgeContext中,它公开了三元组字段,并且还具有将消息显式发送到源和目标顶点的功能。此外,我们删除了字节码检查,而是要求用户指出三元组中实际需要的字段。

以下代码块使用mapReduceTriplets

val graph: Graph[Int, Float] = ...
def msgFun(triplet: Triplet[Int, Float]): Iterator[(Int, String)] = {
  Iterator((triplet.dstId, "Hi"))
}
def reduceFun(a: String, b: String): String = a + " " + b
val result = graph.mapReduceTriplets[String](msgFun, reduceFun)

可以重写aggregateMessages为:

val graph: Graph[Int, Float] = ...
def msgFun(triplet: EdgeContext[Int, Float, String]) {
  triplet.sendToDst("Hi")
}
def reduceFun(a: String, b: String): String = a + " " + b
val result = graph.aggregateMessages[String](msgFun, reduceFun)

计算学位信息

常见的聚合任务是计算每个顶点的程度:与每个顶点相邻的边数。在有向图的上下文中,通常需要知道每个顶点的入度,出度和总度。本 GraphOps类包含运营商计算度数每个顶点的集合。例如,在下面的示例中,我们计算最大进度,出度和总度数:

// Define a reduce operation to compute the highest degree vertex
def max(a: (VertexId, Int), b: (VertexId, Int)): (VertexId, Int) = {
  if (a._2 > b._2) a else b
}
// Compute the max degrees
val maxInDegree: (VertexId, Int)  = graph.inDegrees.reduce(max)
val maxOutDegree: (VertexId, Int) = graph.outDegrees.reduce(max)
val maxDegrees: (VertexId, Int)   = graph.degrees.reduce(max)

收集邻居

在某些情况下,通过收集每个顶点处的相邻顶点及其属性来表达计算可能会更容易。使用collectNeighborIdscollectNeighbors运算符可以轻松完成 此 操作。

class GraphOps[VD, ED] {
  def collectNeighborIds(edgeDirection: EdgeDirection): VertexRDD[Array[VertexId]]
  def collectNeighbors(edgeDirection: EdgeDirection): VertexRDD[ Array[(VertexId, VD)] ]
}

这些运营商可能会非常昂贵,因为他们复制信息并需要大量沟通。如果可能,请尝试aggregateMessages 直接使用运算符表示相同的计算 。

缓存和取消缓存

在Spark中,默认情况下RDD不保留在内存中。为避免重新计算,在多次使用它们时必须将它们显式缓存(请参见《Spark编程指南》)。GraphX中的图形行为相同。多次使用图形时,请确保先调用Graph.cache()它。

在迭代计算中,为了获得最佳性能,也可能需要取消缓存。默认情况下,缓存的RDD和图形将保留在内存中,直到内存压力迫使它们按LRU顺序逐出为止。对于迭代计算,先前迭代的中间结果将填满缓存。尽管它们最终将被驱逐,但存储在内存中的不必要数据将减慢垃圾回收速度。一旦不再需要中间结果,则将其取消缓存将更加有效。这涉及在每次迭代中实现(缓存和强制执行)图或RDD,取消缓存所有其他数据集,并且仅在以后的迭代中使用实现的数据集。但是,由于图是由多个RDD组成的,因此很难正确地取消持久保留它们。对于迭代计算,我们建议使用Pregel API,它可以正确地保留中间结果。

Pregel API

图是固有的递归数据结构,因为顶点的属性取决于其邻居的属性,而顶点的属性又取决于邻居的属性。结果,许多重要的图算法迭代地重新计算每个顶点的属性,直到达到定点条件为止。已经提出了一系列图并行抽象来表达这些迭代算法。GraphX公开了Pregel API的变体。

在较高层次上,GraphX中的Pregel运算符是受图拓扑约束的批量同步并行消息传递抽象 。Pregel运算符在一系列超级步骤中执行,在这些步骤中,顶点从上一个超级步骤接收入站消息的总和,计算顶点属性的新值,然后在下一个超级步骤中将消息发送到相邻的顶点。与Pregel不同,消息是根据边缘三元组并行计算的,并且消息计算可以访问源顶点和目标顶点属性。在超级步骤中会跳过未收到消息的顶点。当没有消息剩余时,Pregel运算符终止迭代并返回最终图形。

注意,与更标准的Pregel实现不同,GraphX中的顶点只能将消息发送到相邻的顶点,并且使用用户定义的消息传递功能并行完成消息的构造。这些限制允许在GraphX中进行其他优化。

以下是Pregel运算符的类型签名 及其实现的草图(注意:为避免由于长的血统链而引起的stackOverflowError,pregel通过将“ spark.graphx.pregel.checkpointInterval”设置为a)来定期支持检查点图和消息。正数,例如10。并使用SparkContext.setCheckpointDir(directory:String))设置检查点目录:

class GraphOps[VD, ED] {
  def pregel[A]
      (initialMsg: A,
       maxIter: Int = Int.MaxValue,
       activeDir: EdgeDirection = EdgeDirection.Out)
      (vprog: (VertexId, VD, A) => VD,
       sendMsg: EdgeTriplet[VD, ED] => Iterator[(VertexId, A)],
       mergeMsg: (A, A) => A)
    : Graph[VD, ED] = {
    // Receive the initial message at each vertex
    var g = mapVertices( (vid, vdata) => vprog(vid, vdata, initialMsg) ).cache()

    // compute the messages
    var messages = GraphXUtils.mapReduceTriplets(g, sendMsg, mergeMsg)
    var activeMessages = messages.count()
    // Loop until no messages remain or maxIterations is achieved
    var i = 0
    while (activeMessages > 0 && i < maxIterations) {
      // Receive the messages and update the vertices.
      g = g.joinVertices(messages)(vprog).cache()
      val oldMessages = messages
      // Send new messages, skipping edges where neither side received a message. We must cache
      // messages so it can be materialized on the next line, allowing us to uncache the previous
      // iteration.
      messages = GraphXUtils.mapReduceTriplets(
        g, sendMsg, mergeMsg, Some((oldMessages, activeDirection))).cache()
      activeMessages = messages.count()
      i += 1
    }
    g
  }
}

请注意,Pregel使用了两个参数列表(即graph.pregel(list1)(list2))。第一个参数列表包含配置参数,包括初始消息,最大迭代次数以及发送消息的边缘方向(默认情况下沿边缘)。第二个参数列表包含用户定义的函数,这些函数用于接收消息(顶点程序 vprog),计算消息(sendMsg)以及组合消息mergeMsg

在以下示例中,我们可以使用Pregel运算符来表示诸如单个源最短路径之类的计算。

import org.apache.spark.graphx.{Graph, VertexId}
import org.apache.spark.graphx.util.GraphGenerators

// A graph with edge attributes containing distances
val graph: Graph[Long, Double] =
  GraphGenerators.logNormalGraph(sc, numVertices = 100).mapEdges(e => e.attr.toDouble)
val sourceId: VertexId = 42 // The ultimate source
// Initialize the graph such that all vertices except the root have distance infinity.
val initialGraph = graph.mapVertices((id, _) =>
    if (id == sourceId) 0.0 else Double.PositiveInfinity)
val sssp = initialGraph.pregel(Double.PositiveInfinity)(
  (id, dist, newDist) => math.min(dist, newDist), // Vertex Program
  triplet => {  // Send Message
    if (triplet.srcAttr + triplet.attr < triplet.dstAttr) {
      Iterator((triplet.dstId, triplet.srcAttr + triplet.attr))
    } else {
      Iterator.empty
    }
  },
  (a, b) => math.min(a, b) // Merge Message
)
println(sssp.vertices.collect.mkString("\n"))
在Spark存储库中的“ examples / src / main / scala / org / apache / spark / examples / graphx / SSSPExample.scala”中找到完整的示例代码。

图构建器

GraphX提供了几种从RDD或磁盘上的顶点和边的集合构建图形的方法。默认情况下,没有图构建器会重新划分图的边缘;相反,边缘保留在默认分区中(例如HDFS中的原始块)。Graph.groupEdges要求对图进行重新分区,因为它假定相同的边将在同一分区上并置,因此您必须在调用Graph.partitionBy之前先进行调用groupEdges

object GraphLoader {
  def edgeListFile(
      sc: SparkContext,
      path: String,
      canonicalOrientation: Boolean = false,
      minEdgePartitions: Int = 1)
    : Graph[Int, Int]
}

GraphLoader.edgeListFile提供了一种从磁盘上的边缘列表加载图形的方法。它解析以下形式的(源顶点ID,目标顶点ID)对的邻接表,并跳过以以下内容开头的注释行#

# This is a comment
2 1
4 1
1 2

Graph从指定的边创建一个,自动创建边提到的任何顶点。所有顶点和边属性默认为1。该canonicalOrientation参数允许沿正方向(srcId < dstId)重新定向边,这是所连接的组件算法所必需的。该minEdgePartitions参数指定要生成的边缘分区的最小数量。例如,如果HDFS文件具有更多块,则边缘分区可能会比指定的更多。

object Graph {
  def apply[VD, ED](
      vertices: RDD[(VertexId, VD)],
      edges: RDD[Edge[ED]],
      defaultVertexAttr: VD = null)
    : Graph[VD, ED]

  def fromEdges[VD, ED](
      edges: RDD[Edge[ED]],
      defaultValue: VD): Graph[VD, ED]

  def fromEdgeTuples[VD](
      rawEdges: RDD[(VertexId, VertexId)],
      defaultValue: VD,
      uniqueEdges: Option[PartitionStrategy] = None): Graph[VD, Int]

}

Graph.apply允许根据顶点和边的RDD创建图形。任意选取重复的顶点,并在边缘RDD中找到的顶点(而不是顶点RDD)指定为默认属性。

Graph.fromEdges 允许仅从边缘的RDD创建图形,自动创建边缘提及的任何顶点,并为其指定默认值。

Graph.fromEdgeTuples允许仅从边缘元组的RDD创建图形,为边缘分配值1,并自动创建Edge提及的任何顶点并将其指定为默认值。它还支持对边缘进行重复数据删除;要进行重复数据删除,请传递SomePartitionStrategy作为uniqueEdges参数(例如uniqueEdges = Some(PartitionStrategy.RandomVertexCut))。必须使用分区策略才能将相同边缘并置在同一分区上,以便可以对它们进行重复数据删除。

顶点和边缘RDD

GraphX公开RDD存储在图中的顶点和边的视图。但是,由于GraphX在优化的数据结构中维护了顶点和边,并且这些数据结构提供了其他功能,因此分别将顶点和边作为VertexRDDVertexRDDEdgeRDDEdgeRDD返回 。在本节中,我们将介绍这些类型中的一些其他有用功能。请注意,这只是一个不完整的列表,请参阅API文档以获取正式的操作列表。

顶点RDD

VertexRDD[A]扩展RDD[(VertexId, A)]并增加了额外的限制,每个 VertexId只发生一次。此外,VertexRDD[A]表示一顶点,每个顶点的类型属性为A。在内部,这是通过将顶点属性存储在可重用的哈希映射数据结构中来实现的。因此,如果两个VertexRDDs是从相同的基本 VertexRDDVertexRDD派生的(例如by filtermapValues),则可以在恒定时间内将它们连接在一起,而无需进行哈希评估。为了利用此索引数据结构,VertexRDDVertexRDD公开了以下附加功能:

class VertexRDD[VD] extends RDD[(VertexId, VD)] {
  // Filter the vertex set but preserves the internal index
  def filter(pred: Tuple2[VertexId, VD] => Boolean): VertexRDD[VD]
  // Transform the values without changing the ids (preserves the internal index)
  def mapValues[VD2](map: VD => VD2): VertexRDD[VD2]
  def mapValues[VD2](map: (VertexId, VD) => VD2): VertexRDD[VD2]
  // Show only vertices unique to this set based on their VertexId's
  def minus(other: RDD[(VertexId, VD)])
  // Remove vertices from this set that appear in the other set
  def diff(other: VertexRDD[VD]): VertexRDD[VD]
  // Join operators that take advantage of the internal indexing to accelerate joins (substantially)
  def leftJoin[VD2, VD3](other: RDD[(VertexId, VD2)])(f: (VertexId, VD, Option[VD2]) => VD3): VertexRDD[VD3]
  def innerJoin[U, VD2](other: RDD[(VertexId, U)])(f: (VertexId, VD, U) => VD2): VertexRDD[VD2]
  // Use the index on this RDD to accelerate a `reduceByKey` operation on the input RDD.
  def aggregateUsingIndex[VD2](other: RDD[(VertexId, VD2)], reduceFunc: (VD2, VD2) => VD2): VertexRDD[VD2]
}

注意,例如,filter运算符如何返回VertexRDDVertexRDD。过滤器实际上是使用来实现的,BitSet从而重用索引并保留与其他VertexRDDs 快速连接的能力。同样,mapValues运算符不允许map功能更改,VertexId从而使相同的HashMap数据结构可以重用。无论是 leftJoininnerJoin能够连接两个时识别VertexRDD来自同一来源的小号 HashMap和落实线性扫描,而不是昂贵的点查找的加入。

aggregateUsingIndex运算符对于从VertexRDDNET高效构建新的VertexRDD很有用 RDD[(VertexId, A)]。从概念上讲,如果我构建VertexRDD[B]了一组顶点, 这是某些顶点的超集RDD[(VertexId, A)]则可以重用索引进行聚合,然后再对进行索引RDD[(VertexId, A)]。例如:

val setA: VertexRDD[Int] = VertexRDD(sc.parallelize(0L until 100L).map(id => (id, 1)))
val rddB: RDD[(VertexId, Double)] = sc.parallelize(0L until 100L).flatMap(id => List((id, 1.0), (id, 2.0)))
// There should be 200 entries in rddB
rddB.count
val setB: VertexRDD[Double] = setA.aggregateUsingIndex(rddB, _ + _)
// There should be 100 entries in setB
setB.count
// Joining A and B should now be fast!
val setC: VertexRDD[Double] = setA.innerJoin(setB)((id, a, b) => a + b)

边缘RDD

EdgeRDD[ED],其延伸RDD[Edge[ED]]组织在块的边缘在使用中定义的各种分区策略的一个分区PartitionStrategy。在每个分区内,边缘属性和邻接结构分别存储,从而在更改属性值时最大程度地重用。

EdgeRDDEdgeRDD公开的三个附加功能是:

// Transform the edge attributes while preserving the structure
def mapValues[ED2](f: Edge[ED] => ED2): EdgeRDD[ED2]
// Reverse the edges reusing both attributes and structure
def reverse: EdgeRDD[ED]
// Join two `EdgeRDD`s partitioned using the same partitioning strategy.
def innerJoin[ED2, ED3](other: EdgeRDD[ED2])(f: (VertexId, VertexId, ED, ED2) => ED3): EdgeRDD[ED3]

在大多数应用程序中,我们发现EdgeRDDEdgeRDD上的操作是通过图形运算符完成的,或者依赖于基RDD类中定义的操作。

优化表示

虽然在GraphX表示形式的分布式图形中使用的优化的详细描述超出了本指南的范围,但是一些高级的了解可能有助于可伸缩算法的设计以及API的最佳使用。GraphX采用顶点切割方法进行分布式图形分区:

边切割与顶点切割

GraphX不会沿边缘划分图,而是沿顶点划分图,这可以减少通信和存储开销。从逻辑上讲,这对应于为机器分配边并允许顶点跨越多台机器。分配边的确切方法取决于,PartitionStrategy并且对各种启发式方法有一些折衷。用户可以通过用Graph.partitionBy运算符重新划分图来在不同策略之间进行选择。默认的分区策略是使用图形构造中提供的边的初始分区。但是,用户可以轻松切换到GraphX中包含的2D分区或其他启发式方法。

RDD图形表示

 

一旦对边缘进行了划分,高效图形并行计算的关键挑战就是有效地将顶点属性与边缘连接起来。由于现实世界中的图通常具有比顶点更多的边,因此我们将顶点属性移到边。由于并非所有分区都包含与所有顶点相邻的边,因此我们在内部维护一个路由表,该路由表在实现诸如triplets和的 操作所需的连接时,标识在哪里广播顶点aggregateMessages

图算法

GraphX包含一组图形算法,以简化分析任务。这些算法包含在org.apache.spark.graphx.lib软件包中,可以作为方法Graph通过via 直接访问GraphOps。本节介绍了算法及其使用方法。

网页排名

的PageRank测量在图中每个顶点的重要性,假设从边缘ùv表示的认可v通过的重要性ü。例如,如果一个Twitter用户被许多其他用户关注,则该用户的排名将很高。

GraphX带有PageRank的静态和动态实现,作为PageRank对象上的方法。静态PageRank运行固定的迭代次数,而动态PageRank运行直到排名收敛(即,停止变化超过指定的公差)。GraphOps允许直接将这些算法作为方法调用Graph

GraphX还包括一个示例社交网络数据集,可在其上运行PageRank。给出了一组用户data/graphx/users.txt,并且给出了一组用户之间的关系data/graphx/followers.txt。我们计算每个用户的PageRank如下:

import org.apache.spark.graphx.GraphLoader

// Load the edges as a graph
val graph = GraphLoader.edgeListFile(sc, "data/graphx/followers.txt")
// Run PageRank
val ranks = graph.pageRank(0.0001).vertices
// Join the ranks with the usernames
val users = sc.textFile("data/graphx/users.txt").map { line =>
  val fields = line.split(",")
  (fields(0).toLong, fields(1))
}
val ranksByUsername = users.join(ranks).map {
  case (id, (username, rank)) => (username, rank)
}
// Print the result
println(ranksByUsername.collect().mkString("\n"))
在Spark存储库中的“ examples / src / main / scala / org / apache / spark / examples / graphx / PageRankExample.scala”中找到完整的示例代码。

连接的组件

连通组件算法使用其编号最小的顶点的ID标记图的每个连通组件。例如,在社交网络中,连接的组件可以近似群集。GraphX包含在该算法的实现ConnectedComponents目的,并且我们计算从所述示例性社交网络数据集的连通分量的PageRank部分如下:

import org.apache.spark.graphx.GraphLoader

// Load the graph as in the PageRank example
val graph = GraphLoader.edgeListFile(sc, "data/graphx/followers.txt")
// Find the connected components
val cc = graph.connectedComponents().vertices
// Join the connected components with the usernames
val users = sc.textFile("data/graphx/users.txt").map { line =>
  val fields = line.split(",")
  (fields(0).toLong, fields(1))
}
val ccByUsername = users.join(cc).map {
  case (id, (username, cc)) => (username, cc)
}
// Print the result
println(ccByUsername.collect().mkString("\n"))
在Spark存储库中的“ examples / src / main / scala / org / apache / spark / examples / graphx / ConnectedComponentsExample.scala”中找到完整的示例代码。

三角计数

当顶点有两个相邻的顶点且在它们之间有一条边时,该顶点是三角形的一部分。GraphX在TriangleCount对象中实现三角形计数算法,该算法确定通过每个顶点的三角形的数量,从而提供聚类的度量。我们从PageRank部分计算社交网络数据集的三角形计数。请注意,这TriangleCount要求边缘必须符合规范的方向(srcId < dstId),并且必须使用来对图形进行分区Graph.partitionBy

import org.apache.spark.graphx.{GraphLoader, PartitionStrategy}

// Load the edges in canonical order and partition the graph for triangle count
val graph = GraphLoader.edgeListFile(sc, "data/graphx/followers.txt", true)
  .partitionBy(PartitionStrategy.RandomVertexCut)
// Find the triangle count for each vertex
val triCounts = graph.triangleCount().vertices
// Join the triangle counts with the usernames
val users = sc.textFile("data/graphx/users.txt").map { line =>
  val fields = line.split(",")
  (fields(0).toLong, fields(1))
}
val triCountByUsername = users.join(triCounts).map { case (id, (username, tc)) =>
  (username, tc)
}
// Print the result
println(triCountByUsername.collect().mkString("\n"))
在Spark存储库中的“ examples / src / main / scala / org / apache / spark / examples / graphx / TriangleCountingExample.scala”中找到完整的示例代码。

例子

假设我想从一些文本文件构建图形,将图形限制在重要的关系和用户上,在子图形上运行page-rank,然后最后返回与顶级用户相关联的属性。我可以使用GraphX在几行中完成所有这些操作:

import org.apache.spark.graphx.GraphLoader

// Load my user data and parse into tuples of user id and attribute list
val users = (sc.textFile("data/graphx/users.txt")
  .map(line => line.split(",")).map( parts => (parts.head.toLong, parts.tail) ))

// Parse the edge data which is already in userId -> userId format
val followerGraph = GraphLoader.edgeListFile(sc, "data/graphx/followers.txt")

// Attach the user attributes
val graph = followerGraph.outerJoinVertices(users) {
  case (uid, deg, Some(attrList)) => attrList
  // Some users may not have attributes so we set them as empty
  case (uid, deg, None) => Array.empty[String]
}

// Restrict the graph to users with usernames and names
val subgraph = graph.subgraph(vpred = (vid, attr) => attr.size == 2)

// Compute the PageRank
val pagerankGraph = subgraph.pageRank(0.001)

// Get the attributes of the top pagerank users
val userInfoWithPageRank = subgraph.outerJoinVertices(pagerankGraph.vertices) {
  case (uid, attrList, Some(pr)) => (pr, attrList.toList)
  case (uid, attrList, None) => (0.0, attrList.toList)
}

println(userInfoWithPageRank.vertices.top(5)(Ordering.by(_._2._1)).mkString("\n"))
在Spark存储库中的“ examples / src / main / scala / org / apache / spark / examples / graphx / ComprehensiveExample.scala”中找到完整的示例代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值