Skip to content

Commit e55f76f

Browse files
committed
Added binary_quantize and subvector functions for Ecto
1 parent c547f0d commit e55f76f

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
- Added support for `bit` type to Ecto
55
- Added `Pgvector.extensions/0` function
66
- Added `l1_distance`, `hamming_distance`, and `jaccard_distance` functions for Ecto
7+
- Added `binary_quantize` and `subvector` functions for Ecto
78
- Dropped support for Elixir < 1.12
89

910
## 0.2.1 (2023-09-25)

lib/pgvector/ecto/query.ex

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,5 +57,23 @@ if Code.ensure_loaded?(Ecto) do
5757
fragment("(? <%> ?)", unquote(column), unquote(value))
5858
end
5959
end
60+
61+
@doc """
62+
Returns the binary quantization
63+
"""
64+
defmacro binary_quantize(value) do
65+
quote do
66+
fragment("binary_quantize(?)", unquote(value))
67+
end
68+
end
69+
70+
@doc """
71+
Returns a subvector
72+
"""
73+
defmacro subvector(value, start, count) do
74+
quote do
75+
fragment("subvector(?, ?, ?)", unquote(value), unquote(start), unquote(count))
76+
end
77+
end
6078
end
6179
end

test/ecto_test.exs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,16 @@ defmodule EctoTest do
5656
assert Enum.map(items, fn v -> v.id end) == [1, 3, 2]
5757
end
5858

59+
test "vector binary_quantize" do
60+
item = Repo.one(first(from i in Item, select: binary_quantize(i.embedding)))
61+
assert item == <<1::1, 1::1, 1::1>>
62+
end
63+
64+
test "vector subvector" do
65+
result = Repo.one(last(from i in Item, select: subvector(i.embedding, 2, 2)))
66+
assert result |> Pgvector.to_list() == [1, 2]
67+
end
68+
5969
test "halfvec l2 distance" do
6070
items = Repo.all(from i in Item, order_by: l2_distance(i.half_embedding, ^Pgvector.HalfVector.new([1, 1, 1])), limit: 5)
6171
assert Enum.map(items, fn v -> v.id end) == [1, 3, 2]
@@ -82,6 +92,16 @@ defmodule EctoTest do
8292
assert Enum.map(items, fn v -> v.id end) == [1, 3, 2]
8393
end
8494

95+
test "halfvec binary_quantize" do
96+
item = Repo.one(first(from i in Item, select: binary_quantize(i.half_embedding)))
97+
assert item == <<1::1, 1::1, 1::1>>
98+
end
99+
100+
test "halfvec subvector" do
101+
result = Repo.one(last(from i in Item, select: subvector(i.half_embedding, 2, 2)))
102+
assert result |> Pgvector.to_list() == [1, 2]
103+
end
104+
85105
test "bit hamming distance" do
86106
items = Repo.all(from i in Item, order_by: hamming_distance(i.binary_embedding, ^<<1::1, 0::1, 1::1>>), limit: 5)
87107
assert Enum.map(items, fn v -> v.id end) == [2, 3, 1]

0 commit comments

Comments
 (0)