Search code examples
rubyamazon-web-servicesamazon-dynamodbaws-sdk-ruby

Delete all items in DynamoDB table using Ruby


I'm trying to write a simple ruby script that delete all items in a DynamoDB table, but I'm having trouble understand which argument to pass to "delete_items", this is what I have so far:

dynamoDB = Aws::DynamoDB::Resource.new(region: 'us-west-2')

dynamoDB.tables.each do |table|
  puts "Table #{table.name}"
  scan_output = table.scan({
    select: "ALL_ATTRIBUTES"
    })

  scan_output.items.each do |item|
    keys = item.keys
    table.delete_item({
      key: ???
    })
  end
end 

I tried passing the item, or item.keys - both did not work.

Thanks!


Solution

  • I eventually wrote this script which delete all records from all tables (not very useful for most cases, but for mine it was exactly what I needed, as I was using it in a dedicated testing account):

    #!/usr/bin/env ruby
    
    require 'aws-sdk'
    
    dynamoDB = Aws::DynamoDB::Resource.new(region: 'us-west-2')
    
    dynamoDB.tables.each do |table|
      puts "Table #{table.name}"
      scan_output = table.scan({
        select: "ALL_ATTRIBUTES"
        })
    
      scan_output.items.each do |item|
        item_key = Hash.new
        table.key_schema.each do |k|
          item_key[k.attribute_name] = item[k.attribute_name]
        end
        table.delete_item({
          key: item_key
        })
      end
    end