Class: Workarea::Metrics::CalculatePercentiles

Inherits:
Object
  • Object
show all
Defined in:
app/models/workarea/metrics/calculate_percentiles.rb

Instance Method Summary collapse

Constructor Details

#initialize(collection, field) ⇒ CalculatePercentiles

Returns a new instance of CalculatePercentiles.



6
7
8
9
# File 'app/models/workarea/metrics/calculate_percentiles.rb', line 6

def initialize(collection, field)
  @collection = collection
  @field = field
end

Instance Method Details

#aggregationObject



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
# File 'app/models/workarea/metrics/calculate_percentiles.rb', line 15

def aggregation
  @collection.aggregate(
    [
      { '$project' => { @field => 1 } },
      { '$match' => { @field => { '$gt' => 0 } } },
      { '$sort' => { @field => 1 } },
      { '$group' => { '_id' => nil, 'values' => { '$push' => "$#{@field}" } } },
      {
        '$project' => (0..99).reduce({}) do |memo, percentile|
          memo.merge(percentile => {
            '$arrayElemAt' => [
              '$values',
              {
                '$floor' => {
                  '$multiply' => [percentile / 100.to_f, { '$size' => '$values' }]
                }
              }
            ]
          })
        end
      }
    ],
    allow_disk_use: true
  )
end

#resultsObject



11
12
13
# File 'app/models/workarea/metrics/calculate_percentiles.rb', line 11

def results
  @results ||= (aggregation.first || {}).except('_id')
end