Datastores with ruby: Redis and Ohm (part 1)

(30.04.2010)

Once upon a time there were only “relational” data bases (Oracle, MySQL, Postgres, etc etc etc). Nowadays there is a lot of rumors about “key-value” stores, and to be honest it is not only “rumor”/noise but some big provider and IT companies are seriously considering them in order to improve their own overall performance and capabilities.

In this post I’d like to explore a little on Redis and in particular on Ohm a ruby gem that aims to create persistent models on Redis.

First, let’s install Redis on our Linux box (on Mac OS X it should be more or less the same, on Windows I simply don’t care :)).

$ wget http://redis.googlecode.com/files/redis-1.2.6.tar.gz
$ tar -zxvf ./redis-1.2.6.tar.gz
$ cd redis-1.2.6
$ make

Then, after some seconds the package is compiled, it consists of these executable files:

We need only the first one (maybe the second too if you want to explore a little the insight of Redis…). So let’s start the Redis server:

$ redis-server start

and then server is listening to 6379 port.

Now it’s time to write some ruby code in order to have some “models” and store them in Redis. For this purpose we use Ohm:

require 'rubygems'
require 'ohm'
require 'pp'

class Post < Ohm::Model
  attribute :title
  attribute :body

  index :title
end

Ohm.connect(:db => 0)

p = Post.create :title => 'My first post here', :body => 'lorem ipsum...bla bla bla'
pp p

Ohm.flush

Each model we define sub-classing Ohm::Model can have some attributes we have to define; each attribute stores a ‘String’.

When running we obtain this output:

#<Post:1 title="My first post here" body="lorem ipsum...bla bla bla">

the ‘1’ after ‘#<Post:’ is the id assigned by Redis to the object p.

Notice that in order to be “found” by some attribute, we have to define an index to that attribute (title in out example), otherwise we’ll be unable to find a post by its title.

Post.find(:title => 'My first post here')
#<Set (Post): [#<Post:1 title="My first post here" body="lorem ipsum...bla bla bla">]>

Also notice it returns a set of objects.

To connect to the Redis server we use Ohm.connect method, by optionally specifing the DB number: each database has its own number that identifies it.

Ok, I hope I whet your appetite…let’s continue on a following post ;)



Comments

(Comments)
blog comments powered by Disqus