Skip to content

Commit

Permalink
Fixed error parsing zero sparse vectors
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Jul 10, 2024
1 parent 633cbd7 commit 5c65394
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## 0.3.1 (unreleased)

- Fixed error parsing zero sparse vectors
- Fixed error with Psycopg 2 and pgvector < 0.7
- Fixed error message when `vector` type not found with Psycopg 3

Expand Down
10 changes: 6 additions & 4 deletions pgvector/utils/sparsevec.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,12 @@ def from_text(cls, value):
elements, dim = value.split('/', 2)
indices = []
values = []
for e in elements[1:-1].split(','):
i, v = e.split(':', 2)
indices.append(int(i) - 1)
values.append(float(v))
# split on empty string returns single element list
if len(elements) > 2:
for e in elements[1:-1].split(','):
i, v = e.split(':', 2)
indices.append(int(i) - 1)
values.append(float(v))
return cls._from_parts(int(dim), indices, values)

@classmethod
Expand Down
4 changes: 4 additions & 0 deletions tests/test_sparse_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,7 @@ def test_values(self):

def test_to_coo(self):
assert SparseVector([1, 0, 2, 0, 3, 0]).to_coo().toarray().tolist() == [[1, 0, 2, 0, 3, 0]]

def test_zero_vector_text(self):
vec = SparseVector({}, 3)
assert vec.to_list() == SparseVector.from_text(vec.to_text()).to_list()

0 comments on commit 5c65394

Please sign in to comment.