Aarav
Aarav

Reputation: 111

Combining two different lines in Python Spark RDD

I am having small problem dealing with python spark rdd. My rdd looks like

old_rdd = [( A1, Vector(V1)), (A2, Vector(V2)), (A3, Vector(V3)), ....].

I want to use flatMap, so as to get new rdd like:

new_rdd = [((A1, A2), (V1, V2)), ((A1, A3), (V1, V3))] and so on.

The problem is flatMap removed tuple like [(A1, V1, A2, V2)...]. Do you have any alternative suggestions with or without flatMap(). Thank you in advance.

Upvotes: 0

Views: 917

Answers (1)

Alberto Bonsanto
Alberto Bonsanto

Reputation: 18042

It is related to Explicit sort in Cartesian transformation in Scala Spark. However, I will suppose that you already cleaned up the RDD for duplicates, and I will assume that the ids have some simple pattern to parse and then identify, and for simplicity I will think on Lists instead of Vectors

old_rdd = sc.parallelize([(1, [1, -2]), (2, [5, 7]), (3, [8, 23]), (4, [-1, 90])])

# It will provide all the permutations, but combinations are a subset of the permutations, so we need to filter.
combined_rdd = old_rdd.cartesian(old_
combinations = combined_rdd.filter(lambda (s1, s2): s1[0] < s2[0])

combinations.collect()

#  The output will be...
# -----------------------------
# [((1, [1, -2]), (2, [5, 7])),
#  ((1, [1, -2]), (3, [8, 23])),
#  ((1, [1, -2]), (4, [-1, 90])),
#  ((2, [5, 7]), (3, [8, 23])),
#  ((2, [5, 7]), (4, [-1, 90])),
#  ((3, [8, 23]), (4, [-1, 90]))]

# Now we need to set the tuple as you want
combinations = combinations.map(lambda (s1, s1): ((s1[0], s2[0]), (s1[1], s2[1]))).collect()

# The output will be...
# ----------------------
# [((1, 2), ([1, -2], [5, 7])),
# ((1, 3), ([1, -2], [8, 23])),
# ((1, 4), ([1, -2], [-1, 90])),
# ((2, 3), ([5, 7], [8, 23])),
# ((2, 4), ([5, 7], [-1, 90])),
# ((3, 4), ([8, 23], [-1, 90]))]

Upvotes: 1

Related Questions