在 Python(boto3)中執行 DynamoDB 條件式寫入
條件式寫入是把 ConditionExpression 附加到 put_item、update_item 或 delete_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_exists、attribute_not_exists、attribute_type、contains、begins_with、size,以及比較運算子(=、<>、<、>、<=、>=、BETWEEN、IN)與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。
相關範例
- 在 Node.js 中執行 DynamoDB 條件式寫入 — 以 AWS SDK v3 執行相同的樂觀鎖。
- 使用 AWS CLI 執行 DynamoDB 條件式寫入 — 從 shell 執行相同的樂觀鎖。
- 在 Python 中使用 DynamoDB PutItem — 只建立的
attribute_not_existsput。 - DynamoDB 條件運算式 — 每個函式與其模式。
- 在多個屬性上強制唯一性 — 條件與交易的結合。
- DynamoDB ConditionalCheckFailedException — 當失敗的檢查在預期之內時,如何以低成本處理它。
References
- UpdateItem — Amazon DynamoDB API Reference
- DynamoDB.Client.update_item — Boto3 documentation
- Condition expressions — Amazon DynamoDB Developer Guide
- DynamoDB read and write operations (capacity unit consumption) — Amazon DynamoDB Developer Guide
最後驗證於 2026-07-13,對照上方連結的 AWS 官方文件。