Spark中两个RDD的笛卡尔积

Cartesian product of two RDD in Spark

我是 Apache Spark 的新手,我正在尝试对两个 RDD 进行笛卡尔乘积。例如,我有 A 和 B,如:

A = {(a1,v1),(a2,v2),...}
B = {(b1,s1),(b2,s2),...}

我需要一个新的 RDD,例如:

C = {((a1,v1),(b1,s1)), ((a1,v1),(b2,s2)), ...}

知道我该怎么做吗?越简单越好:)

提前致谢

PS:我终于按照@Amit Kumar 的建议这样做了:

笛卡尔乘积 = A.cartesian(B)

那不是点积,那是笛卡尔积。使用cartesian方法:

def cartesian[U](other: spark.api.java.JavaRDDLike[U, _]): JavaPairRDD[T, U]

Return the Cartesian product of this RDD and another one, that is, the RDD of all pairs of elements (a, b) where a is in this and b is in other.

Source

您可以按照以下方式进行操作:

A = {(a1,v1),(a2,v2),...}
B = {(b1,s1),(b2,s2),...}

C = A.cartesian(B)

如果你这样做:

C.take(5)

你可以看到这就是你想要的。

以防万一,如果您对如何处理多个列表感到好奇,这里有一个 pyspark 中的示例

>>> a = [1,2,3]
>>> b = [5,6,7,8]
>>> c = [11,22,33,44,55]
>>> import itertools
>>> abcCartesianRDD = sc.parallelize(itertools.product(a,b,c))
>>> abcCartesianRDD.count() #Test
    60