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 = " function() {\n var hours = \#{hours.to_json};\n for (index in hours) {\n if (this.hour.getTime() == hours[index]*1000) {\n emit(hours[index], this.count);\n } else {\n emit(hours[index], 0);\n };\n };\n\n }\n EOF\n\n reduce = <<-EOF\n function(time, counts) {\n var count = 0;\n for (index in counts) { count += counts[index]; };\n return count;\n }\n EOF\n\n query = {:hour => {\"$gte\" => start_time, \"$lte\" => end_time}}\n\n begin\n results = self.collection.map_reduce(map, reduce, :out => {:inline => 1}, :raw => true, :query => query)[\"results\"]\n results = results.sort { |x,y| x[\"id\"] <=> y[\"id\"] }\n results = results.map do |result|\n time = result[\"_id\"].to_i\n time *= 1000 if options[:precision] == \"millisecond\"\n [time, result[\"value\"].to_i]\n end\n rescue\n results = []\n end\n\n return results\n end\nend\n"
|