« Back to Index

DynamoDB Update Document

View original Gist on GitHub

DynamoDB Update Document.rb

require "aws-sdk"
require "thread" # for Mutex

class DynamoTest
  attr_reader :table_name, :client
  
  def initialize
    @mutex      = Mutex.new
    @client     = AWS::DynamoDB::Client::V20120810.new
    @table_name = "foo"
    
    put_stuff
  end
  
  def put_stuff(ident, value) # value == "my_content"
    current_sequence = sequence_for(ident) # ident == "my_primary_key"
    
    @mutex.synchronize do
      client.put_item({
        :table_name => table_name,
        :item => {
          'key' => {
            'S' => ident
          },
          'value' => {
            'N' => value.to_s
          }
        },
        # The conditions of our "put" operation:
        # If the "key" isn't NULL (i.e. it exists) then our condition has failed
        # This means we only want to put the item if it doesn't already exist
        # Also, The "value" we're putting needs to be a numeric value greater than the current sequence value.
        :expected => {
          'key' => {
            :comparison_operator => 'NULL'
          },
          'value' => {
            :comparison_operator => 'GE',
            :attribute_value_list => [
              { 'N' => current_sequence.to_s }
            ]
          }
        },
        :conditional_operator => 'OR'
      })
    end
  end
  
  def sequence_for(ident)
    data = client.get_item(
      item_payload(ident)
    )

    data.length > 0 ? data[:item]["value"][:n].to_i : 0
  end
  
  def item_payload(ident)
    {
      :table_name => table_name,
      :key => {
        'key' => {
          'S' => ident.to_s
        }
      }
    }
  end
end