Skip to content

Instantly share code, notes, and snippets.

@damien-monni
Created February 21, 2020 13:59
Show Gist options
  • Save damien-monni/954be06ca364c823802dae0b5e00e0f3 to your computer and use it in GitHub Desktop.
Save damien-monni/954be06ca364c823802dae0b5e00e0f3 to your computer and use it in GitHub Desktop.
Delete all item from a DynamoDB table
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1' });
const getAllItemFromTable = async (table) => {
let ExclusiveStartKey;
let items = [];
do {
const params = { TableName: table };
if (ExclusiveStartKey) {
params.ExclusiveStartKey = ExclusiveStartKey;
}
const response = await docClient.scan(params).promise();
items = [...items, ...response.Items];
ExclusiveStartKey = response.LastEvaluatedKey;
} while (ExclusiveStartKey);
return items;
};
const deleteItemsFromTable = async (table, items) => {
for (let i = 0; i < items.length; i += 25) {
const sliced = items.slice(i, i + 25);
const requests = sliced.map((item) =>
({
DeleteRequest: {
Key: {
pk: item.pk,
sk: item.sk,
},
},
}),
);
try {
await docClient
.batchWrite({
RequestItems: {
[table]: requests,
},
})
.promise();
console.log(`Success delete from ${i} to ${i + sliced.length - 1}`);
} catch (err) {
console.log(err);
}
}
};
const TABLE_NAME = 'MY_TABLE_NAME';
const deleteAllItems = async () => {
const items = await getAllItemFromTable(TABLE_NAME);
await deleteItemsFromTable(TABLE_NAME, items);
}
deleteAllItems();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment