我有一个形式的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))))
虽然并集返回正确的结果,但交集始终为空列表。我无法确定问题所在。请帮忙!谢谢!
下面是一个示例:
(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
背后的逻辑是什么,但是如果您初始化t1
并在Spark REPL中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))
我发现是map(x => (x._1, (List(x._2)))).reduceByKey(_ ++ _)
中的List(x._2)
问题,将List(a, b, c)
更改为List(List(a, b, c))
。由于List(List(a, b, c))
与List(a, b, c)
不匹配,交集将为空。您可以按如下方式删除List()
,结果将是正确的。
val t1 = sc.makeRDD(a).map(x => (x._1, x._2)).reduceByKey(_ ++ _)
或
val t1 = sc.makeRDD(a).reduceByKey(_ ++ _)