From 2cf9d0fa6e1126dcebe4baa57c6eacf032c7be9c Mon Sep 17 00:00:00 2001 From: Josh Schwartzman Date: Tue, 3 Jul 2018 11:27:19 -0700 Subject: [PATCH] Add time zone to date histogram (#1136) --- lib/searchkick/query.rb | 6 +----- test/aggs_test.rb | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/lib/searchkick/query.rb b/lib/searchkick/query.rb index 82afcab..d3d2cdf 100644 --- a/lib/searchkick/query.rb +++ b/lib/searchkick/query.rb @@ -742,12 +742,8 @@ module Searchkick }.merge(shared_agg_options) } elsif (histogram = agg_options[:date_histogram]) - interval = histogram[:interval] payload[:aggs][field] = { - date_histogram: { - field: histogram[:field], - interval: interval - } + date_histogram: histogram } elsif (metric = @@metric_aggs.find { |k| agg_options.has_key?(k) }) payload[:aggs][field] = { diff --git a/test/aggs_test.rb b/test/aggs_test.rb index 8068ff0..89dec19 100644 --- a/test/aggs_test.rb +++ b/test/aggs_test.rb @@ -116,6 +116,32 @@ class AggsTest < Minitest::Test assert_equal 4, products.aggs["products_per_year"]["buckets"].size end + def test_aggs_with_time_zone + start_time = Time.at(1529366400) + + store [ + {name: "Opera House Pass", created_at: start_time}, + {name: "London Eye Pass", created_at: start_time + 16.hours}, + {name: "London Tube Pass", created_at: start_time + 16.hours} + ] + + sydney_search = search_aggregate_by_day_with_time_zone('Pass', '+10:00') # Sydney + london_search = search_aggregate_by_day_with_time_zone('Pass', '+01:00') # London + + # London search will return all 3 in one bucket because of time zone offset + expected_london_buckets = [ + {"key_as_string" => "2018-06-19T00:00:00.000+01:00", "key" => 1529362800000, "doc_count" => 3} + ] + assert_equal expected_london_buckets, london_search.aggs["products_per_day"]["buckets"] + + # Sydney search will return them in separate buckets due to time zone offset + expected_sydney_buckets = [ + {"key_as_string" => "2018-06-19T00:00:00.000+10:00", "key" => 1529330400000, "doc_count" => 1}, + {"key_as_string" => "2018-06-20T00:00:00.000+10:00", "key" => 1529416800000, "doc_count" => 2} + ] + assert_equal expected_sydney_buckets, sydney_search.aggs["products_per_day"]["buckets"] + end + def test_aggs_avg products = Product.search("*", { @@ -200,6 +226,23 @@ class AggsTest < Minitest::Test protected + def search_aggregate_by_day_with_time_zone(query, time_zone = '-8:00') + Product.search(query, { + where: { + created_at: {lt: Time.now} + }, + aggs: { + products_per_day: { + date_histogram: { + field: :created_at, + interval: :day, + time_zone: time_zone + } + } + } + }) + end + def buckets_as_hash(agg) Hash[agg["buckets"].map { |v| [v["key"], v["doc_count"]] }] end -- libgit2 0.21.0