【发布时间】:2014-12-22 00:14:31
【问题描述】:
我有两个 RDD:points 和 pointsWithinEps。 points 中的每个点代表x, y 坐标。 pointsWithinEps 代表两点和它们之间的距离:((x, y), distance)。我想循环所有点,并且对于每个点,只过滤pointsWithinEps 中的元素作为x(第一个)坐标。所以我做了以下事情:
points.foreach(p =>
val distances = pointsWithinEps.filter{
case((x, y), distance) => x == p
}
if (distances.count() > 3) {
// do some other actions
}
)
但是这种语法是无效的。据我了解,不允许在 Spark foreach 中创建变量。我应该这样做吗?
for (i <- 0 to points.count().toInt) {
val p = points.take(i + 1).drop(i) // take the point
val distances = pointsWithinEps.filter{
case((x, y), distance) => x == p
}
if (distances.count() > 3) {
// do some other actions
}
}
或者有更好的方法来做到这一点?完整代码托管在这里:https://github.com/timasjov/spark-learning/blob/master/src/DBSCAN.scala
编辑:
points.foreach({ p =>
val pointNeighbours = pointsWithinEps.filter {
case ((x, y), distance) => x == p
}
println(pointNeighbours)
})
现在我有以下代码,但它会引发 NullPointerException (pointsWithinEps)。为什么pointsWithinEps为空(在foreach之前有元素),如何解决?
【问题讨论】:
-
我是否理解正确,对于
points上的每个点 (x,y),您想要来自pointsWithinEps的所有 ((x,y),distance) 元组源自同一 (x ) ? -
是的。基本上对于每个点,我都想找出哪些其他点是它的邻居(在 epsilon 内的点)。在我的情况下,它是点本身和 ((x, y), distance) 结构中的 x。代码在 github 中,因此例如您可以执行它并在调试器中找到确切的值。
标签: scala apache-spark rdd