这是从 DynamoDB 表中扫描和删除所有项目的代码,但我不确定如果您想从表中删除所有项目,为什么不能删除表并重新创建。
请注意,除非您有一些非常具体的用例,否则这不是推荐的方法。当代码从表中读取项目然后删除项目时,这将花费您。
代码:-
您可能需要更改以下代码中的表名和键值。在下面的代码中,使用的表名是files
,其键值为fileName
。
如果您同时拥有分区键和排序键,则需要设置这两个值。该files
表只有分区键。
#! /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