Skip to content

Instantly share code, notes, and snippets.

@kenjij
Created October 5, 2021 00:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenjij/d432876393b207114e6fca95965bcdc1 to your computer and use it in GitHub Desktop.
Save kenjij/d432876393b207114e6fca95965bcdc1 to your computer and use it in GitHub Desktop.
AWS DynamoDB batch write (put) in Ruby, ideally use in Lambda
require 'aws-sdk-dynamodb'
# DynamoDB batch write (put) routine
# @param items [Array<Hash>] DynamoDB items to put
# @param table [String] DynamoDB table name
def ddb_batch_put(items, table)
ddb = Aws::DynamoDB::Client.new
batch = items.map { |item| {put_request: {item: item}} if Hash === item }
batch.compact!
puts "Batch write to: #{table}, #{batch.length} items."
batch = {table => batch}
while batch
resp = ddb.batch_write_item({request_items: batch })
if resp.unprocessed_items.length > 0
batch = resp.unprocessed_items
puts "Unprocessed: #{batch}"
else
batch = nil
puts 'Batch write complete.'
end
end
true
rescue => e
puts "ddb_batch_put error: #{e.message}"
puts e.backtrace.join("\n")
false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment