Skip to content

Commit

Permalink
Added support for where
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Sep 3, 2024
1 parent d0ed940 commit 24db039
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
14 changes: 6 additions & 8 deletions lib/searchkick/query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -532,31 +532,29 @@ def prepare
raise ArgumentError, "Hybrid search not supported yet"
end

if options[:where]
raise ArgumentError, "KNN search with where not supported yet"
end

if options[:knn].size != 1
raise ArgumentError, "Invalid knn option"
end

k = per_page + offset
filter = payload.delete(:query)

if Searchkick.opensearch?
payload[:query].delete(:match_all)
payload[:query][:knn] = {}
payload[:query] = {knn: {}}
options[:knn].each do |field, vector|
payload[:query][:knn][field.to_sym] = {
vector: vector,
k: k
k: k,
filter: filter
}
end
else
options[:knn].each do |field, vector|
payload[:knn] = {
field: field,
k: k,
query_vector: vector
query_vector: vector,
filter: filter
}
end
end
Expand Down
12 changes: 8 additions & 4 deletions test/knn_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,17 @@ def setup
super
end

def test_works
def test_basic
store [{name: "A", embedding: [1, 2, 3]}, {name: "B", embedding: [-1, -2, -3]}]
assert_order "*", ["A", "B"], knn: {embedding: [1, 2, 3]}

expected = Searchkick.opensearch? ? [1, 0] : [2, 1]
scores = Product.search(knn: {embedding: [1, 2, 3]}).hits.map { |v| v["_score"] }
assert_in_delta expected[0], scores[0]
assert_in_delta expected[1], scores[1]
assert_in_delta 1, scores[0]
assert_in_delta 0, scores[1]
end

def test_where
store [{name: "A", store_id: 1, embedding: [1, 2, 3]}, {name: "B", store_id: 2, embedding: [-1, -2, -3]}]
assert_order "*", ["A"], knn: {embedding: [1, 2, 3]}, where: {store_id: 1}
end
end

0 comments on commit 24db039

Please sign in to comment.