在 Python(boto3)中執行 DynamoDB 條件式寫入

條件式寫入是把 ConditionExpression 附加到 put_itemupdate_itemdelete_item 上:DynamoDB 會對目前的項目評估它,只有在成立時才套用寫入 — 以 atomic 方式進行,沒有 read-modify-write 競爭。這是 DynamoDB 的樂觀鎖基本手法。本範例以版本檢查為一次更新加上守衛。

Code

import boto3

client = boto3.client("dynamodb")

# Update the item only if nobody changed it since we read version 7.
try:
    client.update_item(
        TableName="Music",
        Key={"Artist": {"S": "Arturo Sandoval"}, "SongTitle": {"S": "Cubano Chant"}},
        UpdateExpression="SET #upd0 = :updValue0, #version = :newVersion",
        ConditionExpression="attribute_exists(#cond0) AND #version = :expectedVersion",
        ExpressionAttributeNames={"#upd0": "Genre", "#version": "Version", "#cond0": "Artist"},
        ExpressionAttributeValues={
            ":updValue0": {"S": "Latin Jazz"},
            ":expectedVersion": {"N": "7"},
            ":newVersion": {"N": "8"},
        },
        ReturnValuesOnConditionCheckFailure="ALL_OLD",
    )
    print("Updated to version 8")
except client.exceptions.ConditionalCheckFailedException as e:
    # With ReturnValuesOnConditionCheckFailure="ALL_OLD", the current item
    # rides back on the exception — no extra read to see what beat you.
    print("Lost the race — item is now:", e.response.get("Item"))

說明

  • ConditionExpression — 與寫入以 atomic 方式一起對已儲存的項目檢查。可用的函式:attribute_existsattribute_not_existsattribute_typecontainsbegins_withsize,以及比較運算子(=<><><=>=BETWEENIN)與 AND/OR/NOT
  • 兩個主力慣用手法:
    • 更新上使用 attribute_exists(#key) = 「只更新、絕不建立」。沒有它,對缺少的 key 執行 update_item 會靜默建立該項目(意外 upsert 的 bug)。
    • put 上使用 attribute_not_exists(#key) = 「只建立、絕不覆寫」— 見 PutItem 頁面
  • 樂觀鎖 — 讀取項目(版本 7),然後在寫入時以 #version = :expectedVersion 檢查並把版本推進到 8。兩個並行的寫入者不可能都贏;輸家會拿到 ConditionalCheckFailedException,接著重新讀取、在新版本上重試。
  • ReturnValuesOnConditionCheckFailure="ALL_OLD" — 把目前的項目放在例外回應上(e.response),省下失敗檢查後的後續 get_item。它不消耗讀取容量;失敗的條件式寫入仍會對其寫入嘗試計費。
  • resource API 上,相同的守衛是 table.update_item(..., ConditionExpression=Attr("Version").eq(7) & Attr("Artist").exists()),使用原生的 Python 值。

改用視覺化操作

條件運算式正是 DynamoDB Expression Builder 所建立的 — 選擇函式,取得運算式與 name/value map,形成可執行的 boto3 程式碼。

想以產生且可審視的運算式編輯項目,而非手打的佔位符 — 下載 DynoTable

相關範例

References

最後驗證於 2026-07-13,對照上方連結的 AWS 官方文件。

不必透過主控台就能操作 DynamoDB

DynoTable 是一款快速的 DynamoDB 桌面用戶端 — 瀏覽表格、執行 SQL 風格的查詢,並在本機編輯項目。