gpt4 book ai didi

node.js - 使用 Lambda 删除 Dynamodb 中的所有项目?

转载 作者:太空宇宙 更新时间:2023-11-04 00:08:22 25 4
gpt4 key购买 nike

使用 Lambda (node.js) - 如何删除 Dynamodb 表中的所有项目?

表中有 500K 行

我尝试使用扫描方法,然后循环遍历每个项目,然后使用删除方法。它最多只允许 3000 行。

代码

exports.handler = function(context, callback) {
getRecords().then((data) => {
data.Items.forEach(function(item) {
deleteItem(item.Id).then((data1) => {

});
});
});
};

var deleteItem = function(id) {
var params = {
TableName: "TableName",
Key: {
"Id": id
},
};

return new Promise(function(resolve, reject) {
client.delete(params, function(err, data) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}


function getRecords() {
var params = {
TableName: 'TableName',
IndexName: 'Type-index',
KeyConditionExpression: 'Type = :ty',
ExpressionAttributeValues: {
':ty': "1"
},
ProjectionExpression: "Id",
};

return new Promise(function(resolve, reject) {
client.query(params, function(err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}

最佳答案

已经有一个正确答案,但这里有另一个代码片段,用于从 Dynamo DB 中删除所有记录。

const AWS = require("aws-sdk");

AWS.config.update({
region: "us-east-1",
});

const docClient = new AWS.DynamoDB.DocumentClient();
const getAllRecords = async (table) => {
let params = {
TableName: table,
};
let items = [];
let data = await docClient.scan(params).promise();
items = [...items, ...data.Items];
while (typeof data.LastEvaluatedKey != "undefined") {
params.ExclusiveStartKey = data.LastEvaluatedKey;
data = await docClient.scan(params).promise();
items = [...items, ...data.Items];
}
return items;
};
const deleteItem = (table, id) => {
var params = {
TableName: table,
Key: {
id: id,
},
};

return new Promise(function (resolve, reject) {
docClient.delete(params, function (err, data) {
if (err) {
console.log("Error Deleting ", id,err);
reject(err);
} else {
console.log("Success Deleting ", id,err);
resolve();
}
});
});
};
exports.handler = async function (event, context, callback) {
try {
const tableName = "<table>";
// scan and get all items
const allRecords = await getAllRecords(tableName);
// delete one by one
for (const item of allRecords) {
await deleteItem(tableName, item.id);
}
callback(null, {
msg: "All records are deleted.",
});
} catch (e) {
callback(null, JSON.stringify(e, null, 2));
}
};

关于node.js - 使用 Lambda 删除 Dynamodb 中的所有项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51110377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com