這是從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
你以爲我知道表名,而我想刪除所有表中的所有記錄。我將發佈我最終使用的腳本。 – duduamar