问题
I am wanting to implement a postcommit hook for riak that decrements a counter in a map in another bucket. However I am having a bit of trouble dealing with the riak datatypes.
Here is me attempting from riak console
:
(riak@127.0.0.1)9>{ok, C} = riak:local_client().
{ok,{riak_client,['riak@127.0.0.1',undefined]}}
(riak@127.0.0.1)10>{ok, Obj} = C:get({<<"product">>, <<"default">>}, <<"1">>).
{ok,{r_object,{<<"product">>,<<"default">>},
<<"1">>,
[{r_content,{dict,5,16,16,8,80,48,
{[],[],[],[],[],[],[],[],[],[],[],[],...},
{{[],[],[],[],
[[<<"dot">>|{<<"#\tþù"...>>,{...}}]],
[],[],[],[],[],...}}},
<<69,2,0,0,0,11,114,105,97,107,95,100,116,95,109,97,112,
77,1,...>>}],
[{<<35,9,254,249,108,41,151,242>>,{1,63593788980}}],
{dict,1,16,16,8,80,48,
{[],[],[],[],[],[],[],[],[],[],[],[],[],...},
{{[],[],[],[],[],[],[],[],[],[],[],...}}},
undefined}}
(riak@127.0.0.1)11> Mp = riak_object:get_value(O3).
<<69,2,0,0,0,11,114,105,97,107,95,100,116,95,109,97,112,
77,1,131,80,0,0,0,206,120,1,203,96,...>>
(riak@127.0.0.1)12> MpP = riak_dt_map:from_binary(Mp).
{error,invalid_binary}
product
bucket datatype is set to map
. Each object stored should have a counter called quantity
which I'd like to decrement.
However I cannot find any documentation or sample code dealing with datatypes in a pre or post commit context. (actually examples of any kind are few). I've been reading the source of riak_client and riak_dt_map but I am new to erlang so I'm making slow progress and would appreciate some help.
回答1:
The r_object that you have there does not directly hold a riak_dt_map, rather it holds a riak_kv_crdt that contains a riak_dt_map that in turn contains your counter.
To update the counter, you would need to first get the context from the map:
{{Context,_},_}=riak_kv_crdt:value(Obj,riak_dt_map).
Then build the operation to increment the counter named <<"name">> in the map contained in the CRDT:
Op = {crdt_op,riak_dt_map,{update,[{update,{<<"name">>,riak_dt_emcntr},increment}]},Context}.
And then apply that operation to the CRDT, providing the actor ID you want to use to update the vclock/version vector:
NewObj = riak_kv_crdt:update(Obj,Actor,Op).
The result should be another r_object that is ready to be sent back for storage.
来源:https://stackoverflow.com/questions/29092235/dealing-with-riak-datatypes-in-postcommit-hooks