Skip to content

Commit a4df507

Browse files
committed
Add save/load
1 parent 654158c commit a4df507

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

vectorstore/in_memory.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package vectorstore
33
import (
44
"container/heap"
55
"context"
6+
"encoding/gob"
7+
"io"
68

79
"github.com/hupe1980/golc/internal/util"
810
"github.com/hupe1980/golc/metric"
@@ -195,3 +197,26 @@ func (vs *InMemory) SimilaritySearch(ctx context.Context, query string) ([]schem
195197

196198
return documents, nil
197199
}
200+
201+
func (vs *InMemory) Load(r io.Reader) error {
202+
decoder := gob.NewDecoder(r)
203+
204+
// Decode the data
205+
if err := decoder.Decode(&vs.data); err != nil {
206+
return err
207+
}
208+
209+
return nil
210+
}
211+
212+
// Save saves the data to an io.Writer.
213+
func (vs *InMemory) Save(w io.Writer) error {
214+
encoder := gob.NewEncoder(w)
215+
216+
// Encode the data
217+
if err := encoder.Encode(vs.data); err != nil {
218+
return err
219+
}
220+
221+
return nil
222+
}

vectorstore/in_memory_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
package vectorstore
22

33
import (
4+
"bytes"
45
"context"
56
"testing"
67

78
"github.com/stretchr/testify/assert"
9+
"github.com/stretchr/testify/require"
810

911
"github.com/hupe1980/golc/schema"
1012
)
@@ -52,6 +54,31 @@ func TestInMemory(t *testing.T) {
5254
assert.Equal(t, expectedDocuments[i].PageContent, doc.PageContent)
5355
}
5456
})
57+
58+
t.Run("SaveAndLoad", func(t *testing.T) {
59+
originalData := []InMemoryItem{
60+
{Content: "item1", Vector: []float32{1.0, 2.0, 3.0}, Metadata: map[string]any{"key1": "value1"}},
61+
{Content: "item2", Vector: []float32{4.0, 5.0, 6.0}, Metadata: map[string]any{"key2": "value2"}},
62+
}
63+
64+
// Create an InMemory instance with the original data
65+
vsOriginal := &InMemory{data: originalData}
66+
67+
// Serialize the original data
68+
var buf bytes.Buffer
69+
err := vsOriginal.Save(&buf)
70+
require.NoError(t, err, "Failed to save data")
71+
72+
// Create a new InMemory instance
73+
vsLoaded := &InMemory{}
74+
75+
// Load the serialized data
76+
err = vsLoaded.Load(&buf)
77+
require.NoError(t, err, "Failed to load data")
78+
79+
// Check if the loaded data matches the original data
80+
assert.Equal(t, originalData, vsLoaded.data, "Loaded data does not match original data")
81+
})
5582
}
5683

5784
// mockEmbedder implements the schema.Embedder interface for testing purposes.

0 commit comments

Comments
 (0)