Complete API documentation for LibraVDB.
func New(opts ...Option) (*Database, error)Creates a new database instance with the specified options.
Options:
WithStoragePath(path string)- Set storage directoryWithMetrics(enabled bool)- Enable/disable metrics collectionWithTracing(enabled bool)- Enable/disable distributed tracingWithMaxCollections(max int)- Set maximum number of collections
Example:
db, err := libravdb.New(
libravdb.WithStoragePath("./data"),
libravdb.WithMetrics(true),
libravdb.WithMaxCollections(100),
)func (db *Database) CreateCollection(ctx context.Context, name string, opts ...CollectionOption) (*Collection, error)Creates a new collection with the specified configuration.
func (db *Database) GetCollection(name string) (*Collection, error)Retrieves an existing collection by name.
func (db *Database) ListCollections() []stringReturns the names of all persisted collections in the database, including
collections discovered during reopen before any GetCollection calls.
func (db *Database) ListCollectionsWithContext(ctx context.Context) ([]string, error)Returns the same storage-backed collection list, but surfaces discovery errors to callers that need strict reopen/lifecycle handling.
func (db *Database) DeleteCollection(ctx context.Context, name string) errorDeletes a collection and its persisted data.
func (db *Database) DeleteCollections(ctx context.Context, names []string) errorDeletes multiple collections by exact name.
func (db *Database) Health(ctx context.Context) (*obs.HealthStatus, error)Returns the current health status of the database.
func (db *Database) Stats() *DatabaseStatsReturns comprehensive database statistics.
func (db *Database) Close() errorGracefully shuts down the database and all collections.
WithDimension(dim int) // Set vector dimension
WithMetric(metric DistanceMetric) // Set distance metricWithHNSW(m, efConstruction, efSearch int) // Configure HNSW index
WithFlat() // Use flat (exact) index
WithAutoIndexSelection(enabled bool) // Enable automatic index selectionWithMemoryLimit(bytes int64) // Set memory limit
WithMemoryMapping(enabled bool) // Enable memory mapping
WithCachePolicy(policy CachePolicy) // Set cache eviction policyWithQuantization(config *quant.QuantizationConfig) // Custom quantization
WithProductQuantization(codebooks, bits int, trainRatio float64) // Product quantization
WithScalarQuantization(bits int, trainRatio float64) // Scalar quantizationWithMetadataSchema(schema MetadataSchema) // Define metadata schema
WithIndexedFields(fields ...string) // Index specific fields for filteringWithBatchConfig(config BatchConfig) // Configure batch operations
WithBatchChunkSize(size int) // Set batch chunk size
WithBatchConcurrency(concurrency int) // Set batch concurrencyfunc (c *Collection) Insert(ctx context.Context, id string, vector []float32, metadata map[string]interface{}) errorInserts or updates a vector in the collection.
Parameters:
id- Unique identifier for the vectorvector- Float32 array matching collection dimensionmetadata- Optional key-value pairs for filtering
func (c *Collection) InsertBatch(ctx context.Context, entries []VectorEntry) errorInserts multiple vectors through a stable public batch API.
func (c *Collection) Delete(ctx context.Context, id string) errorDeletes a single vector by ID.
func (c *Collection) DeleteBatch(ctx context.Context, ids []string) errorDeletes multiple vectors by ID.
func (c *Collection) Iterate(ctx context.Context, fn func(Record) error) errorIterates all persisted records in the collection.
func (c *Collection) ListAll(ctx context.Context) ([]Record, error)Returns all persisted records in the collection.
func (c *Collection) ListByMetadata(ctx context.Context, field string, value interface{}) ([]Record, error)Returns records whose metadata field exactly matches the supplied value.
func (c *Collection) Count(ctx context.Context) (int, error)Returns the exact number of live records in the collection.
func (c *Collection) Search(ctx context.Context, vector []float32, k int) (*SearchResults, error)Performs vector similarity search.
Parameters:
vector- Query vectork- Number of results to return
Returns:
SearchResultscontaining matched vectors with scores
func (c *Collection) Query(ctx context.Context) *QueryBuilderReturns a query builder for advanced filtering and search.
func (c *Collection) Stats() *CollectionStatsReturns collection statistics including memory usage and optimization status.
func (c *Collection) Close() errorCloses the collection and releases resources.
The QueryBuilder provides a fluent interface for complex queries with filtering.
func (qb *QueryBuilder) WithVector(vector []float32) *QueryBuilder
func (qb *QueryBuilder) Limit(limit int) *QueryBuilder
func (qb *QueryBuilder) WithThreshold(threshold float32) *QueryBuilder
func (qb *QueryBuilder) List() ([]Record, error)
func (qb *QueryBuilder) Execute() (*SearchResults, error)func (qb *QueryBuilder) Eq(field string, value interface{}) *QueryBuilder
func (qb *QueryBuilder) NotEq(field string, value interface{}) *QueryBuilderfunc (qb *QueryBuilder) Gt(field string, value interface{}) *QueryBuilder
func (qb *QueryBuilder) Lt(field string, value interface{}) *QueryBuilder
func (qb *QueryBuilder) Between(field string, min, max interface{}) *QueryBuilderfunc (qb *QueryBuilder) ContainsAny(field string, values []interface{}) *QueryBuilder
func (qb *QueryBuilder) ContainsAll(field string, values []interface{}) *QueryBuilderfunc (qb *QueryBuilder) And() *QueryBuilder
func (qb *QueryBuilder) Or() *QueryBuilder
func (qb *QueryBuilder) Not() *QueryBuilder
func (qb *QueryBuilder) End() *QueryBuilderresults, err := collection.Query(ctx).
WithVector(queryVector).
Eq("category", "documents").
Limit(10).
Execute()records, err := collection.Query(ctx).
Eq("sessionId", "s1").
Limit(100).
List()results, err := collection.Query(ctx).
WithVector(queryVector).
Between("score", 0.8, 1.0).
Limit(10).
Execute()results, err := collection.Query(ctx).
WithVector(queryVector).
And().
Eq("category", "documents").
Or().
Gt("priority", 5).
ContainsAny("tags", []interface{}{"urgent", "important"}).
End().
End().
Limit(10).
Execute()For high-throughput batch insertions:
func (c *Collection) NewStreamingBatchInsert(opts *StreamingOptions) *StreamingBatchInserttype StreamingOptions struct {
BufferSize int // Internal buffer size
ChunkSize int // Batch processing chunk size
MaxConcurrency int // Maximum concurrent workers
Timeout time.Duration // Operation timeout
EnableBackpressure bool // Enable backpressure handling
BackpressureThreshold float64 // Buffer utilization threshold
ProgressCallback func(*StreamingStats) // Progress reporting
ErrorCallback func(error, *VectorEntry) // Error handling
}opts := libravdb.DefaultStreamingOptions()
opts.ChunkSize = 1000
opts.MaxConcurrency = 8
stream := collection.NewStreamingBatchInsert(opts)
err := stream.Start()
if err != nil {
log.Fatal(err)
}
defer stream.Close()
// Send vectors
for _, entry := range largeDataset {
err := stream.Send(entry)
if err != nil {
log.Printf("Failed to send entry: %v", err)
}
}
// Get statistics
stats := stream.Stats()
fmt.Printf("Processed %d entries\n", stats.TotalProcessed)type VectorEntry struct {
ID string `json:"id"`
Vector []float32 `json:"vector"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}type SearchResult struct {
ID string `json:"id"`
Score float32 `json:"score"`
Vector []float32 `json:"vector,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}type SearchResults struct {
Results []*SearchResult `json:"results"`
Took time.Duration `json:"took"`
Total int `json:"total"`
}type CollectionStats struct {
Name string `json:"name"`
VectorCount int `json:"vector_count"`
Dimension int `json:"dimension"`
IndexType string `json:"index_type"`
MemoryUsage int64 `json:"memory_usage"`
MemoryStats *CollectionMemoryStats `json:"memory_stats,omitempty"`
OptimizationStatus *OptimizationStatus `json:"optimization_status,omitempty"`
HasQuantization bool `json:"has_quantization"`
HasMemoryLimit bool `json:"has_memory_limit"`
MemoryMappingEnabled bool `json:"memory_mapping_enabled"`
}const (
L2Distance DistanceMetric = iota // Euclidean distance
InnerProduct // Inner product (dot product)
CosineDistance // Cosine distance
)const (
HNSW IndexType = iota // Hierarchical Navigable Small World
IVFPQ // Inverted File with Product Quantization
Flat // Brute-force exact search
)const (
LRUCache CachePolicy = iota // Least Recently Used
LFUCache // Least Frequently Used
FIFOCache // First In, First Out
)LibraVDB provides structured error information:
type Error struct {
Code ErrorCode `json:"code"`
Message string `json:"message"`
Component string `json:"component"`
Context *ErrorContext `json:"context,omitempty"`
}ErrInvalidDimension- Vector dimension mismatchErrCollectionNotFound- Collection doesn't existErrDatabaseClosed- Operation on closed databaseErrMemoryLimitExceeded- Memory limit reachedErrBackpressureActive- Streaming backpressure triggered
if err != nil {
if libravdbErr, ok := err.(*libravdb.Error); ok {
switch libravdbErr.Code {
case libravdb.ErrInvalidDimension:
// Handle dimension mismatch
case libravdb.ErrMemoryLimitExceeded:
// Handle memory pressure
default:
// Handle other errors
}
}
}