使用条件表达式更新 dynamoDB 列



我想使用等效于 sql 的条件更新 dynamoDB 表的现有项目 (%)

opIdUserId 状态

  • 123-U1 进行中
  • 345-U2 进行中
  • 123-U3 暂停

我的dynamodb中的opIdUserId是主分区键。我想将 opIdUserId 字段值的状态更新为 COMP,该字段值从 或包含 123 开始。

这是我目前正在尝试的,但研究并发现我无法使用KeyConditionExpression进行更新。

const AWS = require('aws-sdk'); 
const docClient = new AWS.DynamoDB.DocumentClient({region: 'eu-west-1'}); 
var table = "tablename";
exports.handler = function(event, context, callback){
var params = {
TableName: table,
KeyConditionExpression: "begins_with(opIdUserId, :i)",
UpdateExpression: "set operationStatus = :o",
ExpressionAttributeValues:{
":o":"COMP",
":i":"123-"
},
ReturnValues:"UPDATED_NEW"
};
docClient.update(params, function(err, data) {
if (err) {
callback(err, null);
} else {
callback(null,data); 
}
});
} 

请建议如何在特定条件下更新dynamoDB中的项目。

您应该在表上创建一个全局二级索引,以使用KeyConditionExpressionquery123开头的项目。

var params = {
TableName: table,
KeyConditionExpression: "id = :id AND begins_with(opIdUserId, :opIdUserId)",
UpdateExpression: "set operationStatus = :operationStatus",
ExpressionAttributeValues:{
":opIdUserId":"123-",
":id": "something"
}
};
var documentClient = new AWS.DynamoDB.DocumentClient();
documentClient.query(params, function(err, data) {
if (err) console.log(err);
else console.log(data);
});

请记住,您不能在partition key上使用BEGINS_WITH运行查询,只能在sort key上运行。

然后,您可以使用表的partition and sort key对每个元素使用update方法,更新operationStatus

如果您向我提供有关您的DynamoDB表的信息,我可以帮助您创建GSI

最新更新