diff --git a/lib/searchkick/query.rb b/lib/searchkick/query.rb index fa006e2..85658ca 100644 --- a/lib/searchkick/query.rb +++ b/lib/searchkick/query.rb @@ -346,9 +346,12 @@ module Searchkick end aggs.each do |field, agg_options| + size = agg_options[:limit] ? agg_options[:limit] : 100_000 + payload[:aggs][field] = { terms: { - field: agg_options[:field] || field + field: agg_options[:field] || field, + size: size } } @@ -363,11 +366,7 @@ module Searchkick } }, aggs: { - field => { - terms: { - field: field - } - } + field => payload[:aggs][field] } } end diff --git a/lib/searchkick/results.rb b/lib/searchkick/results.rb index 4d7ea63..f18d520 100644 --- a/lib/searchkick/results.rb +++ b/lib/searchkick/results.rb @@ -76,12 +76,14 @@ module Searchkick end def aggs - response["aggregations"].each do |field, filtered_agg| - buckets = filtered_agg[field] - # move the buckets one level above into the field hash - if buckets - filtered_agg.delete(field) - filtered_agg.merge!(buckets) + @aggs ||= begin + response["aggregations"].dup.each do |field, filtered_agg| + buckets = filtered_agg[field] + # move the buckets one level above into the field hash + if buckets + filtered_agg.delete(field) + filtered_agg.merge!(buckets) + end end end end diff --git a/test/aggs_test.rb b/test/aggs_test.rb index 82cce31..9e76791 100644 --- a/test/aggs_test.rb +++ b/test/aggs_test.rb @@ -27,6 +27,13 @@ class TestAggs < Minitest::Test assert_equal ({1 => 1, 2 => 2}), store_agg({aggs: {store_id_new: {field: "store_id"}}}, "store_id_new") end + def test_limit + agg = Product.search("Product", aggs: {store_id: {limit: 1}}).aggs["store_id"] + assert_equal 1, agg["buckets"].size + # assert_equal 3, agg["doc_count"] + assert_equal 1, agg["sum_other_doc_count"] + end + def test_where_no_smart_aggs assert_equal ({2 => 2}), store_agg(where: {color: "red"}, aggs: {store_id: {where: {in_stock: false}}}) assert_equal ({2 => 2}), store_agg(where: {color: "blue"}, aggs: {store_id: {where: {in_stock: false}}}) -- libgit2 0.21.0