Storing Images in Riak from Rails

noSQL, Riak Add comments

Storing images in a noSQL database might be a good approach for many applications, and it can alleviate many replication and scalability issues when it comes to images and by extension other binary files.

Riak can store any kind of data, including binary. Whatever you can turn into an Erlang tuple can be stored, without the 4MB document size limitation of MongoDB or the “attachment”-model of CouchDB.

First, ripple has to be installed, the “official” Ruby driver for Riak:

sudo gem install ripple

Then require it in environment.rb of your Rails app:

config.gem ‘ripple’

This gem will pull some dependencies, namely activesupport-3.x and also activemodel. To continue working with Rails 2.3.5 without these beta gems, first uninstall them:

sudo gem uninstall activesupport –version ’3.0.0.beta3′

sudo gem uninstall activemodel

You will now get

no such file to load — active_support/i18n

when trying to start the server.

Sean is in the process of splitting the ripple gem into the ‘riak’ and ‘ripple’ (OM) parts to make the ‘riak’ part compatible with Rails 2.3.5., but for now you could either unpack the gem into vendor/gems (Google is your friend), or patch the offending file (your path may be different):

/usr/local/lib/ruby/gems/1.8/gems/ripple-0.6.1/lib/riak/i18n.rb:14

By simply changing

require ‘active_support/i18n’

to

require ‘i18n’

Now script/console or script/server will still give a bunch of warnings but the app should start.

Finally, here’s the snippet to store an image in riak:

require ‘riak’
client = Riak::Client.new
bucket = client.bucket(“my_image_store”)
object = Riak::RObject.new(bucket, “elephant_in_room.jpg”)
object.content_type = “image/jpeg”
fi = File.new(“/path/to/elephant.jpg”, “r”)
object.data = fi
object.store

Now point your browser to

http://127.0.0.1:8098/riak/my_image_store/elephant_in_room.jpg

and there is your image, just as you read it from disk.

Note the structure of the URL

http://127.0.0.1:8098/riak/<bucket_name>/<key_name>

and behold the simplicity and predictability of an HTTP/REST API. Accessing data really becomes a “no-brainer”. Riak of course vastly expands on this concept with links.

Surely you’ll want to embed the image in a larger document but this snippet might help you to get started.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

2 Responses to “Storing Images in Riak from Rails”

  1. Joshua Partogi Says:

    Hi,

    Thanks for this. I was wondering though, have you been able to get the file by calling the robject instead of using the Riak REST API?

    Many thanks for the tutorial.

  2. dirk Says:

    @Joshua:
    Thanks for your comment. I usually issue a GET, I’ll post here once I’ve tried other ways.

Leave a Reply