【问题标题】:Joining two DataFrames and appending where not exists加入两个 DataFrame 并在不存在的地方追加
【发布时间】:2018-01-30 00:03:42
【问题描述】:

我有两个 DataFrame。一个是MasterList,另一个是InsertList

主列表:

+--------+--------+
|  ttm_id|audit_id|
+--------+--------+
|       1|      10|
|      15|      10|
+--------+--------+

插入列表:

+--------+--------+
|  ttm_id|audit_id|
+--------+--------+
|       1|      10|
|      15|       9|
+--------+--------+

在 Scala 中,我如何加入两个 DataFrame,但只附加到新的 DataFrame 记录

WHERE MasterList.ttm_id = InsertList.ttm_id AND
      MasterList.audit_id != InsertList.audit_id

-

预期输出:

+--------+--------+
|  ttm_id|audit_id|
+--------+--------+
|       1|      10|
|      15|      10|
|      15|       9|
+--------+--------+

【问题讨论】:

    标签: scala apache-spark apache-spark-sql


    【解决方案1】:

    我反对通过两列和union 加入 (NOT IN)

    val masterList = Seq((1, 10), (15, 10)).toDF("ttm_id", "audit_id")
    val insertList = Seq((1, 10), (15, 9)).toDF("ttm_id", "audit_id")
    
    insertList
        .join(masterList, Seq("ttm_id", "audit_id"), "leftanti")
        .union(masterList)
        .show
    // +------+--------+
    // |ttm_id|audit_id|
    // +------+--------+
    // |    15|       9|
    // |     1|      10|
    // |    15|      10|
    // +------+--------+
    

    【讨论】:

      【解决方案2】:

      您似乎想合并 rows from insertList dataFrame 不在masterList dataFrame时间>。这可以使用except 函数来实现

      insertList.except(masterList)
      

      而您只需使用 union 函数将两个 dataFrames 合并为

      masterList.union(insertList.except(masterList))
      

      你应该得到你想要的

      +------+--------+
      |ttm_id|audit_id|
      +------+--------+
      |1     |10      |
      |15    |10      |
      |15    |9       |
      +------+--------+
      

      【讨论】:

        猜你喜欢
        • 2018-09-30
        • 2010-10-19
        • 2017-08-27
        • 1970-01-01
        • 2019-05-25
        • 1970-01-01
        • 1970-01-01
        • 2016-12-07
        • 2017-07-16
        相关资源
        最近更新 更多