【问题标题】:Joining 2 tables in pyspark, multiple conditions, left join?在pyspark中加入2个表,多个条件,左连接?
【发布时间】:2020-11-06 06:20:34
【问题描述】:

我有 2 个如下表。我下面的代码是连接 2 个表(左连接)。问题是我必须两次做同样的加入。第一个连接发生在 log_no 和 LogNumber 上,它返回左表 (table1) 中的所有记录,以及右表 (table2) 中的匹配记录。第二个连接做同样的事情,但在 log_no 的子字符串上使用 LogNumber。例如,777 将与表 2 中的 777 匹配,777-A 没有匹配,但是当使用子字符串函数时,777-A 变为 777,这将在表 2 中匹配。

不是像下面那样创建 2 个单独的连接,而是如何用一个连接来覆盖这两种情况。代码如下:

# first join to match 1234-A (table 1) with 1234-A (table 2)
df5 = df5.join(df_app, trim(df5.LOG_NO) == trim(df_app.LogNumber), "left")\
         .select (df5["*"], df_app["ApplicationId"])
df5 = df5.withColumnRenamed("ApplicationId","ApplicationId_1")
        
# second join with substring function, to match 777-C with 777, 
# my string is longer than my examples, this is why I have a substring for the first 8 characters. I provided simple examples.

df5 = df5.join(df_app, substring(trim(df5.LOG_NO), 1, 8) == trim(df_app.LogNumber), "left")\
         .select (df5["*"], df_app["ApplicationId"])
df5 = df5.withColumnRenamed("ApplicationId","ApplicationId_2")

【问题讨论】:

    标签: apache-spark pyspark apache-spark-sql pyspark-dataframes


    【解决方案1】:

    您可以使用按位 OR 组合两个连接条件:

    df5 = df5.join(df_app, 
                   (trim(df5.LOG_NO) == trim(df_app.LogNumber)) |
                   (substring(trim(df5.LOG_NO), 1, 8) == trim(df_app.LogNumber)), 
                   "left") \
             .select(df5["*"], df_app["ApplicationId"])
    

    【讨论】:

    • 我很困惑为什么AND?这意味着这两个条件都必须为真。如果第一个条件失败,则子字符串条件应该为真。
    • @AJR 对不起,应该是 OR。编辑了我的答案。
    • 我的程序没有完成....我不得不在双倍时间后杀死它。通常我的胶水工作大约需要 22 分钟才能完成,我让它运行了 44 分钟,它仍在运行......我认为出于某种原因,按位或将我的程序置于循环中并且它没有完成。还有什么建议吗??谢谢
    • @AJR 首先尝试使用较小的数据框,以检查它是否正确完成工作。 'OR' 不可能将您的程序置于循环中。这根本不可能。
    猜你喜欢
    • 2016-03-06
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多