[英]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的情況下)。
注意-這將允許您使用沒有userKey
的key
來更新項目。 如果您對此擔心,則可以將條件擴展為:
ConditionExpression: 'userKey = :userKey OR(attribute_not_exists(key) AND attribute_not_exists(userKey))'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.