簡體   English   中英

如何創建或更新同一DynamoDb項目?

[英]How to create or update the same DynamoDb item?

我正在使用節點aws-sdk,已經實現了一種在DynamoDb中創建或更新項目的方法。

它可以根據鍵(Id)正常運行,並且可以創建或更新項目。

我的參數如下:

  let params = {
    TableName: TableName,
    Key: {
      key: args.key
    },
    UpdateExpression: `set 
        userKey = :userKey,
        content = :content`,
    ExpressionAttributeValues: {
      ':userKey': args.userKey,
      ':content': args.content
    },
    ExpressionAttributeNames: { 
    }
  };

從那時起,我意識到我需要有條件地檢查更新中的輔助密鑰,以確保userKey匹配。

所以我補充說:

    ConditionExpression: 'userKey = :userKey',

現在,由於條件失敗,創建不起作用,在一條語句中進行創建和條件更新的正確方法是什么?

我的表定義如下:

AttributeDefinitions:
      - AttributeName: key
        AttributeType: S
      - AttributeName: userKey
        AttributeType: S
      - AttributeName: timestamp
        AttributeType: N
    KeySchema:
      - AttributeName: key
        KeyType: HASH

您有兩種選擇-

如果您的userKey實際上是表的排序鍵( https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html ),則可以這樣更改參數:

Key: {
  key: args.key
  userKey: args.userKey
}

但是,如果userKey只是另一個屬性,則可以這樣擴展條件表達式:

ConditionExpression: 'userKey = :userKey OR attribute_not_exists(userKey)'

這將要求這些 userKey匹配正是您期望,或者說,它沒有被設置在所有(這將是上UPSERT的情況下)。

注意-這允許您使用沒有userKeykey來更新項目。 如果您對此擔心,則可以將條件擴展為:

ConditionExpression: 'userKey = :userKey OR(attribute_not_exists(key) AND attribute_not_exists(userKey))'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM