Spark:从 RDD[X] 产生所有可能组合的 RDD[(X, X)] [英] Spark: produce RDD[(X, X)] of all possible combinations from RDD[X]
问题描述
是否可以在 Spark 中从 Scala 集合中实现.combinations"功能?
Is it possible in Spark to implement '.combinations' function from scala collections?
/** Iterates over combinations.
*
* @return An Iterator which traverses the possible n-element combinations of this $coll.
* @example `"abbbc".combinations(2) = Iterator(ab, ac, bb, bc)`
*/
例如,对于大小 = 2 的组合,我如何从 RDD[X] 到 RDD[List[X]] 或 RDD[(X,X)].假设 RDD 中的所有值都是唯一的.
For example how can I get from RDD[X] to RDD[List[X]] or RDD[(X,X)] for combinations of size = 2. And lets assume that all values in RDD are unique.
推荐答案
笛卡尔积和组合是两个不同的东西,笛卡尔积会创建一个大小为 rdd.size() ^ 2
和组合将创建一个大小为 rdd.size() 选择 2
Cartesian product and combinations are two different things, the cartesian product will create an RDD of size rdd.size() ^ 2
and combinations will create an RDD of size rdd.size() choose 2
val rdd = sc.parallelize(1 to 5)
val combinations = rdd.cartesian(rdd).filter{ case (a,b) => a < b }`.
combinations.collect()
请注意,这仅在列表元素上定义了排序时才有效,因为我们使用 <
.这个只适用于选择两个,但可以通过确保关系 a < 轻松扩展.b
表示序列中的所有 a 和 b
Note this will only work if an ordering is defined on the elements of the list, since we use <
. This one only works for choosing two but can easily be extended by making sure the relationship a < b
for all a and b in the sequence
这篇关于Spark:从 RDD[X] 产生所有可能组合的 RDD[(X, X)]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!