Last active
August 29, 2015 13:56
-
-
Save marcelmeyer/8981441 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(key_grouper). | |
%% You have to make sure that the journal bucket is set to allow siblings ({"props" : { "allow_mult":true}}. | |
%% Fetch the grouped keys using the Accept: multi/mixed header. | |
-define (JOURNAL, <<"test">>). | |
-export([ | |
store_per_month/1, | |
store_per_hour/1, | |
store_per_10min/1, | |
store_per_min/1]). | |
-export([log/1]). | |
%% ------------------------------------------------------------------ | |
%% API Functions | |
%% ------------------------------------------------------------------ | |
store_per_month(Object) -> | |
store(Object, per_month). | |
store_per_hour(Object) -> | |
store(Object, per_hour). | |
store_per_10min(Object) -> | |
store(Object, per_10min). | |
store_per_min(Object) -> | |
store(Object, per_min). | |
log(Object) -> | |
error_logger:info_msg("OBJECT: ~p~n",[Object]). | |
%% ------------------------------------------------------------------ | |
%% Internal Function Definitions | |
%% ------------------------------------------------------------------ | |
store(Object, Grouping) -> | |
{TimeKey, ObjectKey} = group_fact(Grouping, Object), | |
error_logger:info_msg("Grouping: TimeKey=~p ObjectKey=~p~n",[TimeKey, ObjectKey]), | |
save(?JOURNAL, TimeKey, ObjectKey). | |
group_fact(Grouping, Object) -> | |
Key = riak_object:key(Object), | |
Bucket = riak_object:bucket(Object), | |
Bstr = binary:bin_to_list(Bucket), | |
TimeKey = time_bucket(Grouping), | |
ReplKey = binary:list_to_bin(lists:flatten([Bstr,TimeKey])), | |
{ReplKey, Key}. | |
%% Produces a key based on the time. | |
time_bucket(per_month) -> | |
{{Y,M,_},_} = calendar:local_time(), | |
io_lib:fwrite("-~p-~p", [Y,M]); | |
time_bucket(per_day) -> | |
{{Y,M,D},_} = calendar:local_time(), | |
io_lib:fwrite("-~p-~p-~p", [Y,M,D]); | |
time_bucket(per_hour) -> | |
{{Y,M,D},{H,_,_}} = calendar:local_time(), | |
io_lib:fwrite("-~p-~p-~p-~p", [Y,M,D,H]); | |
time_bucket(per_min) -> | |
{{Y,M,D},{H,Mi,_}} = calendar:local_time(), | |
io_lib:fwrite("-~p-~p-~p-~p-~p", [Y,M,D,H,Mi]); | |
time_bucket(per_10min) -> | |
{{Y,M,D},{H,Mi,_}} = calendar:local_time(), | |
io_lib:fwrite("-~p-~p-~p-~p-~p", [Y,M,D,H,Mi div 10]). | |
save(Bucket, Key, Value) -> | |
Object = riak_object:new(Bucket, Key, Value), | |
{ok, C} = riak:local_client(), | |
C:put(Object). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment