Commit 858976b694bf7ce76cba566da3825616091c680c
Exists in
master
and in
21 other branches
Merge branch 'samuel02-stats-facets'
Showing
3 changed files
with
23 additions
and
1 deletions
Show diff stats
README.md
... | ... | @@ -443,6 +443,12 @@ price_ranges = [{to: 20}, {from: 20, to: 50}, {from: 50}] |
443 | 443 | Product.search "*", facets: {price: {ranges: price_ranges}} |
444 | 444 | ``` |
445 | 445 | |
446 | +Use the `stats` option to get to max, min, mean, and total scores for each facet | |
447 | + | |
448 | +```ruby | |
449 | +Product.search "*", facets: {store_id: {stats: true}} | |
450 | +``` | |
451 | + | |
446 | 452 | ### Highlight |
447 | 453 | |
448 | 454 | Highlight the search query in the results. | ... | ... |
lib/searchkick/query.rb
... | ... | @@ -219,6 +219,7 @@ module Searchkick |
219 | 219 | facets.each do |field, facet_options| |
220 | 220 | # ask for extra facets due to |
221 | 221 | # https://github.com/elasticsearch/elasticsearch/issues/1305 |
222 | + size = facet_options[:limit] ? facet_options[:limit] + 150 : 100000 | |
222 | 223 | |
223 | 224 | if facet_options[:ranges] |
224 | 225 | payload[:facets][field] = { |
... | ... | @@ -226,11 +227,19 @@ module Searchkick |
226 | 227 | field.to_sym => facet_options[:ranges] |
227 | 228 | } |
228 | 229 | } |
230 | + elsif facet_options[:stats] | |
231 | + payload[:facets][field] = { | |
232 | + terms_stats: { | |
233 | + key_field: field, | |
234 | + value_script: "doc.score", | |
235 | + size: size | |
236 | + } | |
237 | + } | |
229 | 238 | else |
230 | 239 | payload[:facets][field] = { |
231 | 240 | terms: { |
232 | 241 | field: field, |
233 | - size: facet_options[:limit] ? facet_options[:limit] + 150 : 100000 | |
242 | + size: size | |
234 | 243 | } |
235 | 244 | } |
236 | 245 | end | ... | ... |
test/facets_test.rb
... | ... | @@ -59,6 +59,13 @@ class TestFacets < Minitest::Unit::TestCase |
59 | 59 | assert_equal ({1 => 1, 2 => 1}), store_facet(where: {store_id: 2, price: {gt: 5}}, facets: [:store_id], smart_facets: true) |
60 | 60 | end |
61 | 61 | |
62 | + def test_stats_facets | |
63 | + options = {where: {store_id: 2}, facets: {store_id: {stats: true}}} | |
64 | + facets = Product.search("Product", options).facets["store_id"]["terms"] | |
65 | + expected_facets_keys = %w[term count total_count min max total mean] | |
66 | + assert_equal expected_facets_keys, facets.first.keys | |
67 | + end | |
68 | + | |
62 | 69 | protected |
63 | 70 | |
64 | 71 | def store_facet(options) | ... | ... |