Monday, 26 January 2009

Start using Amazon SimpleDB with ruby in 10 minutes

The information in this post is outdated, if you want a better complete overview of the SimpleDB ruby libraries you should read this article

Out there you can already find more than one project that lets you access Amazon SimpleDB using ruby.

Since I wasn't really happy with any of them I started building my solution on top of aws-sdb.
Being really bad at naming projects I named my gem dead_simple_db.

To install the gem just type in your console


sudo gem install hungryblank-dead_simple_db -s http://gems.github.com


Here's how you can use it.


require 'rubygems'
require 'dead_simple_db'

#you need your Amazon AWS credentials defined in the environment

ENV['AMAZON_ACCESS_KEY_ID'] = 'your access key'
ENV['AMAZON_SECRET_ACCESS_KEY'] = 'your secret access key'

#Let's define a class that will use SimpleDb backend to store the instances

class Client < DeadSimpleDb::Base

#Let's define the SimpleDb domain where the class will be stored
domain 'test_domain'

#Add the definitions of the attributes we need to store
attr_sdb :first_name, 'String'
attr_sdb :last_name, 'String'
attr_sdb :budget, 'Integer', :digits => 9
attr_sdb :first_purchase, 'Time'

end

#and now is time to create the first object

c = Client.new
c.first_name = "Henry"
c.last_name = "Chinaski"
c.budget = 1000
c.first_purchase = Time.now

# that's how you save your first record on Amazon SimpleDB

c.save

# and that's how you fetch it

henry = Client.find(:first, "['first_name' = 'Henry']")
puts henry.first_name


Now this might be not exciting but it's been pretty easy, if you've time you can check that


henry.first_purchase


Is actually a Time object and not a string, dead_simple_db does the type casting for you so you don't have to worry if SimpleDb can store only strings.
For a similar reason the budget attribute has been defined with 9 digits, on the SimpleDB backend 1000 is stored ad "000001000" to allow the sorting as string to work properly with numbers.

Note that dead_simple_db always stores in the records a 'class_name' attribute with the name of the class the record refers to, this allow you to store more than one class in the same domain.

If you do store multiple classes in one domain, please remember to add the class_name to your queries to avoid weird results!

So here you go you have no more excuses to not take a look a SimpleDB, is free and now it's simple to access it in a way that makes instantly sense.

Planned improvements on the short term are


  • Return query results with over 250 elements

  • Introduce support to QueryWithAttributes in find

  • Automatically add class_name filter to queries

1 comment:

Michael Sheakoski said...

Have you tried Right AWS? Of all the AWS gems this one works the best for me and is updated often. They also have an ActiveRecord-like interface for SimpleDB called ActiveSDB (currently in alpha status). http://rightaws.rubyforge.org/