From 89502e6ba5fdea27fc5d0b7597ba150acb65501f Mon Sep 17 00:00:00 2001 From: Andrew Kane Date: Fri, 20 Nov 2020 14:35:50 -0800 Subject: [PATCH] Added missing_ids method to results - #1452 --- CHANGELOG.md | 1 + lib/searchkick/results.rb | 15 ++++++++++----- test/search_test.rb | 10 +++++++--- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 55dacec..f8c4157 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ ## 4.4.2 (unreleased) +- Added `missing_ids` method to results - Fixed issue with `like` and special characters ## 4.4.1 (2020-06-24) diff --git a/lib/searchkick/results.rb b/lib/searchkick/results.rb index 7688253..7cf4c2b 100644 --- a/lib/searchkick/results.rb +++ b/lib/searchkick/results.rb @@ -22,6 +22,8 @@ module Searchkick # TODO return enumerator like with_score def with_hit @with_hit ||= begin + @missing_ids = [] + if options[:load] # results can have different types results = {} @@ -42,8 +44,6 @@ module Searchkick end end - missing_ids = [] - # sort results = hits.map do |hit| @@ -58,12 +58,12 @@ module Searchkick end [result, hit] end.select do |result, hit| - missing_ids << hit["_id"] unless result + @missing_ids << hit["_id"] unless result result end - if missing_ids.any? - Searchkick.warn("Records in search index do not exist in database: #{missing_ids.join(", ")}") + if @missing_ids.any? + Searchkick.warn("Records in search index do not exist in database: #{@missing_ids.join(", ")}") end results @@ -92,6 +92,11 @@ module Searchkick end end + def missing_ids + with_hit + @missing_ids + end + def suggestions if response["suggest"] response["suggest"].values.flat_map { |v| v.first["options"] }.sort_by { |o| -o["score"] }.map { |o| o["text"] }.uniq diff --git a/test/search_test.rb b/test/search_test.rb index 1305a96..eada9e9 100644 --- a/test/search_test.rb +++ b/test/search_test.rb @@ -37,12 +37,16 @@ class SearchTest < Minitest::Test assert_equal ["Dollar Tree"], products.map(&:name) end - def test_record_not_found + def test_missing_ids store_names ["Product A", "Product B"] - Product.where(name: "Product A").delete_all + product = Product.find_by(name: "Product A") + product.delete assert_output nil, /\[searchkick\] WARNING: Records in search index do not exist in database/ do - assert_search "product", ["Product B"] + result = Product.search("product") + assert_equal ["Product B"], result.map(&:name) + assert_equal [product.id.to_s], result.missing_ids end + assert_equal [], Product.search("product", load: false).missing_ids ensure Product.reindex end -- libgit2 0.21.0