Class: ClawDruid

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/claw_druid.rb

Constant Summary collapse

THRESHOLD =
ENV["DEBUG"] ? 5 : 30
OPERATIONS =
{
  '<' => "lessThan",
  '>' => 'greaterThan',
  '=' => 'equalTo'
}
FnAggregates =
{
  "min" => "return Math.min(current, (COLUMN));",
  "max" => "return Math.max(current, (COLUMN));",
  "sum" => "return current + (COLUMN);"
}
TopN =
"topN"
Select =
"select"
GroupBy =
"groupBy"
TimeSeries =
"timeseries"
TimeBoundary =
"timeBoundary"
SegmentMetaData =
"segmentMetadata"
DataSourceMetaData =
"dataSourceMetadata"
Permit_Properties =
{
  TopN => [:queryType, :dataSource, :intervals, :granularity, :filter, :aggregations, :postAggregations, :dimension, :threshold, :metric, :context],
  Select => [:queryType, :dataSource, :intervals, :granularity, :descending, :filter, :dimensions, :metrics, :pagingSpec, :context],
  GroupBy => [:queryType, :dataSource, :dimensions, :limitSpec, :having, :granularity, :filter, :aggregations, :postAggregations, :intervals, :context],
  TimeSeries => [:queryType, :dataSource, :descending, :intervals, :granularity, :filter, :aggregations, :postAggregations, :context],
  TimeBoundary => [:queryType, :dataSource, :bound, :filter, :context],
  SegmentMetaData => [:queryType, :dataSource, :intervals, :toInclude, :merge, :context, :analysisTypes, :lenientAggregatorMerge],
  DataSourceMetaData => [:queryType, :dataSource, :context],
}

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ ClawDruid

Returns a new instance of ClawDruid.



41
42
43
44
45
46
47
48
# File 'lib/claw_druid.rb', line 41

def initialize(params = {})
  @url        = params[:url]
  @params     = {dataSource: params[:source], granularity: "all", queryType: Select}
  @threshold  = params[:threshold] || THRESHOLD

  # The page_identifiers of every query, the key is the params.hash of the query, the value is a identifiers like "publisher_daily_report_2017-02-02T00:00:00.000Z_2017-02-04T00:00:00.000Z_2017-03-30T12:10:27.053Z"
  @paging_identifiers = {}
end

Instance Method Details

#count(*columns) ⇒ Object



124
125
126
127
128
129
130
131
132
133
# File 'lib/claw_druid.rb', line 124

def count(*columns)
  @params[:queryType]    ||= TimeSeries
  @params[:aggregations] ||= []
  if columns.empty?
    @params[:aggregations] << { type: "count", name: "count" }
  else
    @params[:aggregations] += columns.map{|column| { type: "cardinality", name: "count(#{column})", fields: [column] } }
  end
  self
end

#deleteObject



306
307
308
309
310
# File 'lib/claw_druid.rb', line 306

def delete
  result = HTTParty.delete(@url)
  puts result.code if ENV["DEBUG"]
  result.body
end

#each(&block) ⇒ Object



292
293
294
# File 'lib/claw_druid.rb', line 292

def each(&block)
  to_a.each(&block)
end

#getObject



300
301
302
303
304
# File 'lib/claw_druid.rb', line 300

def get
  result = HTTParty.get(@url)
  puts result.code if ENV["DEBUG"]
  result.body
end

#group(*dimensions) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/claw_druid.rb', line 50

def group(*dimensions)
  dimensions = dimensions[0] if dimensions.count == 1 && dimensions[0].is_a?(Array)

  @params[:queryType]  = GroupBy

  lookup_dimensions = dimensions.except{|dimension| dimension.is_a? Hash }
  select_lookup(lookup_dimensions)

  if dimensions && dimensions.count > 0
    @params[:dimensions] ||= []
    @params[:dimensions]  += dimensions.map(&:to_s).map(&:strip)
    @params[:dimensions].uniq!
  end
  @params.delete(:metrics)
  self
end

#having(*conditions) ⇒ Object



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/claw_druid.rb', line 224

