26 Aug 2012, 13:12
Generic-user-small

Radek Skokan (2 posts)

Hello,

I’m having a strange problem with the homework for day 2.

When I restrict the inputs to only few rooms, it works well. The code look s like

{
"inputs":[
  ["rooms","101"], ["rooms","102"], ["rooms","103"], 
  ["rooms","201"], ["rooms","202"], ["rooms","203"]
],
"query":[
{"map":{
"language":"javascript",
"source":
"function(v) {
  var room = JSON.parse(v.values[0].data);
  var data = {};
  var floor = 'floor_' + Math.floor(v.key / 100);
  data[floor] = room.capacity;
  return [data];
}"}},
{"reduce":{
"language":"javascript",
"source":
"function(v) {
  var totals = {};
  for (var i in v) {
    for (var floor in v[i]) {
      if (totals[floor]) totals[floor] += v[i][floor];
      else totals[floor] = v[i][floor];
    }
  }
  return totals;
}"}}
]}

But once I want to go through all the rooms, Riak (1.2) complains with ` {“phase”:1,”error”:”bad_json”,”input”:”{struct,[{«"floor_48"»,4}]}”,”type”:”exit”,”stack”:”[{riak_kv_w_reduce,’-js_runner/1-fun-0-‘,3,[{file,"src/riak_kv_w_reduce.erl"},{line,285}]},{riak_kv_w_reduce,reduce,3,[{file,"src/riak_kv_w_reduce.erl"},{line,207}]},{riak_kv_w_reduce,maybe_reduce,2,[{file,"src/riak_kv_w_reduce.erl"},{line,157}]},{riak_pipe_vnode_worker,process_input,3,[{file,"src/riak_pipe_vnode_worker.erl"},{line,445}]},{riak_pipe_vnode_worker,wait_for_input,2,[{file,"src/riak_pipe_vnode_worker.erl"},{line,377}]},{gen_fsm,handle_msg,7,[{file,"gen_fsm.erl"},{line,494}]},{proc_lib,…}]”} `

It is almost the same code just with different specification of the inputs section:

{
"inputs":"rooms",
"query":[
{"map":{
"language":"javascript",
"source":
"function(v) {
  var room = JSON.parse(v.values[0].data);
  var data = {};
  var floor = 'floor_' + Math.floor(v.key / 100);
  data[floor] = room.capacity;
  return [data];
}"}},
{"reduce":{
"language":"javascript",
"source":
"function(v) {
  var totals = {};
  for (var i in v) {
    for (var floor in v[i]) {
      if (totals[floor]) totals[floor] += v[i][floor];
      else totals[floor] = v[i][floor];
    }
  }
  return totals;
}"}}
]}

Any Idea what I’m doing wrong?

Thanks

PS: Thanks for the nice book!

28 Aug 2012, 17:19
Generic-user-small

Mick Brooks (6 posts)

Hi Radek,

My guess is that the problem is caused by the reduce not returning an array, similar to what was happening here:

http://forums.pragprog.com/forums/202/topics/10881

even though the error message you see is not identical. If I’m right, the fix is to change the reduce function to @return [totals]@ instead of @return totals@

Cheers,

Mick

06 Sep 2012, 12:02
Generic-user-small

Radek Skokan (2 posts)

You are right Mick, once I changed it to return an array, Riak doesn’t complain anymore (still my code here is not perfect ;-) ).

Thanks! Radek

  You must be logged in to comment