Created
November 11, 2020 02:18
-
-
Save derwiki/c918d5f2a82e42bd0f7b485145e5c0e4 to your computer and use it in GitHub Desktop.
Function that uses batch_writer to efficiently(-ish) delete all of the entries in a DynamoDB table
This file contains hidden or 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
import boto3 | |
dynamo = boto3.resource('dynamodb') | |
def truncate_table(table_name): | |
table = dynamo.Table(table_name) | |
table_key_names = [key.get("AttributeName") for key in table.key_schema] | |
response = table.scan(ProjectionExpression=", ".join(table_key_names) | |
data = response.get('Items') | |
while 'LastEvaluatedKey' in response: | |
response = table.scan(ProjectionExpression=ProjectionExpression, ExclusiveStartKey=response['LastEvaluatedKey']) | |
data.extend(response['Items']) | |
with table.batch_writer() as batch: | |
for each in data: | |
result = batch.delete_item( | |
Key={key: each[key] for key in table_key_names} | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment