【问题标题】:Pyspark multiple left join on the same conditionsPyspark 在相同条件下多次左连接
【发布时间】:2021-06-23 09:48:07
【问题描述】:

我有一个包含 key1key2 列的主表。 我需要在相同的条件["key1", "key2"] 上将这张表加入许多其他(table_1table_2、...、table_n)。 我正在尝试这样的事情。

condition = ["key1", "key2"]
df1 = sqlc.sql("SELECT key1, key2 FROM table")
df_1 = sqlc.table("table_1")
df_2 = sqlc.table("table_2")
...
df_n = sqlc.table("table_n")

merged_df = df \
    .join(df_1, condition, how="left") \
    .join(df_2, condition, how="left") \
    ...
    .join(df_n, condition, how="left") \

有没有更高效、更可靠的实现方式?也许使用cache()checkpoint()? 最佳做法是什么? Pyspark 2.4.0 版

【问题讨论】:

    标签: python dataframe apache-spark pyspark apache-spark-sql


    【解决方案1】:

    我建议将df_* 连接成一个PySpark DataFrame

    
    from functools import reduce
    
    def spark_concat(inp):
      df_complete = reduce(lambda x,y:x.union(y), inp)
      return df_complete
    
    
    res = []
    
    for tb in ['table1','table2']:
        res += [sqlc.table(tb)]
    
    df_table_complete = spark_concat(res)
    
    condition = ....
    merged_df = df.join(df_table_complete, condition, how="left")
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 2017-09-24
      • 2011-12-11
      • 1970-01-01
      • 2018-12-06
      • 2010-11-11
      相关资源
      最近更新 更多