Getting Started:
CRUD Operations with Ruby

Creating Objects In Riak

First, let’s create a few objects and a bucket to keep them in.

my_bucket = client.bucket("test")

val1 = 1
obj1 ='one') = val1

In this first example we have stored the integer 1 with the lookup key of one. Next, let’s store a simple string value of two with a matching key.

val2 = "two"
obj2 ='two') = val2

That was easy. Finally, let’s store a bit of JSON. You will probably recognize the pattern by now.

val3 = { myValue: 3 }
obj3 ='three') = val3

Reading Objects From Riak

Now that we have a few objects stored, let’s retrieve them and make sure they contain the values we expect.

fetched1 = my_bucket.get('one')
fetched2 = my_bucket.get('two')
fetched3 = my_bucket.get('three') == val1 == val2 == val3.to_json

That was easy. we simply request the objects by key. in the last example, we converted to JSON so we can compare a string key to a symbol key.

Updating Objects In Riak

While some data may be static, other forms of data may need to be updated. This is also easy to accomplish. Let’s update the value of myValue in the 3rd example to 42.["myValue"] = 42

Deleting Objects From Riak

As a last step, we’ll demonstrate how to delete data. You’ll see that the delete message can be called either against the bucket or the object.


Working With Complex Objects

Since the world is a little more complicated than simple integers and bits of strings, let’s see how we can work with more complex objects. Take, for example, this Ruby hash that encapsulates some knowledge about a book.

book = {
  :isbn => '1111979723',
  :title => 'Moby Dick',
  :author => 'Herman Melville',
  :body => 'Call me Ishmael. Some years ago...',
  :copies_owned => 3

All right, so we have some information about our Moby Dick collection that we want to save. Storing this to Riak should look familiar by now.

books_bucket = client.bucket('books')
new_book =[:isbn]) = book

Some of you may be thinking, “But how does the Ruby Riak client encode/decode my object?” If we fetch our book back and print the raw data, we shall know:

fetched_book = books_bucket.get(book[:isbn])
puts fetched_book.raw_data

Raw Data:

{"isbn":"1111979723","title":"Moby Dick","author":"Herman Melville",
"body":"Call me Ishmael. Some years ago...","copies_owned":3}

JSON! The Ruby Riak client will serialize objects to JSON when it comes across structured data like hashes. For more advanced control over serialization you can use a library called Ripple, which is a rich Ruby modeling layer over the basic riak client. Ripple falls outside the scope of this document but we shall visit it later.

Now, let’s clean up our mess: