过滤和排序顶点 Graphx Scala

Filter and Sort Vertices Graphx Scala

我的图包含具有不同属性 classes 的顶点。我想过滤具有特定 属性 的顶点,然后对它们进行排序。这是我的代码的样子:

class VertexProperty()
case class Property1(val name: String, val servings: Int) extends VertexProperty
case class Property2(val description: String) extends VertexProperty

val vertexArray = Array(
(1L, Property1("propertyName",8)),
(2L, Property1("propertyName",4)),
(3L, Property2("description"))
)

val edgeArray = Array(
 Edge(1L, 2L, "step1"),
 Edge(1L, 3L, "step2")
 )

val vertexRDD: RDD[(Long, VertexProperty)] = sc.parallelize(vertexArray) 
val edgeRDD: RDD[Edge[String]] = sc.parallelize(edgeArray)
val graph: Graph[VertexProperty, String] = Graph(vertexRDD, edgeRDD)

我只想获取 属性1 的顶点,这段代码工作正常:

val vertices = graph.vertices.filter{
  case (id, vp: Property1) => vp.description != ""
  case _ => false
}

结果是:

(1L, Property1("propertyName",8)), (2L, Property1("propertyName",4))

现在,问题是我想按照 Property1 class 的第二个参数 "servings" 对这些顶点进行排序。我可以按顶点 ID 对结果进行排序:

vertices.collect().sortBy(_._1).foreach(println)

但这行不通。

vertices.collect().sortBy(_._2._2).foreach(println)

VertexProperty 转换为 trait(或使父级 class Serializable

sealed trait VertexProperty
case class Property1(name: String, servings: Int) extends VertexProperty
case class Property2(description: String) extends VertexProperty

确保类型匹配:

val vertexArray: Array[(Long, VertexProperty)] = Array(
  (1L, Property1("propertyName",8)),
  (2L, Property1("propertyName",4)),
  (3L, Property2("description"))
)

收集而不是过滤:

val vertices: RDD[(Long, Property1)] = graph.vertices.collect {
  case (id, p @ Property1(name, _)) if name != "" => (id, p)
}

结果 RDD 将是 RDD[(Long, Property1)],您可以按 Property1 个字段对其进行排序。

:

  1. 如果不进行额外的调整,它可能无法在 REPL 中工作。请参阅 并在必要时按照说明进行操作。

  2. collect { } 的行为不同于 collect()。第一个 returns 一个 RDD,它通过应用 f 包含所有匹配值,而最新的 returns 收集并 returns 一个包含此 RDD 中所有元素的数组给驱动程序。

  3. 你不能 sortBy(_._2._2),因为 Property1 不是 Tuple2 并且没有 _._2 - 它只有 nameservings。也没有必要 collect:

    vertices.sortBy(_._2.servings)