Sha256: c5794c687b79b3656862536d597e0bf638216196100f1ab00e0a09dfa2d27999

Contents?: true

Size: 1.11 KB

Versions: 62

Compression:

Stored size: 1.11 KB

Contents

module Workarea
  module Metrics
    class CalculatePercentiles
      delegate :[], to: :results

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

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

      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
    end
  end
end

Version data entries

62 entries across 62 versions & 1 rubygems

Version Path
workarea-core-3.5.27 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.5.26 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.4.45 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.5.25 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.5.23 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.4.44 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.5.22 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.4.43 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.5.21 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.4.42 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.5.20 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.4.41 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.5.19 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.4.40 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.5.18 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.4.39 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.5.17 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.4.38 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.5.16 app/models/workarea/metrics/calculate_percentiles.rb
workarea-core-3.4.37 app/models/workarea/metrics/calculate_percentiles.rb