LoginSignup
12
14

More than 5 years have passed since last update.

dynamoDBをrubyから操作してみる

Posted at

最近ビックデータに向けた流行? なのかRDBMSよりKVSに触れる機会が多くなってきており、
さっとrubyで(Railsで)扱いたいな〜って思ってたんだけど、
ruby + DynomoDBに関する日本語のサイトって少ないなって思い、
少し調べてみたので、簡単にやり方をまとめてみました。

■本家 aws-sdk dynamoDBクラスドキュメント
http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/DynamoDB.html

# encoding : utf-8
require "aws-sdk"
dynamo_db = AWS::DynamoDB.new(
  :access_key_id  => "AWS アクセスキー",
  :secret_access_key => "AWS シークレットキー",
  :dynamo_db_endpoint => "DynamoDB endpoint",
  :region => "DynamoDB region"
)

# create table 
table = dynamo_db.tables.create(
  'blog',1,2,  # table名,read capacity,write capacity
  :hash_key => {:id => :string},
  :range_key => {:user_id => :string}
)

# table count
p table.count

# Hash Key
puts table.hash_key.name
puts table.hash_key.type

# Range Key
puts table.range_key.name
puts table.range_key.type

# read capacity
puts table.read_capacity_units
# write capacity
puts table.write_capacity_units

while true
  puts table.status
  str = table.status.to_s
  if str == "active"
    break
  end
  sleep 3
end

# insert
table.items.create(
  'id' => '000000001',
  'user_id' => '000000001',
  'user_name' => 'kuwata',
  'blog_title' => 'apo',
  'blog_body' => 'apoapoapoapo...apo?'
)

# table item count
puts table.items.count

# item 全件の内容をハッシュで出力
table.items.each do |item|
  puts item.attributes.to_hash
end

table.items.create(
  'id' => '000000001',
  'user_id' => '000000002',
  'user_name' => 'hagakure',
  'blog_title' => 'dabe',
  'blog_body' => '模擬刀の先制攻撃だべ!!!'
)

# query
table.items.query(:hash_value => "000000001").each do |item|
  puts item.attributes.to_hash
end

# query count
puts table.items.query(:hash_value => "000000001").count

# table delete
table.delete

12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14