1
votes

I have a pyspark data frame(df1) which consist of 10K rows and the data frame looks like -

id       mobile_no       value
1        1111111111        .43
2        2222222222        .54
3        3333333333        .03
4        4444444444        .22

another pyspark data frame (df2) consist of 100k records and looks like -

mobile_no            gender
912222222222           M
914444444444           M
919999999999           F
915555555555           M
918888888888           F

I want inner join using pyspark where final data frame looks like -

mobile_no          value           gender
2222222222         .54               M
4444444444         .22               M

the length of the mobile_no in df2 is 12 but in df1 is 10. I can join it but it's costly operation. Any help using pyspark?

common_cust = spark.sql("SELECT mobile_number, age \
                         FROM df1 \
                         WHERE mobile_number IN (SELECT DISTINCT mobile_number FROM df2)")
1

1 Answers

0
votes

One way could be to use substring function on df2 to keep only the last 10 digits to get the same length than in df1:

import pyspark.sql.functions as F

ddf2.select(F.substring('mobile_no', 3, 10).alias('mobile_no'),'gender').show()
+----------+------+
| mobile_no|gender|
+----------+------+
|2222222222|     M|
|4444444444|     M|
|9999999999|     F|
|5555555555|     M|
|8888888888|     F|
+----------+------+

Then you just need to do a inner join to get your expected output:

common_cust = df1.select('mobile_no', 'value')\
                 .join( df2.select(F.substring('mobile_no', 3, 10).alias('mobile_no'),'gender'), 
                        on=['mobile_no'], how='inner')
common_cust.show()
+----------+-----+------+
| mobile_no|value|gender|
+----------+-----+------+
|2222222222| 0.54|     M|
|4444444444| 0.22|     M|
+----------+-----+------+

If you want to use a spark.sql, I guess you can do it like this:

common_cust = spark.sql("""select df1.mobile_no, df1.value, df2.gender
                           from df1
                           inner join df2 
                           on df1.mobile_no = substring(df2.mobile_no, 3, 10)""")