def having(*conditions)
  if conditions[0].is_a?(Hash)
    conditions = conditions[0]

    conditions = conditions.delete_if{|key, value| value.blank?}.map{|column, value|
      { type: OPERATIONS["="], aggregation: column, value: value }
    }.compact
  elsif conditions[0].is_a?(String)
    # Process the ('a = ? and b = ?', 1, 2)
    conditions[0].gsub!(" \?").each_with_index { |v, i| " #{conditions[i + 1]}" }
    conditions = [having_chain( conditions[0] )]
  else
    conditions = nil
  end

  unless conditions.blank?
    @params[:having]               ||= { type: "and", havingSpecs: [] }
    @params[:having][:havingSpecs]  += conditions
  end
  
  self
end

#limit(limit_count) ⇒ Object



188
189
190
191
192
193
# File 'lib/claw_druid.rb', line 188

def limit(limit_count)
  @params[:limitSpec]         ||= {}
  @params[:limitSpec][:type]  ||= "default"
  @params[:limitSpec][:limit]   = limit_count
  self
end

#map(&block) ⇒ Object



296
297
298
# File 'lib/claw_druid.rb', line 296

def map(&block)
  to_a.map(&block)
end

#max_timeObject



261
262
263
264
265
# File 'lib/claw_druid.rb', line 261

def max_time
  @params[:queryType] = TimeBoundary
  @params[:bound]     = "maxTime"
  self
end

#meta_method(method, columns) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/claw_druid.rb', line 92

def meta_method(method, columns)
  columns = columns[0] if columns.count == 1 and columns[0].is_a?(Array)

  @params[:queryType]    ||= TimeSeries
  @params[:aggregations] ||= []
  @params[:aggregations] += columns.map{|column, naming| 
    naming       ||=  "#{method}(#{column})"
    fnAggregate    =  FnAggregates[method.to_s].gsub("COLUMN", column.to_s)
    if column[/( [\+\-\*\/] )/]
      fields = column.split(/ [\+\-\*\/] /)
      {
        type:         "javascript",
        name:         naming,
        fieldNames:   fields,
        fnAggregate:  "function(current, #{fields.join(', ')}) { #{fnAggregate} }",
        fnCombine:    "function(partialA, partialB) { return partialA + partialB; }",
        fnReset:      "function()                   { return 0; }"
      }
    else
      { type: "double#{method.capitalize}", name: naming, fieldName: column } 
    end
  }
  @params[:aggregations].uniq!
  self
end

#min_timeObject



267
268
269
270
271
# File 'lib/claw_druid.rb', line 267

def min_time
  @params[:queryType] = TimeBoundary
  @params[:bound]     = "minTime"
  self
end

#order(*columns) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/claw_druid.rb', line 166

def order(*columns)
  columns = columns[0] if columns[0].is_a?(Hash) || columns[0].is_a?(Array)
  
  if @params[:queryType] != GroupBy
    @params[:metric]   ||= []
    @params[:metric]    += columns.map{|column, direction| column }
    @params[:descending] = columns.any?{|column, direction| direction.to_s[/desc/]}
  else
    @params[:limitSpec]         ||= {}
    @params[:limitSpec][:type]  ||= "default"
    @params[:limitSpec][:limit] ||= 500000
    @params[:limitSpec][:columns] = columns.map{|column, direction| 
      {
        dimension: column.to_s,
        direction: direction.to_s[/desc/] ? "descending" : "ascending",
        dimensionOrder: "lexicographic"
      }
    }
  end
  self
end

#page(page_count) ⇒ Object



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/claw_druid.rb', line 202

def page(page_count)
  if page_count == 1
    @params[:pagingSpec] = {pagingIdentifiers: {}, threshold: @threshold}
  elsif page_count > 1
    current = permit_params.reject{|key, value| key == :pagingSpec}.hash
    @paging_identifiers[current] ||= {0 => {}}

    (1..page_count-1).each do |current_page|
      if begin @paging_identifiers[current][current_page].nil? rescue true end
        result = query(@params.merge(pagingSpec: {pagingIdentifiers: @paging_identifiers[current][current_page-1], threshold: @threshold}))
        
        # The pagingIdentifiers is something like { "publisher_daily_report_2017-03-01T00:00:00.000Z_2017-03-11T00:00:00.000Z_2017-04-17T21:04:30.804Z" => -10 }
        @paging_identifiers[current]              ||= {}
        @paging_identifiers[current][current_page]  = JSON.parse(result)[0]["result"]["pagingIdentifiers"].transform_values{|value| value + 1}
      end
    end if begin @paging_identifiers[current][page_count - 1].nil? rescue true end

    @params[:pagingSpec] = {pagingIdentifiers: @paging_identifiers[current][page_count - 1], threshold: @threshold}
  end
  self
