cubicle 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,2 @@
1
+ == 0.1.0
2
+ * Initial release
@@ -0,0 +1,22 @@
1
+ The MIT LICENSE
2
+
3
+ Copyright (c) 2010 Gabriel Horner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,173 @@
1
+ == Overview
2
+ Cubicle is a Ruby library and DSL for automating the generation, execution and caching of common aggregations of MongoDB documents. Cubicle was born from the need to easily extract simple, processed statistical views of raw, real time business data being collected from a variety of systems.
3
+
4
+ == Motivation
5
+ Aggregating data in MongoDB, unlike relational or multidimensional (OLAP) database, requires writing custom reduce functions in JavaScript for the simplest cases and full map reduce functions in the more complex cases, even for common aggregations like sums or averages.
6
+
7
+ While writing such map reduce functions isn't particularly difficult it can be tedious and error prone and requires switching from Ruby to JavaScript. Cubicle presents a simplified Ruby DSL for generating the JavaScript required for most common aggregation tasks and also handles processing, caching and presenting the results. JavaScript is still required in some cases, but is limited to constructing simple data transformation expressions.
8
+
9
+
10
+ == Approach
11
+ Cubicle breaks the task of defining and executing aggregation queries into two pieces. The first is the Cubicle, an analysis friendly 'view' of the underlying collection which defines both the attributes that will be used for grouping (dimensions) , the numerical fields that will be aggregated (measures), and kind of aggregation will be applied to each measure. The second piece of the Cubicle puzzle is a Query which specifies which particular dimensions or measures will be selected from the Cubicle for a given data request, along with how the resulting data will be filtered, ordered, paginated and organized.
12
+
13
+ == Install
14
+
15
+ Install the gem with:
16
+
17
+ gem install cubicle
18
+ or
19
+ sudo gem install cubicle
20
+
21
+
22
+ == An Example
23
+ Given a document with the following structure (I'm using MongoMapper here as the ORM, but MongoMapper, or any other ORM, is not required by Cubicle, it works directly with the Mongo-Ruby Driver)
24
+
25
+ class PokerHand
26
+ include MongoMapper::Document
27
+
28
+ key :match_date, String #we use iso8601 strings for dates, but Time works too
29
+ key :table, String
30
+ key :winner, Person # {:person=>{:name=>'Jim', :address=>{...}...}}
31
+ key :winning_hand, Symbol #:two_of_a_kind, :full_house, etc...
32
+ key :amount_won, Float
33
+ end
34
+
35
+ == The Cubicle
36
+ here's how a Cubicle designed to analyze these poker hands might look:
37
+
38
+ class PokerHandCubicle
39
+ extend Cubicle
40
+
41
+ date :date, :field_name=>'match_date'
42
+ dimension :month, :expression=>'this.match_date.substring(0,7)'
43
+ dimension :year, :expression=>'this.match_date.substring(0,4)'
44
+
45
+ dimensions :table, :winning_hand
46
+ dimension :winner, :field_name=>'winner.name'
47
+
48
+ count :total_hands, :expression=>'true'
49
+ count :total_draws, :expression=>'this.winning_hand=="draw"'
50
+ sum :total_winnings, :field_name=>'amount_won'
51
+ avg :avg_winnings, :field_name=>'amount_won'
52
+
53
+ ratio :draw_pct, :total_draws, :total_hands
54
+ end
55
+
56
+ == The Queries
57
+ The Queries
58
+ And here's how you would use this cubicle to query the underlying data:
59
+
60
+ aggregated_data = PokerHandCubicle.query
61
+
62
+
63
+ Issuing an empty query to the cubicle like the one above will return a list of measures aggregated according to type for each combination of dimensions. However, once a Cubicle has been defined, you can query it in many different ways. For instance if you wanted to see the total number of hands by type, you could do this:
64
+
65
+ hands_by_type = PokerHandCubicle.query { select :winning_hand, :total_hands }
66
+
67
+ Or, if you wanted to see the total amount won with a full house, by player, sorted by amount won, you could do this:
68
+
69
+ full_houses_by_player = PokerHandCubicle.query do
70
+ select :winner
71
+ where :winning_hand=>'full_house'
72
+ order_by :total_winnings
73
+ end
74
+
75
+ Cubicle can return your data in a hierarchy (tree) too, if you want. If you wanted to see the percent of hands resulting in a draw by table by day, you could do this:
76
+
77
+ draw_pct_by_player_by_day = PokerHandCubicle.query do
78
+ select :draw_pct
79
+ by :date, :table
80
+ end
81
+
82
+ In addition to the basic query primitives such as select, where, by and order_by, Cubicle has a basic understanding of time, so as long as you have a dimension in your cubicle defined using 'date', and that dimension is either an iso8601 string or an instance of Time, then you can easily perform some handy date filtering in the DSL:
83
+
84
+ winnings_last_30_days_by_player = PokerHandCubicle.query do
85
+ select :winner, :total_winnings
86
+ for_the_last 30.days
87
+ end
88
+
89
+ or
90
+
91
+ winnings_ytd_by_player = PokerHandCubicle.query do
92
+ select :winner, :all_measures
93
+ year_to_date
94
+ order_by [:total_winnings, :desc]
95
+ end
96
+
97
+ == The Results
98
+ Cubicle data is returned as either an array of hashes, for a two dimensional query, or a hash-based tree the leaves of which are arrays of hashes for hierarchical data (via queries using the 'by' keyword)
99
+
100
+ Flat data:
101
+ [{:dimension1=>'d1', :dimension2=>'d1', :measure1=>'1.0'},{:dimension1=>'d2'...
102
+
103
+ Hierarchical data 2 levels deep:
104
+ {'dimension 1'=>{'dimension2'=>[{:measures1=>'1.0'}],'dimension2b'=>[{measure1=>'2.0'}],...
105
+
106
+ When you request two dimensional data (i.e. you do not use the 'by' keyword) you can transform your two dimensional data set into hierarchical data at any time using the 'hierarchize' method, specifying the dimensions you want to use in your hierarchy:
107
+
108
+ data = MyCubicle.query {select :date, :name, :all_measures}
109
+ hierarchized_data = data.hierarchize :name, :date
110
+
111
+ This will result in a hash containing each unique value for :name in your source collection, and for each unique :name, a hash containing each unique :date with that :name, and for each :date, an array of hashes keyed by the measures in your Cubicle.
112
+
113
+ == Caching & Processing
114
+ Map reduce operations, especially over large or very large data sets, can take time to complete. Sometimes a long time. However, very often what you want to do is present a graph or a table of numbers to an interactive user on your website, and you probably don't want to make them wait for all your bazillion rows of raw data to be reduced down to the handful of numbers they are actually interested in seeing. For this reason, Cubicle has two modes of operation, the normal default mode in which aggregations are automatically cached until YourCubicle.expire! Or YourCubicle.process is called, and transient mode, which bypasses the caching mechanisms and executes real time queries against the raw source data.
115
+
116
+ == Preprocessed Aggregations
117
+ The expected normal mode of operation, however, is cached mode. While far from anything actually resembling an OLAP cube, Cubicle was designed to to process data on some periodic schedule and provide quick access to stored, aggregated data in between each processing, much like a real OLAP cube. Also reminiscent of an OLAP cube, Cubicle will cache aggregations at various levels of resolution, depending on the aggregations that were set up when defining a cubicle and depending on what queries are executed. For example, if a given Cubicle has three dimensions, Name, City and Date, when the Cubicle is processed, it will calculated aggregated measures for each combination of values on those three fields. If a query is executed that only requires Name and Date, then Cubicle will aggregate and cache measures by just Name and Date. If a third query asks for just Name, then Cubicle will create an aggregation based just on Name, but rather than using the original data source with its many rows, it will execute its map reduce against the previously cached Name-Date aggregation, which by definition will have fewer rows and should therefore perform faster. If you are aware ahead of time the aggregations your queries will need, you can specify them in the Cubicle definition, like this
118
+ class MyCubicle
119
+ extend Cubicle
120
+ dimension :name
121
+ dimension :date
122
+ ...
123
+ avg :my_measure
124
+ ...
125
+ aggregate :name, :date
126
+ aggregate :name
127
+ aggregate :date
128
+ end
129
+
130
+ When aggregations are specified in this way, then Cubicle will pre-aggregate your data for each of the specified combinations of dimensions whenever MyCubicle.process is called, eliminating the first-hit penalty that would otherwise be incurred when Cubicle encountered a given aggregation for the first time.
131
+
132
+ == Transient (Real Time) Queries
133
+ Sometimes you may not want to query cached data. In our application, we are using Cubicle to provide data for our performance management Key Performance Indicators (KPI's) which consist of both a historical trend of a particular metric as well as the current, real time value of the same metric for, say, the current month or a rolling 30 day period. For performance reasons, we fetch our trend, which is usually 12 months, from cached data but want up to the minute freshness for our real time KPI values, so we need to query the living source data. To accomplish this using Cubicle, you simply insert 'transient!' into your query definition, like so
134
+
135
+ MyCubicle.query do
136
+ transient!
137
+ select :this, :that, :the_other
138
+ end
139
+
140
+ This will bypass cached aggregations and execute a map reduce query directly against the cubicle source collection.
141
+
142
+ == Mongo Mapper plugin
143
+ If MongoMapper is detected, Cubicle will use its connection to MongoDB. Additionally, Cubicle will install a simple MongoMapper plugin for doing ad-hoc, non-cached aggregations on the fly from a MongoMapper document, like this:
144
+ MyMongoMapperModel.aggregate do
145
+ dimension :my_dimension
146
+ count :measure1
147
+ avg :measure2
148
+ end.query {order_by [:measure2, :desc]; limit 10;}
149
+
150
+ == Limitations
151
+ * Cubicle cannot currently cause child documents to be emitted in the map reduce. This is a pretty big limitation, and will be resolved shortly.
152
+ * Documentation is non-existent. This is being worked on (head that one before?)
153
+ * Test coverage is OK, but the tests could be better organized
154
+ * Code needs to be modularized a bit, main classes are a bit hairy at the moment
155
+
156
+
157
+ == Credits
158
+
159
+ * Alex Wang, Patrick Gannon for features, fixes & testing
160
+
161
+ == Bugs/Issues
162
+ Please report them {on github}[http://github.com/plasticlizard/cubicle/issues].
163
+
164
+ == Links
165
+
166
+ == Todo
167
+ * Support for emitting child / descendant documents
168
+ * Work with native Date type, instead of just iso strings
169
+ * Hirb support
170
+ * Member format strings
171
+ * Auto gen of a cubicle definition based on existing keys/key types in the MongoMapper plugin
172
+ * DSL support for topcount and bottomcount queries
173
+ * Support for 'duration' aggregation that will calculated durations between timestamps
@@ -0,0 +1,49 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+ require 'rake/testtask'
4
+ require 'rake/rdoctask'
5
+
6
+ begin
7
+ require 'jeweler'
8
+ require File.dirname(__FILE__) + "/lib/cubicle/version"
9
+
10
+ Jeweler::Tasks.new do |s|
11
+ s.name = "cubicle"
12
+ s.version = Cubicle::VERSION
13
+ s.summary = "Pseudo-Multi Dimensional analysis / simplified aggregation for MongoDB in Ruby (NOLAP ;))"
14
+ s.description = "Cubicle provides a dsl and aggregation caching framework for automating the generation, execution and caching of map reduce queries when using MongoDB in Ruby. Cubicle also includes a MongoMapper plugin for quickly performing ad-hoc, multi-level group-by queries against a MongoMapper model."
15
+ s.email = "hereiam@sonic.net"
16
+ s.homepage = "http://github.com/PlasticLizard/cubicle"
17
+ s.authors = ["Nathan Stults"]
18
+ s.has_rdoc = false #=>Should be true, someday
19
+ s.extra_rdoc_files = ["README.rdoc", "LICENSE.txt"]
20
+ s.files = FileList["[A-Z]*", "{bin,lib,test}/**/*"]
21
+
22
+ s.add_dependency('activesupport', '>= 2.3')
23
+ s.add_dependency('mongo', '>= 0.18.3')
24
+
25
+ s.add_development_dependency('shoulda', '2.10.3')
26
+ end
27
+
28
+ Jeweler::GemcutterTasks.new
29
+
30
+ rescue LoadError => ex
31
+ puts "Jeweler not available. Install it for jeweler-related tasks with: sudo gem install jeweler"
32
+
33
+ end
34
+
35
+ Rake::TestTask.new do |t|
36
+ t.libs << 'libs' << 'test'
37
+ t.pattern = 'test/**/*_test.rb'
38
+ t.verbose = false
39
+ end
40
+
41
+ Rake::RDocTask.new do |rdoc|
42
+ rdoc.rdoc_dir = 'rdoc'
43
+ rdoc.title = 'test'
44
+ rdoc.options << '--line-numbers' << '--inline-source'
45
+ rdoc.rdoc_files.include('README*')
46
+ rdoc.rdoc_files.include('lib/**/*.rb')
47
+ end
48
+
49
+ task :default => :test
@@ -0,0 +1,91 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE DIRECTLY
3
+ # Instead, edit Jeweler::Tasks in rakefile, and run the gemspec command
4
+ # -*- encoding: utf-8 -*-
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = %q{cubicle}
8
+ s.version = "0.1.0"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["Nathan Stults"]
12
+ s.date = %q{2010-03-13}
13
+ s.description = %q{Cubicle provides a dsl and aggregation caching framework for automating the generation, execution and caching of map reduce queries when using MongoDB in Ruby. Cubicle also includes a MongoMapper plugin for quickly performing ad-hoc, multi-level group-by queries against a MongoMapper model.}
14
+ s.email = %q{hereiam@sonic.net}
15
+ s.extra_rdoc_files = [
16
+ "LICENSE.txt",
17
+ "README.rdoc"
18
+ ]
19
+ s.files = [
20
+ "CHANGELOG.rdoc",
21
+ "LICENSE.txt",
22
+ "README.rdoc",
23
+ "Rakefile",
24
+ "cubicle.gemspec",
25
+ "lib/cubicle.rb",
26
+ "lib/cubicle/aggregation.rb",
27
+ "lib/cubicle/calculated_measure.rb",
28
+ "lib/cubicle/data.rb",
29
+ "lib/cubicle/data_level.rb",
30
+ "lib/cubicle/date_time.rb",
31
+ "lib/cubicle/dimension.rb",
32
+ "lib/cubicle/measure.rb",
33
+ "lib/cubicle/member.rb",
34
+ "lib/cubicle/member_list.rb",
35
+ "lib/cubicle/mongo_environment.rb",
36
+ "lib/cubicle/mongo_mapper/aggregate_plugin.rb",
37
+ "lib/cubicle/query.rb",
38
+ "lib/cubicle/ratio.rb",
39
+ "lib/cubicle/support.rb",
40
+ "lib/cubicle/version.rb",
41
+ "test/config/database.yml",
42
+ "test/cubicle/cubicle_aggregation_test.rb",
43
+ "test/cubicle/cubicle_data_level_test.rb",
44
+ "test/cubicle/cubicle_data_test.rb",
45
+ "test/cubicle/cubicle_query_test.rb",
46
+ "test/cubicle/cubicle_test.rb",
47
+ "test/cubicle/mongo_mapper/aggregate_plugin_test.rb",
48
+ "test/cubicles/defect_cubicle.rb",
49
+ "test/log/test.log",
50
+ "test/models/defect.rb",
51
+ "test/test_helper.rb"
52
+ ]
53
+ s.homepage = %q{http://github.com/PlasticLizard/cubicle}
54
+ s.rdoc_options = ["--charset=UTF-8"]
55
+ s.require_paths = ["lib"]
56
+ s.rubygems_version = %q{1.3.6}
57
+ s.summary = %q{Pseudo-Multi Dimensional analysis / simplified aggregation for MongoDB in Ruby (NOLAP ;))}
58
+ s.test_files = [
59
+ "test/cubicle/cubicle_aggregation_test.rb",
60
+ "test/cubicle/cubicle_data_level_test.rb",
61
+ "test/cubicle/cubicle_data_test.rb",
62
+ "test/cubicle/cubicle_query_test.rb",
63
+ "test/cubicle/cubicle_test.rb",
64
+ "test/cubicle/mongo_mapper/aggregate_plugin_test.rb",
65
+ "test/cubicles/defect_cubicle.rb",
66
+ "test/models/defect.rb",
67
+ "test/test_helper.rb",
68
+ "examples/cubicles/poker_hand_cubicle.rb",
69
+ "examples/models/poker_hand.rb"
70
+ ]
71
+
72
+ if s.respond_to? :specification_version then
73
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
74
+ s.specification_version = 3
75
+
76
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
77
+ s.add_runtime_dependency(%q<activesupport>, [">= 2.3"])
78
+ s.add_runtime_dependency(%q<mongo>, [">= 0.18.3"])
79
+ s.add_development_dependency(%q<shoulda>, ["= 2.10.3"])
80
+ else
81
+ s.add_dependency(%q<activesupport>, [">= 2.3"])
82
+ s.add_dependency(%q<mongo>, [">= 0.18.3"])
83
+ s.add_dependency(%q<shoulda>, ["= 2.10.3"])
84
+ end
85
+ else
86
+ s.add_dependency(%q<activesupport>, [">= 2.3"])
87
+ s.add_dependency(%q<mongo>, [">= 0.18.3"])
88
+ s.add_dependency(%q<shoulda>, ["= 2.10.3"])
89
+ end
90
+ end
91
+
@@ -0,0 +1,16 @@
1
+ class PokerHandCubicle
2
+ extend Cubicle
3
+
4
+ date :date, :field_name=>'match_date'
5
+ dimension :month, :expression=>'this.match_date.substring(0,7)'
6
+ dimension :year, :expression=>'this.match_date.substring(0,4)'
7
+
8
+ dimensions :table, :winner, :winning_hand
9
+
10
+ count :total_hands, :expression=>'true'
11
+ count :total_draws, :expression=>'this.winning_hand=="draw"'
12
+ sum :total_winnings, :field_name=>'amount_won'
13
+ avg :avg_winnings, :field_name=>'amount_won'
14
+
15
+ ratio :royal_flush_pct, :royal_flushes, :total_hands
16
+ end
@@ -0,0 +1,3 @@
1
+ class CookieSale
2
+ #Code here
3
+ end
@@ -0,0 +1,389 @@
1
+ require "rubygems"
2
+ require "active_support"
3
+ require "mongo"
4
+
5
+ dir = File.dirname(__FILE__)
6
+ ["mongo_environment",
7
+ "member",
8
+ "member_list",
9
+ "measure",
10
+ "calculated_measure",
11
+ "dimension",
12
+ "ratio",
13
+ "query",
14
+ "data_level",
15
+ "data",
16
+ "aggregation",
17
+ "date_time",
18
+ "support"].each {|lib|require File.join(dir,'cubicle',lib)}
19
+
20
+ require File.join(dir,"cubicle","mongo_mapper","aggregate_plugin") if defined?(MongoMapper::Document)
21
+
22
+ module Cubicle
23
+
24
+ def self.register_cubicle_directory(directory_path, recursive=true)
25
+ searcher = "#{recursive ? "*" : "**/*"}.rb"
26
+ Dir[File.join(directory_path,searcher)].each {|cubicle| require cubicle}
27
+ end
28
+
29
+ def self.mongo
30
+ @mongo ||= defined?(::MongoMapper::Document) ? ::MongoMapper : MongoEnvironment
31
+ end
32
+
33
+ def self.logger
34
+ Cubicle.mongo.logger
35
+ end
36
+
37
+ def database
38
+ Cubicle.mongo.database
39
+ end
40
+
41
+ def collection
42
+ database[target_collection_name]
43
+ end
44
+
45
+ def transient?
46
+ @transient ||= false
47
+ end
48
+
49
+ def transient!
50
+ @transient = true
51
+ end
52
+
53
+ def expire!
54
+ collection.drop
55
+ expire_aggregations!
56
+ end
57
+
58
+ def aggregations
59
+ return (@aggregations ||= [])
60
+ end
61
+
62
+ #DSL
63
+ def source_collection_name(collection_name = nil)
64
+ return @source_collection = collection_name if collection_name
65
+ @source_collection ||= name.chomp("Cubicle").chomp("Cube").underscore.pluralize
66
+ end
67
+ alias source_collection_name= source_collection_name
68
+
69
+ def target_collection_name(collection_name = nil)
70
+ return nil if transient?
71
+ return @target_name = collection_name if collection_name
72
+ @target_name ||= "#{name.blank? ? source_collection_name : name.underscore.pluralize}_cubicle"
73
+ end
74
+ alias target_collection_name= target_collection_name
75
+
76
+ def dimension(*args)
77
+ dimensions << Cubicle::Dimension.new(*args)
78
+ dimensions[-1]
79
+ end
80
+
81
+ def dimension_names
82
+ return @dimensions.map{|dim|dim.name.to_s}
83
+ end
84
+
85
+ def dimensions(*args)
86
+ return (@dimensions ||= Cubicle::MemberList.new) if args.length < 1
87
+ args = args[0] if args.length == 1 && args[0].is_a?(Array)
88
+ args.each {|dim| dimension dim }
89
+ @dimensions
90
+ end
91
+
92
+ def measure(*args)
93
+ measures << Measure.new(*args)
94
+ measures[-1]
95
+ end
96
+
97
+ def measures(*args)
98
+ return (@measures ||= Cubicle::MemberList.new) if args.length < 1
99
+ args = args[0] if args.length == 1 && args[0].is_a?(Array)
100
+ args.each {|m| measure m}
101
+ @measures
102
+ end
103
+
104
+ def count(*args)
105
+ options = args.extract_options!
106
+ options[:aggregation_method] = :count
107
+ measure(*(args << options))
108
+ end
109
+
110
+ def average(*args)
111
+ options = args.extract_options!
112
+ options[:aggregation_method] = :average
113
+ measure(*(args << options))
114
+ #Averaged fields need a count of non-null values to properly calculate the average
115
+ args[0] = "#{args[0]}_count".to_sym
116
+ count *args
117
+ end
118
+ alias avg average
119
+
120
+ def sum(*args)
121
+ options = args.extract_options!
122
+ options[:aggregation_method] = :sum
123
+ measure(*(args << options))
124
+ end
125
+
126
+ def ratio(member_name, numerator, denominator)
127
+ measures << Ratio.new(member_name, numerator, denominator)
128
+ end
129
+
130
+ def aggregation(*member_list)
131
+ member_list = member_list[0] if member_list[0].is_a?(Array)
132
+ aggregations << member_list
133
+ end
134
+
135
+ def time_dimension(*args)
136
+ return (@time_dimension ||= nil) unless args.length > 0
137
+ @time_dimension = dimension(*args)
138
+ end
139
+ alias time_dimension= time_dimension
140
+ alias date time_dimension
141
+ alias time time_dimension
142
+
143
+ def find_member(member_name)
144
+ @dimensions[member_name] ||
145
+ @measures[member_name]
146
+ end
147
+
148
+ def query(*args,&block)
149
+ options = args.extract_options!
150
+ query = Cubicle::Query.new(self)
151
+ query.source_collection_name = options.delete(:source_collection) if options[:source_collection]
152
+ query.select(*args) if args.length > 0
153
+ if block_given?
154
+ block.arity == 1 ? (yield query) : (query.instance_eval(&block))
155
+ end
156
+ query.select_all unless query.selected?
157
+ return query if options[:defer]
158
+ results = execute_query(query,options)
159
+ #If the 'by' clause was used in the the query,
160
+ #we'll hierarchize by the members indicated,
161
+ #as the next step would otherwise almost certainly
162
+ #need to be a call to hierarchize anyway.
163
+ query.respond_to?(:by) && query.by.length > 0 ? results.hierarchize(*query.by) : results
164
+ end
165
+
166
+ def execute_query(query,options={})
167
+ count = 0
168
+
169
+ find_options = {
170
+ :limit=>query.limit || 0,
171
+ :skip=>query.offset || 0
172
+ }
173
+
174
+ find_options[:sort] = prepare_order_by(query)
175
+ filter = {}
176
+ if query == self || query.transient?
177
+ aggregation = aggregate(query,options)
178
+ else
179
+ process_if_required
180
+ aggregation = aggregation_for(query)
181
+ #if the query exactly matches the aggregation in terms of requested members, we can issue a simple find
182
+ #otherwise, a second map reduce is required to reduce the data set one last time
183
+ if ((aggregation.name.split("_")[-1].split(".")) - query.member_names - [:all_measures]).blank?
184
+ filter = prepare_filter(query,options[:where] || {})
185
+ else
186
+ aggregation = aggregate(query,:source_collection=>collection.name)
187
+ end
188
+ end
189
+ count = aggregation.count
190
+ #noinspection RubyArgCount
191
+ data = aggregation.find(filter,find_options).to_a
192
+ #noinspection RubyArgCount
193
+ aggregation.drop if aggregation.name =~ /^tmp.mr.*/
194
+ Cubicle::Data.new(query, data, count)
195
+ end
196
+
197
+ def process(options={})
198
+ Cubicle.logger.info "Processing #{self.name} @ #{Time.now}"
199
+ start = Time.now
200
+ expire!
201
+ aggregate(self,options)
202
+ #Sort desc by length of array, so that larget
203
+ #aggregations are processed first, hopefully increasing efficiency
204
+ #of the processing step
205
+ aggregations.sort!{|a,b|b.length<=>a.length}
206
+ aggregations.each do |member_list|
207
+ agg_start = Time.now
208
+ aggregation_for(query(:defer=>true){select member_list})
209
+ Cubicle.logger.info "#{self.name} aggregation #{member_list.inspect} processed in #{Time.now-agg_start} seconds"
210
+ end
211
+ duration = Time.now - start
212
+ Cubicle.logger.info "#{self.name} processed @ #{Time.now}in #{duration} seconds."
213
+ end
214
+
215
+ protected
216
+
217
+ def aggregation_collection_names
218
+ database.collection_names.select {|col_name|col_name=~/#{target_collection_name}_aggregation_(.*)/}
219
+ end
220
+
221
+ def expire_aggregations!
222
+ aggregation_collection_names.each{|agg_col|database[agg_col].drop}
223
+ end
224
+
225
+ def find_best_source_collection(dimension_names, existing_aggregations=self.aggregation_collection_names)
226
+ #format of aggregation collection names is source_cubicle_collection_aggregation_dim1.dim2.dim3.dimn
227
+ #this next ugly bit of algebra will create 2d array containing a list of the dimension names in each existing aggregation
228
+ existing = existing_aggregations.map do |agg_col_name|
229
+ agg_col_name.gsub("#{target_collection_name}_aggregation_","").split(".")
230
+ end
231
+
232
+ #This will select all the aggregations that contain ALL of the desired dimension names
233
+ #we are sorting by length because the aggregation with the least number of members
234
+ #is likely to be the most efficient data source as it will likely contain the smallest number of rows.
235
+ #this will not always be true, and situations may exist where it is rarely true, however the alternative
236
+ #is to actually count rows of candidates, which seems a bit wasteful. Of course only the profiler knows,
237
+ #but until there is some reason to believe the aggregation caching process needs be highly performant,
238
+ #this should do for now.
239
+ candidates = existing.select {|candidate|(dimension_names - candidate).blank?}.sort {|a,b|a.length <=> b.length}
240
+
241
+ #If no suitable aggregation exists to base this one off of,
242
+ #we'll just use the base cubes aggregation collection
243
+ return target_collection_name if candidates.blank?
244
+ "#{target_collection_name}_aggregation_#{candidates[0].join('.')}"
245
+
246
+ end
247
+
248
+ def aggregation_for(query)
249
+ return collection if query.all_dimensions?
250
+
251
+ aggregation_query = query.clone
252
+ #If the query needs to filter on a field, it had better be in the aggregation...if it isn't a $where filter...
253
+ filter = (query.where if query.respond_to?(:where))
254
+ filter.keys.each {|filter_key|aggregation_query.select(filter_key) unless filter_key=~/^\$.*/} unless filter.blank?
255
+
256
+ dimension_names = aggregation_query.dimension_names.sort
257
+ agg_col_name = "#{target_collection_name}_aggregation_#{dimension_names.join('.')}"
258
+
259
+ unless database.collection_names.include?(agg_col_name)
260
+ source_col_name = find_best_source_collection(dimension_names)
261
+ exec_query = query(dimension_names + [:all_measures], :source_collection=>source_col_name, :defer=>true)
262
+ aggregate(exec_query, :target_collection=>agg_col_name)
263
+ end
264
+
265
+ database[agg_col_name]
266
+ end
267
+
268
+ def ensure_indexes(collection_name,dimension_names)
269
+ #an index for each dimension
270
+ dimension_names.each {|dim|database[collection_name].create_index([dim,Mongo::ASCENDING])}
271
+ #and a composite
272
+ database[collection_name].create_index(dimension_names)
273
+ end
274
+
275
+ def aggregate(query,options={})
276
+ map, reduce = generate_map_function(query), generate_reduce_function
277
+ options[:finalize] = generate_finalize_function(query)
278
+ options["query"] = prepare_filter(query,options[:where] || {})
279
+
280
+ query.source_collection_name ||= source_collection_name
281
+
282
+ target_collection = options.delete(:target_collection)
283
+ target_collection ||= query.target_collection_name if query.respond_to?(:target_collection_name)
284
+
285
+ options[:out] = target_collection unless target_collection.blank? || query.transient?
286
+
287
+ #This is defensive - some tests run without ever initializing any collections
288
+ return [] unless database.collection_names.include?(query.source_collection_name)
289
+
290
+ result = database[query.source_collection_name].map_reduce(map,reduce,options)
291
+
292
+ ensure_indexes(target_collection,query.dimension_names) if target_collection
293
+
294
+ result
295
+ end
296
+
297
+ def prepare_filter(query,filter={})
298
+ filter.merge!(query.where) if query.respond_to?(:where) && query.where
299
+ filter.stringify_keys!
300
+ transient = (query.transient? || query == self)
301
+ filter.keys.each do |key|
302
+ next if key=~/^\$.*/
303
+ prefix = nil
304
+ prefix = "_id" if (member = self.dimensions[key])
305
+ prefix = "value" if (member = self.measures[key]) unless member
306
+
307
+ raise "You supplied a filter that does not appear to be a member of this cubicle:#{key}" unless member
308
+
309
+ filter_value = filter.delete(key)
310
+ if transient
311
+ if (member.expression_type == :javascript)
312
+ filter_name = "$where"
313
+ filter_value = "'#{filter_value}'" if filter_value.is_a?(String) || filter_value.is_a?(Symbol)
314
+ filter_value = "(#{member.expression})==#{filter_value}"
315
+ else
316
+ filter_name = member.expression
317
+ end
318
+ else
319
+ filter_name = "#{prefix}.#{member.name}"
320
+ end
321
+ filter[filter_name] = filter_value
322
+ end
323
+ filter
324
+ end
325
+
326
+ def prepare_order_by(query)
327
+ order_by = []
328
+ query.order_by.each do |order|
329
+ prefix = "_id" if (member = self.dimensions[order[0]])
330
+ prefix = "value" if (member = self.measures[order[0]]) unless member
331
+ raise "You supplied a field to order_by that does not appear to be a member of this cubicle:#{key}" unless member
332
+ order_by << ["#{prefix}.#{order[0]}",order[1]]
333
+ end
334
+ order_by
335
+ end
336
+
337
+ def process_if_required
338
+ return if database.collection_names.include?(target_collection_name)
339
+ process
340
+ end
341
+
342
+
343
+ def generate_keys_string(query)
344
+ "{#{query.dimensions.map{|dim|dim.to_js_keys}.flatten.join(", ")}}"
345
+ end
346
+
347
+ def generate_values_string(query = self)
348
+ "{#{query.measures.map{|measure|measure.to_js_keys}.flatten.join(", ")}}"
349
+ end
350
+
351
+ def generate_map_function(query = self)
352
+ <<MAP
353
+ function(){emit(#{generate_keys_string(query)},#{generate_values_string(query)});}
354
+ MAP
355
+ end
356
+
357
+ def generate_reduce_function()
358
+ <<REDUCE
359
+ function(key,values){
360
+ var output = {};
361
+ values.forEach(function(doc){
362
+ for(var key in doc){
363
+ if (doc[key] != null){
364
+ output[key] = output[key] || 0;
365
+ output[key] += doc[key];
366
+ }
367
+ }
368
+ });
369
+ return output;
370
+ }
371
+ REDUCE
372
+ end
373
+
374
+ def generate_finalize_function(query = self)
375
+ <<FINALIZE
376
+ function(key,value)
377
+ {
378
+
379
+ #{ (query.measures.select{|m|m.aggregation_method == :average}).map do |m|
380
+ "value.#{m.name}=value.#{m.name}/value.#{m.name}_count;"
381
+ end.join("\n")}
382
+ #{ (query.measures.select{|m|m.aggregation_method == :calculation}).map do|m|
383
+ "value.#{m.name}=#{m.expression};";
384
+ end.join("\n")}
385
+ return value;
386
+ }
387
+ FINALIZE
388
+ end
389
+ end