Last active
May 28, 2024 13:51
-
-
Save pushplay/d2cac7ca1a10a5a49f6947a02657a23a to your computer and use it in GitHub Desktop.
Delete all items (clear) in a DynamoDB table using bash
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
#!/bin/bash | |
TABLE_NAME=TableName | |
KEY=id | |
aws dynamodb scan --table-name $TABLE_NAME --attributes-to-get "$KEY" --query "Items[].id.S" --output text | tr "\t" "\n" | xargs -t -I keyvalue aws dynamodb delete-item --table-name $TABLE_NAME --key '{"id": {"S": "keyvalue"}}' |
Is there a way I can delete all items with different sort keys but the same PK?
That should be doable. Starting from @OtterFlip's work you'll want to replace the "dynamodb scan" with "dynamodb query" and add a "--key-condition-expression" to specify the value of your PK. Check out the docs for details on that.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@lqueryvg - Good point.
Here's a modified version of the above command line which will scan a dynamo table and delete each item in the table. It works for tables which have both a partition and a sort key.
This command uses an AWS CLI profile named "admin" so change it to whichever profile name works for you
This command assumes the partition and sort keys are both of Dynamo type "S" (string) and so alter the attribute types as needed
Change the values of these three enviornment variables to match your table name as well as the names of its partition and sort keys/columns/attributes
export DYNAMO_TABLE="MyTableName"
export DYN_HASH_KEY="MyPartitionKeyName"
export DYN_SORT_KEY="MySortKeyName"
In one command, delete all items in a dynamo table which has both partition and sort keys
aws --profile admin dynamodb scan --table-name ${DYNAMO_TABLE} --attributes-to-get "${DYN_HASH_KEY}" "${DYN_SORT_KEY}" --output text | awk -v DYNAMO_TABLE="$DYNAMO_TABLE" -v DYN_HASH_KEY="$DYN_HASH_KEY" -v DYN_SORT_KEY="$DYN_SORT_KEY" '/PK_HASH/{ HASH=$2; next } /PK_SORT/{ print "aws --profile admin dynamodb delete-item --table-name " DYNAMO_TABLE " --key "{\"" DYN_HASH_KEY "\": {\"S\": \"" HASH "\"},\"" DYN_SORT_KEY "\": {\"S\": \"" $2 "\"}}"\0" }' | xargs -t -0 bash -c
UPDATE: I just noticed that there's still a hard-coded attribute/column name that's not using DYN_HASH_KEY and DYN_SORT_KEY. My table's partition/hash and sort keys are named "PK_HASH" and "PK_SORT" - and you can see they're hard-coded in the above command. So it won't actually work for you unless you modify PK_HASH and PK_SORT to match your own table's hash and sort key names. I'll see if I can fix this, but I'm having difficulty with awk's conditional expressions accepting the awk environment variables in the comparison expression.