Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ListIDs to collection for querying all existing document IDs #105

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,19 @@ func (c *Collection) AddDocument(ctx context.Context, doc Document) error {
return nil
}

// ListIDs returns the IDs of all documents in the collection.
func (c *Collection) ListIDs(_ context.Context) []string {
c.documentsLock.RLock()
defer c.documentsLock.RUnlock()

ids := make([]string, 0, len(c.documents))
for id := range c.documents {
ids = append(ids, id)
}

return ids
}

// GetByID returns a document by its ID.
// The returned document is a copy of the original document, so it can be safely
// modified without affecting the collection.
Expand Down
50 changes: 50 additions & 0 deletions collection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,56 @@ func TestCollection_QueryError(t *testing.T) {
}
}

func TestCollection_ListIDs(t *testing.T) {
ctx := context.Background()

// Create collection
db := NewDB()
name := "test"
metadata := map[string]string{"foo": "bar"}
vectors := []float32{-0.40824828, 0.40824828, 0.81649655} // normalized version of `{-0.1, 0.1, 0.2}`
embeddingFunc := func(_ context.Context, _ string) ([]float32, error) {
return vectors, nil
}
c, err := db.CreateCollection(name, metadata, embeddingFunc)
if err != nil {
t.Fatal("expected no error, got", err)
}
if c == nil {
t.Fatal("expected collection, got nil")
}

// Add documents
ids := []string{"1", "2"}
metadatas := []map[string]string{{"foo": "bar"}, {"a": "b"}}
contents := []string{"hello world", "hallo welt"}
err = c.Add(context.Background(), ids, nil, metadatas, contents)
if err != nil {
t.Fatal("expected nil, got", err)
}

// List IDs
foundIds := c.ListIDs(ctx)

// Ensure IDs match
// (slices are same length and all the items in the first slice exist in the second slice)
if len(foundIds) != len(ids) {
t.Fatal("expected", len(ids), "got", len(foundIds))
}
for _, id := range ids {
found := false
for _, foundID := range foundIds {
if id == foundID {
found = true
break
}
}
if !found {
t.Fatal("expected", id, "in", foundIds)
}
}
}

func TestCollection_Get(t *testing.T) {
ctx := context.Background()

Expand Down