Skip to content

Instantly share code, notes, and snippets.

@carlows
Forked from kenoir/dynamo_db_query_example.md
Created March 30, 2017 19:34
Show Gist options
  • Select an option

  • Save carlows/08211ce2ec0c68bb24b07265c45d02ca to your computer and use it in GitHub Desktop.

Select an option

Save carlows/08211ce2ec0c68bb24b07265c45d02ca to your computer and use it in GitHub Desktop.
Prettied up some AWS Ruby SDK DynamoDB examples from @Integralist.

AWS query-instance_method docs

export AWS_ACCESS_KEY_ID=‘XXXX’
export AWS_SECRET_ACCESS_KEY=‘XXXX’
# ENV['AWS_ACCESS_KEY_ID']
# ENV['AWS_SECRET_ACCESS_KEY']

require 'aws-sdk'
dynamo_db = AWS::DynamoDB.new

# Create table
foobar = dynamo_db.tables.create(
  'foobar', 10, 5, 
  :hash_key => { 
    :component_id => :string 
  }, 
  :range_key => { 
    :opts_hash => :string }
)

foobar.status # => :creating
foobar.status # => :active (takes ~15 seconds)
foobar.hash_key # => <AWS::DynamoDB::PrimaryKeyElement:0x60cd375d @name="component_id", @type=:string>
foobar.range_key # => <AWS::DynamoDB::PrimaryKeyElement:0x48774b2c @name="opts_hash", @type=:string>

# Create Item
item1 = foobar.items.create(
  :component_id => '1', 
  :opts_hash => 'abc'
) 
# => <AWS::DynamoDB::Item table_name:foobar hash_value:1 range_value:abc>

# Retrieve Items
foobar.items # => <AWS::DynamoDB::ItemCollection>
foobar.items.each { |item| puts item.range_value } 
# => abc, def

item2 = foobar.items.create(:component_id => '1', :opts_hash => 'def')
foobar.items.each { |item| puts item.hash_value } 
# => 1, 1

# Delete Tables
dynamo_db.tables.each {|x| if x.name == foobar then x.delete end }

# Query Tables
client = AWS::DynamoDB::Client::V20120810.new
client.query({ 
  :table_name => 'foobar', 
  :key_conditions => { 
    :component_id => { 
      :comparison_operator => 'EQ', 
      :attribute_value_list => [
        { 's' => '1' }
      ]
    } 
  } 
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment