在 Node.js(AWS SDK v3)中執行 DynamoDB 條件式寫入

條件式寫入是把 ConditionExpression 附加到 PutItemUpdateItemDeleteItem 上: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_existsattribute_not_existsattribute_typecontainsbegins_withsize,以及比較運算子(=<><><=>=BETWEENIN)與 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 以別名表示(#versionVersion),因此保留字絕不會咬人。

改用視覺化操作

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

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

相關範例

References

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

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

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