October 29, 2012

“Riak MapReduce with Ruby”

Today, I learned how to use MapReduce in Riak using the Ruby client.

A MapReduce call using the Ruby Riak client

results = Riak::MapReduce.new(riak_client).
        add("site:#{domain}").
        map("function(v){
               obj = JSON.parse(v.values[0].data);
               return [{
                   'date': obj.rank_date,
                   'engine': obj.engine,
                   'count': obj.total_number_of_results
               }];
            }").
        reduce("function(values) {
                 result  = {};
                 values.forEach(function(v){
                  result[v.date] = result[v.date] || {'google': -1, 'yahoo': -1};
                  result[v.date][v.engine] = v.count;
                 });

                 return result;
               }", :keep => true).run