You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DeltaMergeBuilder报错:无whenNotMatchedBySourceDelete属性的解决方法

Delta Lake merge操作报错:'DeltaMergeBuilder' object has no attribute 'whenNotMatchedBySourceDelete'

问题描述

我在使用Delta Lake时,尝试通过WHEN NOT MATCHED BY SOURCE子句删除目标表中无对应源表记录的数据,参考了如下基础语法示例:

(targetDF
  .merge(sourceDF, "source.key = target.key")
  .whenMatchedUpdateAll()
  .whenNotMatchedInsertAll()
  .whenNotMatchedBySourceDelete()
  .execute()
)

但自行编写的代码运行时触发报错:

'DeltaMergeBuilder' object has no attribute 'whenNotMatchedBySourceDelete'

我的代码如下:

deltadf.alias("t")
   .merge(
    partdf.alias("s"),
    "s.primary_key_hash = t.primary_key_hash")
  .whenMatchedUpdateAll("s.change_key_hash <> t.change_key_hash")
  .whenNotMatchedInsertAll()
  .whenNotMatchedBySourceDelete().
 execute()
)

报错原因

  1. Delta Lake版本不兼容:whenNotMatchedBySourceDelete()是Delta Lake 2.0及以上版本新增的API,若使用低于2.0的版本,DeltaMergeBuilder对象不存在该方法。
  2. 代码语法错误:代码中.whenNotMatchedBySourceDelete()末尾多了一个英文句号,会导致语法解析异常,即使版本符合要求也会报错。

解决方法

1. 升级Delta Lake版本

  • 先确认当前版本:
    import delta
    print(delta.__version__)
    
  • 版本低于2.0时执行升级:
    • PySpark环境:
      pip install delta-spark>=2.0.0
      
    • Maven项目:更新pom.xml中的依赖版本:
      <dependency>
        <groupId>io.delta</groupId>
        <artifactId>delta-core_2.12</artifactId>
        <version>2.0.0</version>
      </dependency>
      

2. 修正代码语法错误

删除.whenNotMatchedBySourceDelete()后的多余句号,同时建议显式指定condition参数提升代码可读性,修正后的代码:

deltadf.alias("t")
   .merge(
    partdf.alias("s"),
    "s.primary_key_hash = t.primary_key_hash")
  .whenMatchedUpdateAll(condition="s.change_key_hash <> t.change_key_hash")
  .whenNotMatchedInsertAll()
  .whenNotMatchedBySourceDelete()
  .execute()

若需过滤删除的记录,可给whenNotMatchedBySourceDelete()添加条件,例如:.whenNotMatchedBySourceDelete(condition="t.is_valid = false")

内容的提问来源于stack exchange,提问作者Patterson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:35:05