Skip to content

Commit

Permalink
Improved knn support check
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Sep 3, 2024
1 parent 601d76a commit 2a4ffc0
Show file tree
Hide file tree
Showing 6 changed files with 30 additions and 12 deletions.
20 changes: 20 additions & 0 deletions lib/searchkick.rb
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,26 @@ def self.server_below?(version, true_version = false)
Gem::Version.new(server_version.split("-")[0]) < Gem::Version.new(version.split("-")[0])
end

# private
def self.knn_support?
if opensearch?
!server_below?("2.4.0", true)
else
!server_below?("8.6.0")
end
end

# private
def self.check_knn_support
unless knn_support?
if opensearch?
raise Error, "knn requires OpenSearch 2.4+"
else
raise Error, "knn requires Elasticsearch 8.6+"
end
end
end

def self.search(term = "*", model: nil, **options, &block)
options = options.dup
klass = model
Expand Down
8 changes: 6 additions & 2 deletions lib/searchkick/index_options.rb
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,12 @@ def generate_settings
max_shingle_diff: 4
}

if options[:knn] && Searchkick.opensearch?
settings[:index][:knn] = true
if options[:knn]
Searchkick.check_knn_support

if Searchkick.opensearch?
settings[:index][:knn] = true
end
end

if options[:case_sensitive]
Expand Down
2 changes: 2 additions & 0 deletions lib/searchkick/query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,8 @@ def prepare
# knn
knn = options[:knn]
if knn
Searchkick.check_knn_support

if term != "*"
raise ArgumentError, "Hybrid search not supported yet"
end
Expand Down
2 changes: 1 addition & 1 deletion test/knn_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

class KnnTest < Minitest::Test
def setup
skip unless knn_support?
skip unless Searchkick.knn_support?
super
end

Expand Down
2 changes: 1 addition & 1 deletion test/models/product.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class Product
filterable: [:name, :color, :description],
similarity: "BM25",
match: ENV["MATCH"] ? ENV["MATCH"].to_sym : nil,
knn: knn_support? ? {embedding: {dimensions: 3}} : nil
knn: Searchkick.knn_support? ? {embedding: {dimensions: 3}} : nil

attr_accessor :conversions, :user_ids, :aisle, :details

Expand Down
8 changes: 0 additions & 8 deletions test/test_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,6 @@

ActiveSupport::LogSubscriber.logger = ActiveSupport::Logger.new(STDOUT) if ENV["VERBOSE"]

def knn_support?
if Searchkick.opensearch?
!Searchkick.server_below?("2.4.0", true)
else
!Searchkick.server_below?("8.6.0")
end
end

if defined?(Mongoid)
require_relative "support/mongoid"
else
Expand Down

0 comments on commit 2a4ffc0

Please sign in to comment.