仅当密钥不存在时如何插入到 DynamoDb [英] How to insert to DynamoDb just if the key does not exist
问题描述
我只想向 DynamoDb 添加 id + 一些值.如果 id 已经存在,它应该什么都不做或更新
I want to add id + some values to a DynamoDb just once. If the id exists already it should do nothing or update
我可以去
search
if not found > insert
if found > do nothing or update (for now do nothing is fine)
但希望有更好的方法来做到这一点.id 应该是检查的关键.
But hopfully there is a better way to do it. The id should be the key to check for.
这是节点中的代码:
const dynamodbParams = {
TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
Item: {
id: userId,
createdAt: timestamp
},
};
dynamoDb.put(dynamodbParams).promise()
.then(data => {
console.log('saved: ', dynamodbParams);
})
.catch(err => {
console.error(err);
});
我在 yml 中使用它.不知道 yml 中是否有设置的选项
I use this in yml. Don't know if there are options to set this up in yml
resources:
Resources:
DynamoDbTableExpenses:
Type: 'AWS::DynamoDB::Table'
DeletionPolicy: Retain
Properties:
AttributeDefinitions:
-
AttributeName: id
AttributeType: S
-
AttributeName: createdAt
AttributeType: N
KeySchema:
-
AttributeName: id
KeyType: HASH
-
AttributeName: createdAt
KeyType: RANGE
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: ${self:provider.environment.DYNAMODB_TABLE_BLICKANALYTICS}
推荐答案
您可以用一个 UpdateItem 操作:
You can do the whole thing with a single UpdateItem operation:
const dynamodbParams = {
TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
Key: {id: userId},
UpdateExpression: 'SET createdAt = if_not_exists(createdAt, :ca)',
ExpressionAttributeValues: {
':ca': {'S': timestamp}
}
};
dynamoDb.updateItem(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
console.log(data);
}
}
如果您只想在不存在时插入,您可以使用 PutItem:
If you only want to do insert if not exists, you can easily do that with PutItem:
const dynamodbParams = {
TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
Item: {
id: userId,
createdAt: timestamp
},
ConditionExpression: 'attribute_not_exists(id)'
};
dynamodb.putItem(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
console.log(data);
}
}
注意我还没有完全测试代码,所以如果有任何错误请评论,但它应该可以工作.
Note I have not fully tested the code, so please comment if there's any error, but it should work.
这篇关于仅当密钥不存在时如何插入到 DynamoDb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!