[英]Spark: Intersection of Lists not working
我有以下形式的RDD:
t1-> (Long, List[Long])
和表格清單
t2-> List[Long]
我需要執行列表的並集和交集。 我正在嘗試以下代碼:
val t1 = a.map(x => (x._1, (List(x._2)))).reduceByKey(_ ++ _)
val t2 = b.map(x => (x._1, (List(x._2)))).reduceByKey(_ ++ _).map(x => x._2).collect()
val t3intersect = t1.map(x => (x._1, (x._2.intersect(t2))))
val t3union = t1.map(x => (x._1, (x._2.union(t2))))
盡管union返回正確的結果,但交集始終為空列表。 我無法識別問題。 請幫忙! 謝謝!
這是一個例子:
(1, List(1596, 1617, 1929, 2399, 2674))
(2, List(1702, 1785, 1933, 2054, 2583, 2913))
(3, List(1982, 2002, 2048, 2341, 2666))
和
List(2002, 2399)
這應該返回交集:
(1, List(2399))
(2, List())
(3, List(2002))
和聯合:
(1, List(1596, 1617, 1929, 2399, 2674, 2002))
(2, List(1702, 1785, 1933, 2054, 2583, 2913, 2002, 2399))
(3, List(1982, 2002, 2048, 2341, 2666, 2399))
您的交叉碼對我來說還不錯。 它應該工作。 也可以嘗試這樣做,以提高清晰度和性能:
val t3intersect = t1.mapValues( _ intersect t2 )
編輯 :我不知道什么是a
和b
,以及從它們那里獲取t1
和t2
的邏輯是什么,但是為了進行測試,如果您在Spark REPL中按以下方式初始化t1
和t2
:
scala> val t1 = sc.parallelize( List(
| (1, List(1596, 1617, 1929, 2399, 2674)),
| (2, List(1702, 1785, 1933, 2054, 2583, 2913)),
| (3, List(1982, 2002, 2048, 2341, 2666)) ), 2)
t1: org.apache.spark.rdd.RDD[(Int, List[Int])] = ParallelCollectionRDD[10] at parallelize at <console>:12
scala> val t2 = List(2002, 2399)
t2: List[Int] = List(2002, 2399)
然后,您將獲得預期的結果:
scala> val tr = t1.mapValues( _ intersect t2 )
tr: org.apache.spark.rdd.RDD[(Int, List[Int])] = MappedValuesRDD[12] at mapValues at <console>:16
scala> tr.collect()
res13: Array[(Int, List[Int])] = Array((1,List(2399)), (2,List()), (3,List(2002)))
因此,請注意其他地方的錯誤。
我轉載了您的有問題的案例,如下所示:
object ItersectionList {
def main(args: Array[String]) {
val spConf = new SparkConf().setMaster("local[2]").setAppName("ItersectionList")
val sc = new SparkContext(spConf)
val a = Array(
(1, List(1596, 1617, 1929, 2399, 2674)),
(2, List(1702, 1785, 1933, 2054, 2583, 2913)),
(3, List(1982, 2002, 2048, 2341, 2666))
)
val t2 = List(2002, 2399)
val t1 = sc.makeRDD(a).map(x => (x._1, (List(x._2)))).reduceByKey(_ ++ _)
val t3intersect = t1.map(x => (x._1, (x._2.intersect(t2))))
val t3union = t1.map(x => (x._1, (x._2.union(t2))))
t3intersect.foreach(println)
t3union.foreach(println)
}
}
結果如下:
Intersection:
(2,List())
(1,List())
(3,List())
Union:
(2,List(List(1702, 1785, 1933, 2054, 2583, 2913), 2002, 2399))
(1,List(List(1596, 1617, 1929, 2399, 2674), 2002, 2399))
(3,List(List(1982, 2002, 2048, 2341, 2666), 2002, 2399))
我發現它是問題List(x._2)
在map(x => (x._1, (List(x._2)))).reduceByKey(_ ++ _)
這改變了List(a, b, c)
到List(List(a, b, c))
。 由於List(List(a, b, c))
與List(a, b, c)
不匹配,因此交集將為null。 您可以按以下方式刪除List()
,結果將是正確的。
val t1 = sc.makeRDD(a).map(x => (x._1, x._2)).reduceByKey(_ ++ _)
要么
val t1 = sc.makeRDD(a).reduceByKey(_ ++ _)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.