Recently, I figured out how to use secondary indices in Riak using the Erlang client and am documenting its usage here for the benefit of future end-users. Secondary indices provide a way to query for sets of bucket/key pairs stored in Riak. The sets are defined by either a value or range of values on a specified index. The index can be attached to any riakc_obj prior to a put operation as metadata. Secondary indices are fast, and the preferable way to group associated data if complex operations don’t need to be performed on the contents of the value (for this purpose, there is map-reduce).
First, you’ll want to change the backend storage of Riak to LevelDB. The default bitcask storage option will complain that secondary indices are not supported. Incidentally, swapping storage solutions can be done at runtime, since Riak itself handles primarily the distribution of data, node failover, and the Dynamo principles.
To do this, find the
app.config file in the
etc folder of your
riak build. If you compiled Riak from source using
make rel, this
file will be in
rel/riak/etc. Find the lines:
and change it to
Restarting Riak at this point will change the storage backend on the fly. Note that any data you had in bitcask is not gone, but persisted in a different place on the disk (the paths to these locations are elsewhere in the same config file)
At this point, lets create a few sample indexed objects:
1 2 3 4 5 6 7 8 9 10
Here, I have inserted two objects into Riak, each representing a different employee. I have also inserted them with metadata about their age and state of residence. Note that object metadata is represented as a dictionary in Erlang. To query the data, I can do something like:
The first query will return a list of a single item:
[<<"employee">>, <<"jeremy">>]. The second will return a list of two
[<<"employee">>, <<"jeremy">>] and
[<<"employee">>, <<"helena">>]. Note that the field names of the
index must have either
_int as a suffix to denote the
type of field the index is. At this time, only binary and integer data
can be used to index objects.
And that’s a wrap! In your own applications, you might want to consider grabbing an object’s metadata first before updating it so you don’t wipe out existing metadata. If you are still reading at this point, I hope you found this helpful. I would encourage experienced Riak users (or anybody really) to point out any errors I might have made so I can fix them for the good of the community. Thanks for reading.