Skip to content

Commit

Permalink
Added test for unindexed field [skip ci]
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Sep 3, 2024
1 parent be594d8 commit 6b84664
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 1 deletion.
15 changes: 15 additions & 0 deletions test/knn_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,19 @@ def test_distance
end
assert_equal "distance must be set on index for approximate search", error.message
end

def test_unindexed
store [{name: "A", vector: [1, 2, 3]}, {name: "B", vector: [-1, -2, -3]}]
assert_order "*", ["A", "B"], knn: {field: :vector, vector: [1, 2, 3], distance: "cosine", exact: true}

scores = Product.search(knn: {field: :vector, vector: [1, 2, 3], distance: "cosine", exact: true}).hits.map { |v| v["_score"] }
# TODO match approximate
assert_in_delta 2, scores[0]
assert_in_delta 0, scores[1]

error = assert_raises(Searchkick::InvalidQueryError) do
Product.search(knn: {field: :vector, vector: [1, 2, 3]}).to_a
end
assert_match "to perform knn search on field [vector], its mapping must have [index] set to [true]", error.message
end
end
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: Searchkick.knn_support? ? {embedding: {dimensions: 3, distance: "cosine"}, factors: {dimensions: 3, distance: "euclidean"}} : nil
knn: Searchkick.knn_support? ? {embedding: {dimensions: 3, distance: "cosine"}, factors: {dimensions: 3, distance: "euclidean"}, vector: {dimensions: 3}} : nil

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

Expand Down
3 changes: 3 additions & 0 deletions test/support/activerecord.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
t.text :alt_description
t.text :embedding
t.text :factors
t.text :vector
t.timestamps null: true
end

Expand Down Expand Up @@ -81,9 +82,11 @@ class Product < ActiveRecord::Base
if ActiveRecord::VERSION::STRING.to_f >= 7.1
serialize :embedding, coder: JSON
serialize :factors, coder: JSON
serialize :vector, coder: JSON
else
serialize :embedding, JSON
serialize :factors, JSON
serialize :vector, JSON
end
end

Expand Down
1 change: 1 addition & 0 deletions test/support/mongoid.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Product
field :alt_description
field :embedding, type: Array
field :factors, type: Array
field :vector, type: Array
end

class Store
Expand Down

0 comments on commit 6b84664

Please sign in to comment.