diff --git a/README.md b/README.md index 6fb6be9..f9b9202 100644 --- a/README.md +++ b/README.md @@ -643,6 +643,13 @@ Minimum document count Product.search "apples", aggs: {store_id: {min_doc_count: 2}} ``` +Date histogram [master] + +```ruby +Product.search("Product", aggs: { products_per_year: { date_histogram: { field: :created_at, interval: :year }}}) +``` + + #### Moving From Facets 1. Replace `facets` with `aggs` in searches. **Note:** Stats facets are not supported at this time. diff --git a/lib/searchkick/query.rb b/lib/searchkick/query.rb index 3a08e5e..4974d4f 100644 --- a/lib/searchkick/query.rb +++ b/lib/searchkick/query.rb @@ -564,6 +564,14 @@ module Searchkick ranges: agg_options[:date_ranges] }.merge(shared_agg_options) } + elsif histogram = agg_options[:date_histogram] + interval = histogram[:interval] + payload[:aggs][field] = { + date_histogram: { + field: histogram[:field], + interval: interval + } + } else payload[:aggs][field] = { terms: { diff --git a/test/aggs_test.rb b/test/aggs_test.rb index 3042461..14aed17 100644 --- a/test/aggs_test.rb +++ b/test/aggs_test.rb @@ -96,6 +96,29 @@ class AggsTest < Minitest::Test assert_equal ({2 => 2}), store_agg(where: {color: "blue"}, aggs: {store_id: {where: {in_stock: false}}}, smart_aggs: false) end + def test_aggs_group_by_date + store [{name: "Old Product", created_at: 3.years.ago}] + aggs = Product.search( + "Product", + { + aggs: { + products_per_year: { + date_histogram: { + field: :created_at, + interval: :year + } + } + } + } + ).aggs + + if elasticsearch_below20? + assert_equal 2, aggs["products_per_year"]["buckets"].size + else + assert_equal 4, aggs["products_per_year"]["buckets"].size + end + end + protected def buckets_as_hash(agg) -- libgit2 0.21.0