首页 > 解决方案 > 过滤和排序顶点Graphx Scala

问题描述

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

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)

我只想获取带有 property1 的顶点,并且此代码运行良好:

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

这就是结果:

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

现在,问题是我想让这些顶点按“服务”排序,这是 Property1 类的第二个参数。我可以按顶点 id 对结果进行排序:

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

但这不起作用。

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

标签: scalaapache-sparkspark-graphx

解决方案


转换VertexPropertytrait(或制作父类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 中工作。请参阅Apache Spark 中的案例类相等性并在必要时按照说明进行操作。

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

  3. 你不能sortBy(_._2._2),因为Property1is not a Tuple2and has no _._2- 它只有nameand servings。也没有必要collect

    vertices.sortBy(_._2.servings)
    

推荐阅读