Getting Started:
CRUD Operations with Python

Creating Objects In Riak

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

myBucket = myClient.bucket('test')

val1 = 1
key1 ='one', data=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"
key2 ='two', data=val2)

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

val3 = {"myValue": 3}
key3 ='three', data=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 = myBucket.get('one')
fetched2 = myBucket.get('two')
fetched3 = myBucket.get('three')

assert val1 ==
assert val2 ==
assert val3 ==

That was easy. We simply request the objects by 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

Nothing is complete without a delete. Fortunately, that’s easy too.


Now we can verify that the objects have been removed from Riak.

assert myBucket.get('one').exists == False
assert myBucket.get('two').exists == False
assert myBucket.get('three').exists == False

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 object 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:

booksBucket = myClient.bucket('books')
newBook =['isbn'], data=book)

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

fetchedBook = booksBucket.get(book['isbn'])


JSON! The Riak Python client library encodes things as JSON when it can.

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

If we wanted to get a deserialized object back we would just use the regular method.

Finally, let’s clean up our mess: