2014-10-26 114 views
0

我有兩個RDD:pointspointsWithinEpspoints中的每個點代表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中有元素之前)?

+0

我是否理解正確的話,對於在'points'每個點(X,Y),你希望所有的(( X ,y),距離)來自'pointsWithinEps'的元組來源於相同的(x)? – maasg 2014-10-26 20:19:25

+0

是的。基本上對於每一點我想找到哪些其他點是它的鄰居(在epsilon內的點)。在我的情況下,它指向自身,x((x,y),距離)結構。代碼在github中,例如,你可以執行它並在調試器中找到什麼是值。 – Bob 2014-10-26 20:22:40

回答

2

爲了收集開始在給定的座標,這樣做的一個簡單的分佈式的方法是鍵入由點由按鍵座標x,並將它們組合,這樣所有的距離點:

val pointsWithinEpsByX = pointsWithinEps.map{case ((x,y),distance) => (x,((x,y),distance))} 
val xCoordinatesWithDistance = pointsWithinEpsByX.groupByKey 

然後左連接點的RDD與先前轉換的結果:

val pointsWithCoordinatesWithDistance = points.leftOuterJoin(xCoordinatesWithDistance) 
+0

編譯器顯示沒有groupByKey方法,只有groupBy。對於leftOuterJoin方法也是如此。我正在使用Hadoop 1.X – Bob 2014-10-26 20:53:12

+0

預構建的spark 1.1.0另外,我應該把它放到foreach循環中嗎? – Bob 2014-10-26 20:56:29

+2

這些是通過隱式轉換在(鍵,值)對的RDD上可用的函數。在程序的頂部導入'org.apache.spark.SparkContext._'以使用這些功能。 - 另外,不需要循環。這個功能流水線通過對整個數據集應用轉換和分組來完成工作。 – maasg 2014-10-26 21:01:05

0

聲明變量意味着你有一個塊,而不僅僅是一個表達式,所以你需要使用大括號{},例如,

point.foreach({p => ... }) 
+0

謝謝!但是,您是否也可以幫助我描述的功能? – Bob 2014-10-26 19:52:23