47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
# File 'app/models/concen/visit/page.rb', line 47
def self.aggregate_count_by_time(*args)
options = args.
if hour = options[:hour]
hour = hour.to_i
current_time = Time.now.utc
end_time = options[:start_time] || Time.utc(current_time.year, current_time.month, current_time.day, current_time.hour)
start_time = end_time - (hour-1).hours
hours = []
(0..hour-1).each do |h|
hours << (end_time - h.hours).to_i
end
map = <<-EOF
function() {
var hours = #{hours.to_json};
for (index in hours) {
if (this.hour.getTime() == hours[index]*1000) {
emit(hours[index], this.count);
} else {
emit(hours[index], 0);
};
};
}
EOF
reduce = <<-EOF
function(time, counts) {
var count = 0;
for (index in counts) { count += counts[index]; };
return count;
}
EOF
query = {:hour => {"$gte" => start_time, "$lte" => end_time}}
begin
results = self.collection.map_reduce(map, reduce, :out => {:inline => 1}, :raw => true, :query => query)["results"]
results = results.sort { |x,y| x["id"] <=> y["id"] }
results = results.map do |result|
time = result["_id"].to_i
time *= 1000 if options[:precision] == "millisecond"
[time, result["value"].to_i]
end
rescue
results = []
end
return results
end
end
|