Commit 81875f4cfc9570cdc1b88e5ae205a960a147dd2c

Authored by JP Rosevear
Committed by Andrew Kane
1 parent ff4c8042

Support avg, cardinality, min, max and sum metric aggregates (#877)

Showing 2 changed files with 53 additions and 3 deletions   Show diff stats
lib/searchkick/query.rb
... ... @@ -2,6 +2,8 @@ module Searchkick
2 2 class Query
3 3 extend Forwardable
4 4  
  5 + @@metric_aggs = [:avg, :cardinality, :max, :min, :sum]
  6 +
5 7 attr_reader :klass, :term, :options
6 8 attr_accessor :body
7 9  
... ... @@ -643,10 +645,10 @@ module Searchkick
643 645 interval: interval
644 646 }
645 647 }
646   - elsif agg_options[:cardinality]
  648 + elsif metric = @@metric_aggs.find { |k| agg_options.has_key?(k) }
647 649 payload[:aggs][field] = {
648   - cardinality: {
649   - field: agg_options[:cardinality][:field] || field
  650 + metric => {
  651 + field: agg_options[metric][:field] || field
650 652 }
651 653 }
652 654 else
... ...
test/aggs_test.rb
... ... @@ -116,6 +116,20 @@ class AggsTest < Minitest::Test
116 116 assert_equal 4, products.aggs["products_per_year"]["buckets"].size
117 117 end
118 118  
  119 + def test_aggs_avg
  120 + products =
  121 + Product.search("*", {
  122 + aggs: {
  123 + avg_price: {
  124 + avg: {
  125 + field: :price
  126 + }
  127 + }
  128 + }
  129 + })
  130 + assert_equal 16.5, products.aggs["avg_price"]["value"]
  131 + end
  132 +
119 133 def test_aggs_cardinality
120 134 products =
121 135 Product.search("*", {
... ... @@ -130,6 +144,40 @@ class AggsTest < Minitest::Test
130 144 assert_equal 3, products.aggs["total_stores"]["value"]
131 145 end
132 146  
  147 + def test_aggs_min_max
  148 + products =
  149 + Product.search("*", {
  150 + aggs: {
  151 + min_price: {
  152 + min: {
  153 + field: :price
  154 + }
  155 + },
  156 + max_price: {
  157 + max: {
  158 + field: :price
  159 + }
  160 + }
  161 + }
  162 + })
  163 + assert_equal 5, products.aggs["min_price"]["value"]
  164 + assert_equal 25, products.aggs["max_price"]["value"]
  165 + end
  166 +
  167 + def test_aggs_sum
  168 + products =
  169 + Product.search("*", {
  170 + aggs: {
  171 + sum_price: {
  172 + sum: {
  173 + field: :price
  174 + }
  175 + }
  176 + }
  177 + })
  178 + assert_equal 66, products.aggs["sum_price"]["value"]
  179 + end
  180 +
133 181 protected
134 182  
135 183 def buckets_as_hash(agg)
... ...