scala - 过滤和排序顶点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)
解决方案
转换VertexProperty
为trait
(或制作父类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
字段对其进行排序。
注意:
如果没有额外的调整,它可能无法在 REPL 中工作。请参阅Apache Spark 中的案例类相等性并在必要时按照说明进行操作。
collect { }
的行为与 不同collect()
。第一个通过应用 f 返回一个包含所有匹配值的 RDD,而最新的收集并向驱动程序返回一个包含此 RDD 中所有元素的数组。你不能
sortBy(_._2._2)
,因为Property1
is not aTuple2
and has no_._2
- 它只有name
andservings
。也没有必要collect
:vertices.sortBy(_._2.servings)
推荐阅读
- excel - 清除所有工作表中的所有评论
- java - 响应成功时取消调度程序执行器
- vba - 如何将文件夹中的多个文本文件导入一个工作表并固定宽度?
- html - 如何在不影响文本的情况下对 div 类中的图像进行转换?
- php - 为什么我不能写入文件?
- javascript - 为什么这个承诺会被拒绝?
- r - Assigning quantiles in R where quantiles are not unique
- c# - C# - 列出网页源文件(例如来自检查元素)
- kubernetes - 我如何找出主机上的端口属于哪个端口或服务
- node.js - 从 Node.js 应用程序连接到通过 Amazon 上的 RDS 托管的 postgres 时出现超时错误