end

#query(params = @params) ⇒ Object



247
248
249
250
251
252
253
254
# File 'lib/claw_druid.rb', line 247

def query(params = @params)
  params = permit_params(params)
  ap params if ENV['DEBUG']
  puts params.to_json if ENV['DEBUG']
  result = HTTParty.post(@url, body: params.to_json, headers: { 'Content-Type' => 'application/json' })
  puts result.code if ENV['DEBUG']
  result.body
end

#segment_metaObject



278
279
280
281
# File 'lib/claw_druid.rb', line 278

def segment_meta
  @params[:queryType] = SegmentMetaData
  self
end

#select(*columns) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/claw_druid.rb', line 67

def select(*columns)
  # Split the columns like ['sum(column_a) as sum_a, column_b']
  columns = columns[0].split("\, ") if columns.count == 1 && columns[0].is_a?(String) && columns[0]["\, "]
  columns = columns[0]              if columns.count == 1 && columns[0].is_a?(Array)

  return self if columns.all?{|column| column.blank? }

  # Add the 'i' to regex to be case-insensitive, cause the sum, max and min could be SUM, MAX and MIN
  post_columns = columns.except{|column| column[/(sum|max|min|count).+[\+\-\*\/]/i] }
  @params[:postAggregations] = post_columns.map{|post_column| post_chain(post_column) } unless post_columns.blank?

  method_columns = columns.except{|column| column.is_a?(String) && column[/(sum|max|min|count)\(.+\)/i] }
  method_columns.each{|column| method_column(column) }

  lookup_columns = columns.except{|column| column.is_a? Hash }
  select_lookup(lookup_columns)
  
  if columns && columns.count > 0
    @params[:metrics]    ||= []
    @params[:metrics]     += columns.map(&:to_s).map(&:strip)
    @params[:metrics].uniq!
  end
  self
end

#source_metaObject



273
274
275
276
# File 'lib/claw_druid.rb', line 273

def source_meta
  @params[:queryType] = DataSourceMetaData
  self
end

#time_boundaryObject



256
257
258
259
# File 'lib/claw_druid.rb', line 256

def time_boundary
  @params[:queryType] = TimeBoundary
  self
end

#to_aObject



287
288
289
290
# File 'lib/claw_druid.rb', line 287

def to_a
  result = JSON.parse(query)
  @params[:queryType] == SegmentMetaData ? result[0]["columns"] : begin result[0]["result"]["events"] rescue result end
end

#to_sObject



283
284
285
# File 'lib/claw_druid.rb', line 283

def to_s
  query
end

#top(top_count) ⇒ Object



195
196
197
198
199
200
# File 'lib/claw_druid.rb', line 195

def top(top_count)
  @params[:queryType] = TopN
  @params[:threshold] = top_count
  @params[:metric] = @params.delete(:limitSpec)[:columns][0] if @params[:limitSpec]
  self
end

#where(*conditions) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/claw_druid.rb', line 135

def where(*conditions)
  if conditions[0].is_a?(Hash)
    conditions = conditions[0]
    begin_date = conditions.delete(:begin_date)
    end_date = conditions.delete(:end_date)
    @params[:intervals] = ["#{begin_date}/#{end_date}"]

    conditions = conditions.delete_if{|key, value| value.blank?}.map{|column, values|
      if !values.is_a?(Array)
        { type: "selector", dimension: column, value: values }
      elsif values.count == 1
        { type: "selector", dimension: column, value: values[0] }
      else
        { type: "in", dimension: column, values: values }
      end
    }.compact
  elsif conditions[0].is_a?(String)
    # Process the ('a = ? and b = ?', 1, 2)
    conditions[0].gsub!(" \?").each_with_index { |v, i| " #{conditions[i + 1]}" } if conditions[0][" \?"]
    conditions = [where_chain( conditions[0] )]
  else
    conditions = nil
  end

  unless conditions.blank?
    @params[:filter]          ||= { type: "and", fields: [] }
    @params[:filter][:fields]  += conditions
  end
  self
end