From 3aa30aa53813315e63fd2bd0d3f7856dc2f945e0 Mon Sep 17 00:00:00 2001 From: Andrew Kane Date: Wed, 24 Jun 2020 15:25:26 -0700 Subject: [PATCH] Added with_score method to search results --- CHANGELOG.md | 1 + lib/searchkick/results.rb | 9 +++++++++ test/results_test.rb | 17 +++++++++++++++++ 3 files changed, 27 insertions(+), 0 deletions(-) create mode 100644 test/results_test.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 6819450..3fd2e18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ ## 4.4.1 (unreleased) - Added `stem_exclusion` and `stemmer_override` options +- Added `with_score` method to search results - Improved error message for `reload_synonyms` with non-OSS version of Elasticsearch - Improved output for reindex rake task diff --git a/lib/searchkick/results.rb b/lib/searchkick/results.rb index 7c5a81e..c8f67bc 100644 --- a/lib/searchkick/results.rb +++ b/lib/searchkick/results.rb @@ -211,12 +211,21 @@ module Searchkick end end + # TODO return enumerator like with_score def with_highlights(multiple: false) with_hit.map do |result, hit| [result, hit_highlights(hit, multiple: multiple)] end end + def with_score + return enum_for(:with_score) unless block_given? + + with_hit.each do |result, hit| + yield result, hit["_score"] + end + end + def misspellings? @options[:misspellings] end diff --git a/test/results_test.rb b/test/results_test.rb new file mode 100644 index 0000000..d34eaea --- /dev/null +++ b/test/results_test.rb @@ -0,0 +1,17 @@ +require_relative "test_helper" + +class ResultsTest < Minitest::Test + def test_with_score + store_names ["Product A", "Product B"] + results = Product.search("product") + assert_kind_of Enumerator, results.with_score + assert_equal 2, results.with_score.to_a.size + count = 0 + results.with_score do |product, score| + assert_kind_of Product, product + assert_kind_of Numeric, score + count += 1 + end + assert_equal 2, count + end +end -- libgit2 0.21.0