Commit 232b6a60c8dc6ffadb7612cff3eb95d518282548

Authored by Andrew Kane
2 parents e9b70245 b5f1e04b

Merge branch 'stats-facets' of https://github.com/samuel02/searchkick into samuel02-stats-facets

README.md
... ... @@ -443,6 +443,14 @@ price_ranges = [{to: 20}, {from: 20, to: 50}, {from: 50}]
443 443 Product.search "*", facets: {price: {ranges: price_ranges}}
444 444 ```
445 445  
  446 +
  447 +#### Stats
  448 +If stats is enabled the facets returned will in addition to the term and a count contain `max`, `min`, `mean` and `total` fields for the score in each facet. This is very useful if you want to be able to sort facets on relevance rather than count.
  449 +
  450 +```ruby
  451 +Product.search "*", facets: {store_id: { stats: true }}
  452 +```
  453 +
446 454 ### Highlight
447 455  
448 456 Highlight the search query in the results.
... ...
lib/searchkick/query.rb
... ... @@ -226,6 +226,14 @@ module Searchkick
226 226 field.to_sym => facet_options[:ranges]
227 227 }
228 228 }
  229 + elsif facet_options[:stats]
  230 + payload[:facets][field] = {
  231 + terms_stats: {
  232 + key_field: field,
  233 + value_script: 'doc.score',
  234 + size: facet_options[:limit] ? facet_options[:limit] + 150 : 100000
  235 + }
  236 + }
229 237 else
230 238 payload[:facets][field] = {
231 239 terms: {
... ...
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 =['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)
... ...