Created
December 24, 2020 07:43
-
-
Save daangemist/f24e3704adc53ba661d3163f4960e06c to your computer and use it in GitHub Desktop.
Empty an AWS DynamoDB table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('dotenv').config() | |
const AWS = require('aws-sdk'); | |
AWS.config.update({ | |
credentials: { | |
accessKeyId: 'xxx', | |
secretAccessKey: 'xxx' | |
}, | |
region: 'eu-central-1' | |
}); | |
const docClient = new AWS.DynamoDB.DocumentClient(); | |
const tableName = 'table-name'; | |
async function main() { | |
const request = { | |
TableName: tableName, | |
} | |
let itemCount = 1; | |
while (itemCount > 0) { | |
const result = await docClient.scan(request).promise(); | |
// the old, single item method, which takes way too long. | |
// for(let iter = result.Items.length-1; iter >= 0; iter--) { | |
// const item = result.Items[iter]; | |
// console.log('Deleting ' + item.email); | |
// await docClient.delete({ TableName: tableName, Key: { email: item.email}}).promise(); | |
// } | |
let deleteItems = []; | |
for(let iter = result.Items.length-1; iter >= 0; iter--) { | |
const item = result.Items[iter]; | |
deleteItems.push({ | |
DeleteRequest : { | |
Key : { | |
email : item.email, | |
} | |
} | |
}); | |
} | |
while(deleteItems.length > 0) { | |
const partitionedDeleteItems = deleteItems.slice(0,25); | |
deleteItems = deleteItems.slice(26); | |
const params = { | |
RequestItems : { | |
[tableName] : partitionedDeleteItems, | |
} | |
}; | |
const writeResult = await docClient.batchWrite(params).promise(); | |
console.log('Deleted', partitionedDeleteItems.map(item => item.DeleteRequest.Key.email )); | |
} | |
itemCount = result.Items.length; | |
} | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment