-
Notifications
You must be signed in to change notification settings - Fork 1
/
statistic_document.rb
54 lines (49 loc) · 1.08 KB
/
statistic_document.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
require 'ripple'
class StatisticDocument
attr_reader :average, :count
def initialize(bucket_name)
@bucket_name = bucket_name
end
def compute!
mapred = Riak::MapReduce.new(Ripple.client)
mapred.add @bucket_name
mapred.map(map_javascript, :keep => false)
mapred.reduce(reduce_javascript, :keep => true)
results = mapred.run
@average = results[0][0]
@count = results[0][1]
end
private
def map_javascript
<<-MAP
function(riakObject){
match = riakObject.values[0].data.match(/\"value\":([\\d]+)/);
if(match){
return [[parseInt(match[1]), 1]];
} else {
return [null];
}
}
MAP
end
def reduce_javascript
<<-REDUCE
function(values){
var sum = 0.0;
var count = 0;
for(i=0; i<values.length; i++){
value = values[i];
if(value){
sum = sum + (value[0] * value[1]);
count = count + value[1];
}
}
if(count > 0) {
return [[(sum / count), count]];
} else {
return [];
}
}
REDUCE
end
end