在 Node.js(AWS SDK v3)中執行 DynamoDB 條件式寫入
條件式寫入是把 ConditionExpression 附加到 PutItem、UpdateItem 或 DeleteItem 上:DynamoDB 會對目前的項目評估它,只有在成立時才套用寫入 — 以 atomic 方式進行,沒有 read-modify-write 競爭。這是 DynamoDB 的樂觀鎖基本手法。本範例以版本檢查為一次更新加上守衛。
Code
import {DynamoDBClient, UpdateItemCommand} from '@aws-sdk/client-dynamodb';
const client = new DynamoDBClient({region: 'us-east-1'});
// Update the item only if nobody changed it since we read version 7.
const command = new UpdateItemCommand({
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'
});
try {
await client.send(command);
console.log('Updated to version 8');
} catch (err) {
if (err.name === 'ConditionalCheckFailedException') {
// With ReturnValuesOnConditionCheckFailure: 'ALL_OLD', the current item
// rides back on the exception — no extra read to see what beat you.
console.log('Lost the race — item is now:', err.Item);
} else {
throw err;
}
}說明
ConditionExpression— 與寫入以 atomic 方式一起對已儲存的項目檢查。可用的函式:attribute_exists、attribute_not_exists、attribute_type、contains、begins_with、size,以及比較運算子(=、<>、<、>、<=、>=、BETWEEN、IN)與AND/OR/NOT。- 兩個主力慣用手法:
- 在更新上使用
attribute_exists(#key)= 「只更新、絕不建立」。沒有它,對缺少的 key 執行UpdateItem會靜默建立該項目(意外 upsert 的 bug)。 - 在 put 上使用
attribute_not_exists(#key)= 「只建立、絕不覆寫」— 見 PutItem 頁面。
- 在更新上使用
- 樂觀鎖 — 讀取項目(版本 7),然後在寫入時以
#version = :expectedVersion檢查並把版本推進到 8。兩個並行的寫入者不可能都贏;輸家會拿到ConditionalCheckFailedException,接著重新讀取、在新版本上重試。 ReturnValuesOnConditionCheckFailure: 'ALL_OLD'— 把目前的項目放在例外上(err.Item,已 marshal),省下失敗檢查後的後續GetItem。它不消耗讀取容量;失敗的條件式寫入仍會對其寫入嘗試計費。- 這裡的一切都透過
ExpressionAttributeNames以別名表示(#version→Version),因此保留字絕不會咬人。
改用視覺化操作
條件運算式正是 DynamoDB Expression Builder 所建立的 — 選擇函式,取得運算式與 name/value map,形成可執行的程式碼。
想以產生且可審視的運算式編輯項目,而非手打的佔位符 — 下載 DynoTable。
相關範例
- 在 Python 中執行 DynamoDB 條件式寫入 — 以 boto3 執行相同的樂觀鎖。
- 使用 AWS CLI 執行 DynamoDB 條件式寫入 — 從 shell 執行相同的樂觀鎖。
- 在 Node.js 中使用 DynamoDB PutItem — 只建立的
attribute_not_existsput。 - DynamoDB 條件運算式 — 每個函式與其模式。
- 在多個屬性上強制唯一性 — 條件與交易的結合。
- DynamoDB ConditionalCheckFailedException — 當失敗的檢查在預期之內時,如何以低成本處理它。
References
- UpdateItem — Amazon DynamoDB API Reference
- Condition expressions — Amazon DynamoDB Developer Guide
- DynamoDB read and write operations (capacity unit consumption) — Amazon DynamoDB Developer Guide
最後驗證於 2026-07-13,對照上方連結的 AWS 官方文件。