Commit baa6afb5f5ab7b63bd5e0c98338ef71ccb057a96
Committed by
Andrew Kane
1 parent
907b5249
Exists in
master
and in
21 other branches
Date histogram (#709)
Showing
3 changed files
with
38 additions
and
0 deletions
Show diff stats
README.md
@@ -643,6 +643,13 @@ Minimum document count | @@ -643,6 +643,13 @@ Minimum document count | ||
643 | Product.search "apples", aggs: {store_id: {min_doc_count: 2}} | 643 | Product.search "apples", aggs: {store_id: {min_doc_count: 2}} |
644 | ``` | 644 | ``` |
645 | 645 | ||
646 | +Date histogram [master] | ||
647 | + | ||
648 | +```ruby | ||
649 | +Product.search("Product", aggs: { products_per_year: { date_histogram: { field: :created_at, interval: :year }}}) | ||
650 | +``` | ||
651 | + | ||
652 | + | ||
646 | #### Moving From Facets | 653 | #### Moving From Facets |
647 | 654 | ||
648 | 1. Replace `facets` with `aggs` in searches. **Note:** Stats facets are not supported at this time. | 655 | 1. Replace `facets` with `aggs` in searches. **Note:** Stats facets are not supported at this time. |
lib/searchkick/query.rb
@@ -564,6 +564,14 @@ module Searchkick | @@ -564,6 +564,14 @@ module Searchkick | ||
564 | ranges: agg_options[:date_ranges] | 564 | ranges: agg_options[:date_ranges] |
565 | }.merge(shared_agg_options) | 565 | }.merge(shared_agg_options) |
566 | } | 566 | } |
567 | + elsif histogram = agg_options[:date_histogram] | ||
568 | + interval = histogram[:interval] | ||
569 | + payload[:aggs][field] = { | ||
570 | + date_histogram: { | ||
571 | + field: histogram[:field], | ||
572 | + interval: interval | ||
573 | + } | ||
574 | + } | ||
567 | else | 575 | else |
568 | payload[:aggs][field] = { | 576 | payload[:aggs][field] = { |
569 | terms: { | 577 | terms: { |
test/aggs_test.rb
@@ -96,6 +96,29 @@ class AggsTest < Minitest::Test | @@ -96,6 +96,29 @@ class AggsTest < Minitest::Test | ||
96 | assert_equal ({2 => 2}), store_agg(where: {color: "blue"}, aggs: {store_id: {where: {in_stock: false}}}, smart_aggs: false) | 96 | assert_equal ({2 => 2}), store_agg(where: {color: "blue"}, aggs: {store_id: {where: {in_stock: false}}}, smart_aggs: false) |
97 | end | 97 | end |
98 | 98 | ||
99 | + def test_aggs_group_by_date | ||
100 | + store [{name: "Old Product", created_at: 3.years.ago}] | ||
101 | + aggs = Product.search( | ||
102 | + "Product", | ||
103 | + { | ||
104 | + aggs: { | ||
105 | + products_per_year: { | ||
106 | + date_histogram: { | ||
107 | + field: :created_at, | ||
108 | + interval: :year | ||
109 | + } | ||
110 | + } | ||
111 | + } | ||
112 | + } | ||
113 | + ).aggs | ||
114 | + | ||
115 | + if elasticsearch_below20? | ||
116 | + assert_equal 2, aggs["products_per_year"]["buckets"].size | ||
117 | + else | ||
118 | + assert_equal 4, aggs["products_per_year"]["buckets"].size | ||
119 | + end | ||
120 | + end | ||
121 | + | ||
99 | protected | 122 | protected |
100 | 123 | ||
101 | def buckets_as_hash(agg) | 124 | def buckets_as_hash(agg) |