Skip to content

Instantly share code, notes, and snippets.

@macintux
Created January 13, 2014 03:37
Show Gist options
  • Save macintux/8394348 to your computer and use it in GitHub Desktop.
Save macintux/8394348 to your computer and use it in GitHub Desktop.
Utility functions for Erlang-based Riak demos. These ignore error handling and use strings instead of binaries for readability. Using the anonymous functions makes for a cleaner read.
%% Useful in Erlang shell. These assume an already-defined handle named "Riak"
Get = fun(X, Y) -> helpers:get(Riak, X, Y) end.
RawGet = fun(X, Y) -> helpers:raw_get(Riak, X, Y) end.
Put = fun(X) -> helpers:put(Riak, X) end.
Update = fun(X, Y, Z) -> helpers:update(Riak, X, Y, Z) end.
Resolve = fun(X, Y) -> helpers:update(Riak, X, Y) end.
New = fun(X, Y, Z) -> helpers:new(X, Y, Z) end.
%% Add an object to Riak and retrieve it:
%% 8> Object = New("legacy", "breakfast", "bacon & eggs"),
%% 8> Put(Object).
%% ok
%% 9> Get("legacy", "breakfast").
%% ["bacon & eggs"]
%% Pull vector clock from <<"groceries">>/<<"breakfast">> object already in Riak and use its vector clock to resolve any siblings:
%% Object = RawGet("groceries", "breakfast"),
%% Resolve(Object, "pancakes, bacon & eggs, and orange juice").
%% Could/should abstract away the New/Put cycle by defining Store("bucket", "key", "value")
-module(helpers).
-compile(export_all).
raw_get(Riak, Bucket, Key) ->
{ok, Obj} = riakc_pb_socket:get(Riak, l2b(Bucket), l2b(Key)),
Obj.
get(Riak, Bucket, Key) ->
{ok, Obj} = riakc_pb_socket:get(Riak, l2b(Bucket), l2b(Key)),
lists:map(fun(X) -> binary_to_list(X) end, riakc_obj:get_values(Obj)).
update(Riak, Bucket, Key, Value) ->
{ok, Obj} = riakc_pb_socket:get(Riak, l2b(Bucket), l2b(Key)),
update(Riak, Obj, Value).
update(Riak, Object, Value) ->
helpers:put(Riak,
riakc_obj:set_vclock(
replace(Object, Value),
riakc_obj:vclock(Object))).
l2b(String) ->
unicode:characters_to_binary(String).
replace(Object, Value) ->
new(riakc_obj:bucket(Object), riakc_obj:key(Object), l2b(Value)).
new(Bucket, Key, Value) when is_list(Bucket) ->
riakc_obj:new(l2b(Bucket), l2b(Key), l2b(Value));
new(Bucket, Key, Value) ->
riakc_obj:new(Bucket, Key, Value).
put(Riak, Bucket, Key, Value) ->
{ok, Obj} = new(Bucket, Key, Value),
riakc_pb_socket:put(Riak, Obj).
put(Riak, Object) ->
riakc_pb_socket:put(Riak, Object).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment