invoketheshell invoketheshell - 8 months ago 276
Python Question

How do you perform basic joins of two RDD tables in Spark using Python?

How would you perform basic joins in Spark using python? In R you could use merg() to do this. What is the syntax using python on spark for:

  1. Inner Join

  2. Left Outer Join

  3. Cross Join

With two tables (RDD) with a single column in each that has a common key.


I think an inner join is something like this:

rdd1.join(rdd2).map(case (key, u, v) => (key, ls ++ rs));

Is that right? I have searched the internet and can't find a good example of joins. Thanks in advance.


It can be done either using PairRDDFunctions or Spark Data Frames. Since data frame operations benefit from Catalyst Optimizer the second option can worth considering.

Assuming your data looks as follows:

rdd1 =  sc.parallelize([("foo", 1), ("bar", 2), ("baz", 3)])
rdd2 =  sc.parallelize([("foo", 4), ("bar", 5), ("bar", 6)])

With PairRDDs:

Inner join:


Left outer join:


Cartesian product (doesn't require RDD[(T, U)]):


Broadcast join (doesn't require RDD[(T, U)]):

Finally there is cogroup which has no direct SQL equivalent but can be useful in some situations:

cogrouped = rdd1.cogroup(rdd2)

cogrouped.mapValues(lambda x: (list(x[0]), list(x[1]))).collect()
## [('foo', ([1], [4])), ('bar', ([2], [5, 6])), ('baz', ([3], []))]

With Spark Data Frames

You can use either SQL DSL or execute raw SQL using sqlContext.sql.

df1 = sqlContext.createDataFrame(rdd1, ('k', 'v1'))
df2 = sqlContext.createDataFrame(rdd2, ('k', 'v2'))

# Register temporary tables to be able to use sqlContext.sql

Inner join:

# inner is a default value so it could be omitted
df1.join(df2, df1.k == df2.k, joinType='inner') 
sqlContext.sql('SELECT * FROM df1 JOIN df2 ON df1.k = df2.k')

Left outer join:

df1.join(df2, df1.k == df2.k, joinType='left_outer')
sqlContext.sql('SELECT * FROM df1 LEFT OUTER JOIN df2 ON df1.k = df2.k')

Cross join:

sqlContext.sql('SELECT * FROM df1 JOIN df2')

Since 1.6 (1.5 in Scala) each of these can be combined with broadcast function:

from pyspark.sql.functions import broadcast


to perform broadcast join. See also Why my BroadcastHashJoin is slower than ShuffledHashJoin in Spark