Skip to content

Commit

Permalink
Improved hamming_distance and jaccard_distance
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed May 19, 2024
1 parent a717213 commit b9e2637
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 8 deletions.
4 changes: 2 additions & 2 deletions lib/pgvector/ecto/query.ex
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ if Code.ensure_loaded?(Ecto) do
"""
defmacro hamming_distance(column, value) do
quote do
fragment("(? <~> ?)", unquote(column), ^Pgvector.Ecto.Utils.to_bit_sql(unquote(value)))
fragment("(? <~> ?)", unquote(column), unquote(value))
end
end

Expand All @@ -54,7 +54,7 @@ if Code.ensure_loaded?(Ecto) do
"""
defmacro jaccard_distance(column, value) do
quote do
fragment("(? <%> ?)", unquote(column), ^Pgvector.Ecto.Utils.to_bit_sql(unquote(value)))
fragment("(? <%> ?)", unquote(column), unquote(value))
end
end
end
Expand Down
4 changes: 0 additions & 4 deletions lib/pgvector/ecto/utils.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,4 @@ defmodule Pgvector.Ecto.Utils do
def to_sql(vector) do
vector |> Pgvector.new()
end

def to_bit_sql(vector) when is_bitstring(vector) do
vector
end
end
4 changes: 2 additions & 2 deletions test/ecto_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,12 @@ defmodule EctoTest do
end

test "bit hamming distance" do
items = Repo.all(from i in Item, order_by: hamming_distance(i.binary_embedding, <<1::1, 0::1, 1::1>>), limit: 5)
items = Repo.all(from i in Item, order_by: hamming_distance(i.binary_embedding, ^<<1::1, 0::1, 1::1>>), limit: 5)
assert Enum.map(items, fn v -> v.id end) == [2, 3, 1]
end

test "bit jaccard distance" do
items = Repo.all(from i in Item, order_by: jaccard_distance(i.binary_embedding, <<1::1, 0::1, 1::1>>), limit: 5)
items = Repo.all(from i in Item, order_by: jaccard_distance(i.binary_embedding, ^<<1::1, 0::1, 1::1>>), limit: 5)
assert Enum.map(items, fn v -> v.id end) == [2, 3, 1]
end

Expand Down

0 comments on commit b9e2637

Please sign in to comment.