Skip to content

Instantly share code, notes, and snippets.

@derwiki
Created November 11, 2020 02:18
Show Gist options
  • Save derwiki/c918d5f2a82e42bd0f7b485145e5c0e4 to your computer and use it in GitHub Desktop.
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
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