Commit 858976b694bf7ce76cba566da3825616091c680c

Authored by Andrew Kane
2 parents e9b70245 98c9b5ab

Merge branch 'samuel02-stats-facets'

@@ -443,6 +443,12 @@ price_ranges = [{to: 20}, {from: 20, to: 50}, {from: 50}] @@ -443,6 +443,12 @@ price_ranges = [{to: 20}, {from: 20, to: 50}, {from: 50}]
443 Product.search "*", facets: {price: {ranges: price_ranges}} 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 ### Highlight 452 ### Highlight
447 453
448 Highlight the search query in the results. 454 Highlight the search query in the results.
lib/searchkick/query.rb
@@ -219,6 +219,7 @@ module Searchkick @@ -219,6 +219,7 @@ module Searchkick
219 facets.each do |field, facet_options| 219 facets.each do |field, facet_options|
220 # ask for extra facets due to 220 # ask for extra facets due to
221 # https://github.com/elasticsearch/elasticsearch/issues/1305 221 # https://github.com/elasticsearch/elasticsearch/issues/1305
  222 + size = facet_options[:limit] ? facet_options[:limit] + 150 : 100000
222 223
223 if facet_options[:ranges] 224 if facet_options[:ranges]
224 payload[:facets][field] = { 225 payload[:facets][field] = {
@@ -226,11 +227,19 @@ module Searchkick @@ -226,11 +227,19 @@ module Searchkick
226 field.to_sym => facet_options[:ranges] 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 else 238 else
230 payload[:facets][field] = { 239 payload[:facets][field] = {
231 terms: { 240 terms: {
232 field: field, 241 field: field,
233 - size: facet_options[:limit] ? facet_options[:limit] + 150 : 100000 242 + size: size
234 } 243 }
235 } 244 }
236 end 245 end
test/facets_test.rb
@@ -59,6 +59,13 @@ class TestFacets < Minitest::Unit::TestCase @@ -59,6 +59,13 @@ class TestFacets < Minitest::Unit::TestCase
59 assert_equal ({1 => 1, 2 => 1}), store_facet(where: {store_id: 2, price: {gt: 5}}, facets: [:store_id], smart_facets: true) 59 assert_equal ({1 => 1, 2 => 1}), store_facet(where: {store_id: 2, price: {gt: 5}}, facets: [:store_id], smart_facets: true)
60 end 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 protected 69 protected
63 70
64 def store_facet(options) 71 def store_facet(options)