diff --git a/CHANGELOG.md b/CHANGELOG.md index 00714d8..972215d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/pgvector/utils/sparsevec.py b/pgvector/utils/sparsevec.py index 1c81876..fd9ccff 100644 --- a/pgvector/utils/sparsevec.py +++ b/pgvector/utils/sparsevec.py @@ -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 diff --git a/tests/test_sparse_vector.py b/tests/test_sparse_vector.py index 643e841..06fe81a 100644 --- a/tests/test_sparse_vector.py +++ b/tests/test_sparse_vector.py @@ -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()