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]
テーブル生成
このめんどくさいオプション指定なんとかならんのか。
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
ddb.put_item(
table_name: 'table_name',
item: {
user_id: "1001",
name: "John",
age: 14,
birthday: "2000-01-01"
}
)
GET ITEM
result = ddb.get_item(
table_name: 'table_name',
key: {
user_id: "1001"
}
)
result.item.each do |key, value|
puts "#{key}: #{value}"
end
SCAN
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
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
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 の方には見やすくサンプルも載ってて、ものすごい徒労感。