Taste of Riak

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 record that encapsulates some information about a book.

Let's create a record for books:

> (defrecord book
    title
    author
    body
    isbn
    copies-owned)
()

Now, a book:

> (set hhgttg
    (make-book
      title "The Hitchhiker's Guide to the Galaxy"
      author "Douglas Adams"
      body "... And some said that even the trees had been a bad move ..."
      isbn "0-330-25864-8"
      copies-owned 42))
#(book
  "The Hitchhiker's Guide to the Galaxy"
  "Douglas Adams"
  "... And some said that even the trees had been a bad move ..."
  "0-330-25864-8"
  42)

So we have some information about our HHGTTG collection that we want to save. Storing this to Riak should look familiar by now. To make this clearer to read, we'll do it in stages, instead of all at once. First the basics:

> (set book-bucket (binary "books"))
#B(98 111 111 107 115)
> (set hhgttg-key (list_to_binary (book-isbn hhgttg)))
#B(48 45 51 51 48 45 50 53 56 54 52 45 56)

Now we can create the object:

> (set hhgttg-obj (lrico:new book-bucket hhgttg-key hhgttg))
#(riakc_obj
  #B(98 111 111 107 115)
  #B(48 45 51 51 48 45 50 53 56 54 52 45 56)
  undefined () undefined
  #(book
    "The Hitchhiker's Guide to the Galaxy"
    "Douglas Adams"
    "... And some said that even the trees had been a bad move ..."
    "0-330-25864-8"
    42))

With the object created, we can store it in Riak:

> (lric:put pid hhgttg-obj)
ok

Some of you may be thinking: “How does the Erlang Riak client encode/decode my object?” If we fetch our book back and print the value, we shall know:

> (set `#(ok ,fetched-book) (lric:get pid book-bucket hhgttg-key))
#(ok
  #(riakc_obj ...))

Now let's peek inside:

> (lfe_io:format "~p~n" `(,(lrico:get-value fetched-book)))
#B(131 104 6 100 0 4 98 111 111 107 107 0 36 84 104 101
   32 72 105 116 99 104 104 105 107 101 114 39 115 32 71
   117 105 100 101 32 116 111 32 116 104 101 32 71 97 108
   97 120 121 107 0 13 68 111 117 103 108 97 115 32 65 100
   97 109 115 107 0 61 46 46 46 32 65 110 100 32 115 111
   109 101 32 115 97 105 100 32 116 104 97 116 32 101 118
   101 110 32 116 104 101 32 116 114 101 101 115 32 104 97
   100 32 98 101 101 110 32 97 32 98 97 100 32 109 111 118
   101 32 46 46 46 107 0 13 48 45 51 51 48 45 50 53 56 54
   52 45 56 97 42)

Erlang binaries! The Riak Erlang client library encodes everything as binaries. This, in turn, gets passed on to the lric library. If we wanted to get a book object back we could use binary_to_term/1 to get our original object back:

> (binary_to_term (lrico:get-value fetched-book))
#(book
  "The Hitchhiker's Guide to the Galaxy"
  "Douglas Adams"
  "... And some said that even the trees had been a bad move ..."
  "0-330-25864-8"
  42)

Next, we'll tidy things up.