我有兩個RDD:points
和pointsWithinEps
。 points
中的每個點代表x, y
座標。 pointsWithinEps
表示它們之間的兩點和距離:((x, y), distance)
。我想循環所有點,並且每個點過濾器只有位於pointsWithinEps
的元素(第一個)座標爲x
(第一個)。所以我做如下:Spark內部的代碼執行
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),你希望所有的(( X ,y),距離)來自'pointsWithinEps'的元組來源於相同的(x)? – maasg 2014-10-26 20:19:25
是的。基本上對於每一點我想找到哪些其他點是它的鄰居(在epsilon內的點)。在我的情況下,它指向自身,x((x,y),距離)結構。代碼在github中,例如,你可以執行它並在調試器中找到什麼是值。 – Bob 2014-10-26 20:22:40