Edited at

AWS SDK for Ruby v2 で DynamoDBを使う

More than 3 years have passed since last update.

Class: Aws::DynamoDB::Client — AWS SDK for Ruby V2


Gemfile

source 'https://rubygems.org'

gem 'aws-sdk-core'


インスタンスの生成

v1 は AWSだったのが、v2 ではAws と小文字になった模様。ややこし!

#!/usr/bin/ruby

require 'aws-sdk-core'

ddb = Aws::DynamoDB::Client.new(
endpoint: 'http://localhost:8000',
region: 'ap-northeast-1'
)


サポートされているオペレーション

pp ddb.operation_names

[:batch_get_item, :batch_write_item, :create_table, :delete_item, :delete_table, :describe_table, :get_item, :list_tables, :put_item, :query, :scan, :update_item, :update_table]


テーブル生成

このめんどくさいオプション指定なんとかならんのか。

http://docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html#create_table-instance_method


options = {
table_name: "table_name",
key_schema: [
{
attribute_name: "user_id",
key_type: "HASH"
},
{
attribute_name: "timestamp",
key_type: "RANGE"
}
],
attribute_definitions: [
{
attribute_name: "user_id",
attribute_type: "S"
},
{
attribute_name: "timestamp",
attribute_type: "N"
}
],
provisioned_throughput: {
read_capacity_units: 1,
write_capacity_units: 1
},
global_secondary_indexes: [
{
index_name: "sex-idx",
key_schema: [
{
:attribute_name => "sex",
:key_type => "HASH"
},
],
projection: {
projection_type: "ALL",
},
provisioned_throughput: {
read_capacity_units: 1,
write_capacity_units: 1
}
}
]
}

ddb.create_table(options)


テーブル一覧

result = ddb.list_tables

result.table_names.each do |table|
puts table
end


PUT ITEM

http://docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html#put_item-instance_method

ddb.put_item(

table_name: 'table_name',
item: {
user_id: "1001",
name: "John",
age: 14,
birthday: "2000-01-01"
}
)


GET ITEM

http://docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html#get_item-instance_method

result = ddb.get_item(

table_name: 'table_name',
key: {
user_id: "1001"
}
)

result.item.each do |key, value|
puts "#{key}: #{value}"
end


SCAN

http://docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html#scan-instance_method

result = ddb.scan(

table_name: 'table_name'
)

result.items.each do |item|
puts "-------------"
item.each do |key, value|
puts "#{key}: #{value}"
end
end


UPDATE ITEM

http://docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html#update_item-instance_method

ddb.update_item(

table_name: 'table_name',
key: {"user_id" => "1001"},
attribute_updates: {
"name" => {
value: "Alice",
action: "PUT",
},
"age" => {
value: 20,
action: "PUT"
}
}
)


DELETE ITEM

http://docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html#delete_item-instance_method

ddb.delete_item(

table_name: 'table_name',
key: {"user_id" => "1001"}
)


つらい

最初、http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/DynamoDB/Client.html のページ見て、サンプルコードもないし、めちゃつらいと思ってちまちま試しながらこのページ書きだしたんだけど、

http://docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html の方には見やすくサンプルも載ってて、ものすごい徒労感。


参考