Here is the code to scan and delete all the items from DynamoDB table though I am not sure why can't you delete the table and recreate if you would like to delete all the items from a table.
Please note that this is not a recommended approach unless you have some very specific use case. This would cost you as the code reads the item from table and then delete the item.
Code:-
You may need to change the table name and key value in the below code. In the below code, the table name used is files
and its key value is fileName
.
If you have both partition key and sort key, then you need to set both the values. The files
table has only partition key.
#! /usr/bin/ruby
require "aws-sdk-core"
# Configure SDK
# use credentials file at .aws/credentials
Aws.config[:credentials] = Aws::SharedCredentials.new
Aws.config[:region] = "us-west-2"
# point to DynamoDB Local, comment out this line to use real DynamoDB
Aws.config[:dynamodb] = { endpoint: "http://localhost:8000" }
dynamodb = Aws::DynamoDB::Client.new
tableName = "files"
scanParams = {
table_name: tableName
}
puts "Scanning files table."
begin
loop do
result = dynamodb.scan(scanParams)
result.items.each{|files|
puts "Item :" + "#{files}"
puts "Going to delete item :" + "#{files["fileName"]}"
deleteParams = {
table_name: tableName,
key: {
fileName: files["fileName"]
}
}
begin
deleteResult = dynamodb.delete_item(deleteParams)
puts "Deleted item." + files["fileName"]
rescue Aws::DynamoDB::Errors::ServiceError => error
puts "Unable to delete item:"
puts "#{error.message}"
end
}
break if result.last_evaluated_key.nil?
puts "Scanning for more..."
scanParams[:exclusive_start_key] = result.last_evaluated_key
end
rescue Aws::DynamoDB::Errors::ServiceError => error
puts "Unable to scan:"
puts "#{error.message}"
end