Skip to content

Commit

Permalink
Added sorting to NewSparseVectorFromMap
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Jul 24, 2024
1 parent d5e5fc2 commit f493c52
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
6 changes: 4 additions & 2 deletions sparsevec.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}
}

Expand Down
7 changes: 7 additions & 0 deletions sparsevec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down

0 comments on commit f493c52

Please sign in to comment.