我对 AWS 很陌生,但我需要为 DynamoDB 表中的每个项目添加一个属性(并将值设置为某个值)。
我正在尝试编写一个通用脚本,该脚本能够对传递给它的任何表执行此操作。
经过一些挖掘,看起来我应该能够通过扫描表格,获取项目,然后更新每个项目来做到这一点。
我的问题是:
(1) 这看起来是一个合理的方法吗?
(2) 是否有更简单/更好的方法来自动执行此操作? (为表格中的每个项目在表格范围内添加一个属性?)
最佳答案
const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient({
region:'us-east-1'
});
async function main(event, context) {
let tableContents;
try{
//get items from dynamo
const params = {
TableName: `${YOUR_TABLE_NAME}`,
};
tableContents = await scanDB(params);
}catch(err){
console.log(err);
return err;
}
let calls = [];
tableContents.forEach(function(value){
let params = {
ExpressionAttributeValues: {
":newAttribute": false,
},
Key: {
"indexKey": value.indexKey
},
TableName: `${YOUR_TABLE_NAME}`,
UpdateExpression: "SET newAttribute = :newAttribute",
};
calls.push(dynamoDb.update(params).promise());
});
let response;
try{
response = await Promise.all(calls);
}catch(err){
console.log(err);
}
return response;
}
async function scanDB(params) {
let dynamoContents = [];
let items;
do{
items = await dynamoDb.scan(params).promise();
items.Items.forEach((item) => dynamoContents.push(item));
params.ExclusiveStartKey = items.LastEvaluatedKey;
}while(typeof items.LastEvaluatedKey != "undefined");
return dynamoContents;
};
main();
祝你好运!
关于amazon-dynamodb - 为包含数百万个项目的 DynamoDB 表中的每个项目添加一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55363323/