From f493c52a64153e06a95c473e5b4747f51278ecfe Mon Sep 17 00:00:00 2001 From: Andrew Kane Date: Tue, 23 Jul 2024 17:47:14 -0700 Subject: [PATCH] Added sorting to NewSparseVectorFromMap --- sparsevec.go | 6 ++++-- sparsevec_test.go | 7 +++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/sparsevec.go b/sparsevec.go index 4ef4769..f390e48 100644 --- a/sparsevec.go +++ b/sparsevec.go @@ -36,13 +36,15 @@ func NewSparseVector(vec []float32) SparseVector { func NewSparseVectorFromMap(elements map[int32]float32, dim int32) SparseVector { indices := make([]int32, 0, len(elements)) values := make([]float32, 0, len(elements)) - // no need to sort since binary format is not supported for k, v := range elements { if v != 0 { indices = append(indices, k) - values = append(values, v) } } + slices.Sort(indices) + for _, k := range indices { + values = append(values, elements[k]) + } return SparseVector{dim: dim, indices: indices, values: values} } diff --git a/sparsevec_test.go b/sparsevec_test.go index fcf2fee..0dba6f9 100644 --- a/sparsevec_test.go +++ b/sparsevec_test.go @@ -57,6 +57,13 @@ func TestSparseVectorString(t *testing.T) { } } +func TestSparseVectorFromMapString(t *testing.T) { + vec := pgvector.NewSparseVectorFromMap(map[int32]float32{2: 2, 4: 3, 0: 1, 3: 0}, 6) + if fmt.Sprint(vec) != "{1:1,3:2,5:3}/6" { + t.Error() + } +} + func TestSparseVectorParse(t *testing.T) { var vec pgvector.SparseVector err := vec.Parse("{1:1,3:2,5:3}/6")