我有两个 RDD:points
和pointsWithinEps
. 中的每个点points
代表x, y
坐标。pointsWithinEps
表示两点和它们之间的距离:((x, y), distance)
. 我想循环所有点,并且为每个点过滤仅位于pointsWithinEps
as 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
是 null (在 foreach 之前有元素)?