我想使用等效于 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中的项目。
您应该在表上创建一个全局二级索引,以使用KeyConditionExpression
query
以123
开头的项目。
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
。