Documentation
¶
Overview ¶
Package veclite provides an embeddable vector database with zero external dependencies. It stores vectors with metadata in a single file using gob encoding.
Basic usage:
db, err := veclite.Open("data.veclite")
if err != nil {
log.Fatal(err)
}
defer db.Close()
coll := db.Collection("embeddings")
id, err := coll.Insert(vector, map[string]any{"file": "main.go"})
results, err := coll.Search(queryVector, veclite.TopK(10))
Index ¶
- Constants
- Variables
- type Collection
- func (c *Collection) All() []*Record
- func (c *Collection) Clear()
- func (c *Collection) Count() int
- func (c *Collection) Delete(id uint64) error
- func (c *Collection) DeleteWhere(filters ...Filter) (int, error)
- func (c *Collection) Dimension() int
- func (c *Collection) DistanceType() floats.DistanceType
- func (c *Collection) Find(filters ...Filter) ([]*Record, error)
- func (c *Collection) FindOne(filters ...Filter) (*Record, error)
- func (c *Collection) Get(id uint64) (*Record, error)
- func (c *Collection) GetVector(id uint64) ([]float32, error)
- func (c *Collection) HasIndex() bool
- func (c *Collection) IndexStats() *hnsw.IndexStats
- func (c *Collection) IndexType() IndexType
- func (c *Collection) Insert(vector []float32, payload map[string]any) (uint64, error)
- func (c *Collection) InsertBatch(vectors [][]float32, payloads []map[string]any) ([]uint64, error)
- func (c *Collection) Name() string
- func (c *Collection) Search(query []float32, opts ...SearchOption) ([]Result, error)
- func (c *Collection) SearchExplain(query []float32, opts ...SearchOption) (*SearchExplanation, error)
- func (c *Collection) Stats() CollectionStats
- func (c *Collection) Update(id uint64, payload map[string]any) error
- type CollectionOption
- type CollectionSnapshot
- type CollectionStats
- type DB
- func (db *DB) Close() error
- func (db *DB) Collection(name string) *Collection
- func (db *DB) Collections() []string
- func (db *DB) CreateCollection(name string, opts ...CollectionOption) (*Collection, error)
- func (db *DB) DropCollection(name string) error
- func (db *DB) GetCollection(name string) (*Collection, error)
- func (db *DB) HasCollection(name string) bool
- func (db *DB) IsClosed() bool
- func (db *DB) Path() string
- func (db *DB) Stats() DatabaseStats
- func (db *DB) Sync() error
- type DatabaseSnapshot
- type DatabaseStats
- type DimensionError
- type DistanceType
- type FileStorage
- type Filter
- func And(filters ...Filter) Filter
- func Contains(key, substr string) Filter
- func Equal(key string, value any) Filter
- func Exists(key string) Filter
- func Glob(key, pattern string) Filter
- func In(key string, values ...any) Filter
- func Not(filter Filter) Filter
- func NotEqual(key string, value any) Filter
- func NotIn(key string, values ...any) Filter
- func Or(filters ...Filter) Filter
- func Prefix(key, prefix string) Filter
- func Suffix(key, suffix string) Filter
- type FilterFunc
- type HNSWConfig
- type HNSWIndex
- func (h *HNSWIndex) Count() int
- func (h *HNSWIndex) Delete(id uint64) error
- func (h *HNSWIndex) Insert(id uint64, vector []float32) error
- func (h *HNSWIndex) Internal() *hnsw.Index
- func (h *HNSWIndex) Search(query []float32, k int) ([]IndexResult, error)
- func (h *HNSWIndex) SearchWithEf(query []float32, k int, ef int) ([]IndexResult, error)
- func (h *HNSWIndex) SetInternal(idx *hnsw.Index)
- func (h *HNSWIndex) Stats() hnsw.IndexStats
- func (h *HNSWIndex) Type() string
- type Index
- type IndexResult
- type IndexType
- type MemoryStorage
- type NotFoundError
- type Option
- type Record
- type RecordSnapshot
- type Result
- type SearchExplanation
- type SearchOption
- type Storage
- type StorageError
Constants ¶
const ( // DistanceCosine uses cosine similarity (higher = more similar). DistanceCosine = floats.DistanceCosine // DistanceDot uses dot product (higher = more similar). DistanceDot = floats.DistanceDot // DistanceEuclidean uses Euclidean distance (lower = more similar). DistanceEuclidean = floats.DistanceEuclidean )
const Version = "0.2.0"
Version is the library version.
Variables ¶
var ( // ErrNotFound is returned when a record or collection is not found. ErrNotFound = errors.New("veclite: not found") // ErrDimensionMismatch is returned when vector dimensions don't match. ErrDimensionMismatch = errors.New("veclite: dimension mismatch") // ErrEmptyVector is returned when an empty vector is provided. ErrEmptyVector = errors.New("veclite: empty vector") // ErrCollectionExists is returned when trying to create a collection that already exists. ErrCollectionExists = errors.New("veclite: collection already exists") // ErrDatabaseClosed is returned when operations are attempted on a closed database. ErrDatabaseClosed = errors.New("veclite: database closed") // ErrInvalidPath is returned when an invalid file path is provided. ErrInvalidPath = errors.New("veclite: invalid path") // ErrCorruptedFile is returned when the database file is corrupted. ErrCorruptedFile = errors.New("veclite: corrupted file") // ErrInvalidVersion is returned when the file version is not supported. ErrInvalidVersion = errors.New("veclite: unsupported file version") // ErrBatchSizeMismatch is returned when batch operation input sizes don't match. ErrBatchSizeMismatch = errors.New("veclite: batch size mismatch") )
Sentinel errors for common conditions.
Functions ¶
This section is empty.
Types ¶
type Collection ¶
type Collection struct {
// contains filtered or unexported fields
}
Collection represents a collection of vectors with the same dimension.
func (*Collection) All ¶
func (c *Collection) All() []*Record
All returns all records in the collection.
func (*Collection) Clear ¶
func (c *Collection) Clear()
Clear removes all records from the collection.
func (*Collection) Count ¶
func (c *Collection) Count() int
Count returns the number of records in the collection.
func (*Collection) Delete ¶
func (c *Collection) Delete(id uint64) error
Delete removes a record by ID.
func (*Collection) DeleteWhere ¶
func (c *Collection) DeleteWhere(filters ...Filter) (int, error)
DeleteWhere removes all records matching the filters. Returns the number of deleted records.
func (*Collection) Dimension ¶
func (c *Collection) Dimension() int
Dimension returns the vector dimension. Returns 0 if no vectors have been inserted yet.
func (*Collection) DistanceType ¶
func (c *Collection) DistanceType() floats.DistanceType
DistanceType returns the distance metric type.
func (*Collection) Find ¶
func (c *Collection) Find(filters ...Filter) ([]*Record, error)
Find retrieves all records matching the filters.
func (*Collection) FindOne ¶
func (c *Collection) FindOne(filters ...Filter) (*Record, error)
FindOne retrieves the first record matching the filters.
func (*Collection) Get ¶
func (c *Collection) Get(id uint64) (*Record, error)
Get retrieves a record by ID.
func (*Collection) GetVector ¶
func (c *Collection) GetVector(id uint64) ([]float32, error)
GetVector retrieves just the vector for a record.
func (*Collection) HasIndex ¶ added in v0.2.0
func (c *Collection) HasIndex() bool
HasIndex returns true if this collection has an index.
func (*Collection) IndexStats ¶ added in v0.2.0
func (c *Collection) IndexStats() *hnsw.IndexStats
IndexStats returns statistics about the collection's index. Returns nil if no index is configured.
func (*Collection) IndexType ¶ added in v0.2.0
func (c *Collection) IndexType() IndexType
IndexType returns the index type for this collection.
func (*Collection) Insert ¶
Insert adds a vector with optional payload to the collection. Returns the assigned record ID.
func (*Collection) InsertBatch ¶
InsertBatch adds multiple vectors with payloads to the collection. Returns the assigned record IDs. If payloads is nil or shorter than vectors, missing payloads are treated as nil.
func (*Collection) Search ¶
func (c *Collection) Search(query []float32, opts ...SearchOption) ([]Result, error)
Search finds the most similar vectors to the query vector.
func (*Collection) SearchExplain ¶ added in v0.2.0
func (c *Collection) SearchExplain(query []float32, opts ...SearchOption) (*SearchExplanation, error)
SearchExplain performs a search and returns detailed statistics.
func (*Collection) Stats ¶
func (c *Collection) Stats() CollectionStats
Stats returns statistics about the collection.
type CollectionOption ¶
type CollectionOption interface {
// contains filtered or unexported methods
}
CollectionOption configures a collection.
func WithDimension ¶
func WithDimension(dim int) CollectionOption
WithDimension sets the vector dimension for the collection. If set, all vectors must match this dimension. If not set (0), the dimension is determined by the first insert.
func WithDistanceType ¶
func WithDistanceType(t floats.DistanceType) CollectionOption
WithDistanceType sets the distance metric for the collection. Default is cosine similarity.
func WithHNSW ¶ added in v0.2.0
func WithHNSW(m, efConstruction int) CollectionOption
WithHNSW enables HNSW indexing for the collection. m is the maximum number of connections per node (default: 16, recommended: 12-48). efConstruction is the candidate list size during construction (default: 200).
func WithHNSWConfig ¶ added in v0.2.0
func WithHNSWConfig(config HNSWConfig) CollectionOption
WithHNSWConfig enables HNSW indexing with custom configuration.
type CollectionSnapshot ¶
type CollectionSnapshot struct {
// Name is the collection name.
Name string
// Dimension is the vector dimension.
Dimension int
// DistanceType is the distance metric.
DistanceType floats.DistanceType
// NextID is the next record ID to assign.
NextID uint64
// Records contains all records in the collection.
Records []*RecordSnapshot
// CreatedAt is when the collection was created.
CreatedAt time.Time
// UpdatedAt is when the collection was last modified.
UpdatedAt time.Time
// IndexType is the type of index (none, hnsw).
IndexType IndexType
// HNSWConfig holds the HNSW configuration (if IndexType is hnsw).
HNSWConfig *HNSWConfig
// HNSWSnapshot holds the HNSW index state (if IndexType is hnsw).
HNSWSnapshot *hnsw.Snapshot
}
CollectionSnapshot is the serializable state of a collection.
func NewCollectionSnapshot ¶
func NewCollectionSnapshot(name string, dimension int, distanceType floats.DistanceType) *CollectionSnapshot
NewCollectionSnapshot creates a new empty collection snapshot.
type CollectionStats ¶
type CollectionStats struct {
// Name is the collection name.
Name string
// Count is the number of records in the collection.
Count int
// Dimension is the vector dimension (0 if not yet set).
Dimension int
// DistanceType is the distance metric used.
DistanceType string
// IndexType is the index type (none, hnsw).
IndexType string
}
CollectionStats contains statistics about a collection.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB represents a VecLite database.
func Open ¶
Open opens or creates a VecLite database at the given path. Use ":memory:" for an in-memory database that won't be persisted.
func (*DB) Collection ¶
func (db *DB) Collection(name string) *Collection
Collection returns a collection by name, creating it if it doesn't exist. This is the preferred way to get collections for most use cases.
func (*DB) Collections ¶
Collections returns the names of all collections.
func (*DB) CreateCollection ¶
func (db *DB) CreateCollection(name string, opts ...CollectionOption) (*Collection, error)
CreateCollection creates a new collection with the given options. Returns an error if the collection already exists.
func (*DB) DropCollection ¶
DropCollection removes a collection and all its data.
func (*DB) GetCollection ¶
func (db *DB) GetCollection(name string) (*Collection, error)
GetCollection returns an existing collection or ErrNotFound.
func (*DB) HasCollection ¶
HasCollection returns true if a collection exists.
type DatabaseSnapshot ¶
type DatabaseSnapshot struct {
// Version is the file format version.
Version uint32
// Collections maps collection names to their snapshots.
Collections map[string]*CollectionSnapshot
// CreatedAt is when the database was created.
CreatedAt time.Time
// UpdatedAt is when the database was last modified.
UpdatedAt time.Time
}
DatabaseSnapshot is the serializable state of the database.
func NewDatabaseSnapshot ¶
func NewDatabaseSnapshot() *DatabaseSnapshot
NewDatabaseSnapshot creates a new empty database snapshot.
type DatabaseStats ¶
type DatabaseStats struct {
// Path is the database file path (":memory:" for in-memory).
Path string
// Collections is the number of collections.
Collections int
// TotalRecords is the total number of records across all collections.
TotalRecords int
// CollectionStats contains stats for each collection.
CollectionStats []CollectionStats
}
DatabaseStats contains statistics about the database.
type DimensionError ¶
DimensionError provides details about dimension mismatches.
func (*DimensionError) Error ¶
func (e *DimensionError) Error() string
func (*DimensionError) Unwrap ¶
func (e *DimensionError) Unwrap() error
type DistanceType ¶ added in v0.2.0
type DistanceType = floats.DistanceType
Re-export distance types for external use.
type FileStorage ¶
type FileStorage struct {
// contains filtered or unexported fields
}
FileStorage is a file-based storage implementation. Uses gob encoding with atomic writes for durability.
func NewFileStorage ¶
func NewFileStorage(path string) *FileStorage
NewFileStorage creates a new file storage for the given path.
func (*FileStorage) Delete ¶
func (f *FileStorage) Delete() error
Delete removes the database file and any backup files.
func (*FileStorage) Exists ¶
func (f *FileStorage) Exists() bool
Exists returns true if the database file exists.
func (*FileStorage) Load ¶
func (f *FileStorage) Load() (*DatabaseSnapshot, error)
Load reads the database from the file. Returns nil, nil if the file doesn't exist yet.
func (*FileStorage) Save ¶
func (f *FileStorage) Save(snapshot *DatabaseSnapshot) error
Save writes the database to the file using atomic write pattern. Writes to .tmp file, then renames old to .bak, then renames .tmp to final.
type Filter ¶
type Filter interface {
// Match returns true if the record matches the filter criteria.
Match(r *Record) bool
}
Filter is an interface for filtering records based on payload values.
func Contains ¶
Contains creates a filter that matches records where payload[key] contains the substring.
func NotEqual ¶
NotEqual creates a filter that matches records where payload[key] does not equal value.
func NotIn ¶
NotIn creates a filter that matches records where payload[key] is not in the given values.
type FilterFunc ¶
FilterFunc is a function adapter for the Filter interface.
func (FilterFunc) Match ¶
func (f FilterFunc) Match(r *Record) bool
Match implements Filter interface.
type HNSWConfig ¶ added in v0.2.0
type HNSWConfig struct {
// M is the maximum number of connections per node.
M int
// EfConstruction is the size of the candidate list during index construction.
EfConstruction int
// EfSearch is the default size of the candidate list during search.
EfSearch int
}
HNSWConfig holds HNSW index configuration.
type HNSWIndex ¶ added in v0.2.0
type HNSWIndex struct {
// contains filtered or unexported fields
}
HNSWIndex wraps the HNSW index to implement the Index interface.
func NewHNSWIndex ¶ added in v0.2.0
func NewHNSWIndex(dimension int, distanceType floats.DistanceType, m, efConstruction int) *HNSWIndex
NewHNSWIndex creates a new HNSW index with the given parameters.
func NewHNSWIndexWithConfig ¶ added in v0.2.0
func NewHNSWIndexWithConfig(dimension int, distanceType floats.DistanceType, config hnsw.Config) *HNSWIndex
NewHNSWIndexWithConfig creates a new HNSW index with a custom configuration.
func (*HNSWIndex) Internal ¶ added in v0.2.0
Internal returns the underlying HNSW index (for serialization).
func (*HNSWIndex) Search ¶ added in v0.2.0
func (h *HNSWIndex) Search(query []float32, k int) ([]IndexResult, error)
Search finds the k nearest neighbors to the query vector.
func (*HNSWIndex) SearchWithEf ¶ added in v0.2.0
SearchWithEf searches with a custom ef parameter.
func (*HNSWIndex) SetInternal ¶ added in v0.2.0
SetInternal sets the underlying HNSW index (for deserialization).
func (*HNSWIndex) Stats ¶ added in v0.2.0
func (h *HNSWIndex) Stats() hnsw.IndexStats
Stats returns statistics about the index.
type Index ¶ added in v0.2.0
type Index interface {
// Insert adds a vector with the given ID to the index.
Insert(id uint64, vector []float32) error
// Delete removes a vector from the index.
Delete(id uint64) error
// Search finds the k nearest neighbors to the query vector.
// Returns IDs and distances/similarities.
Search(query []float32, k int) ([]IndexResult, error)
// SearchWithEf searches with a custom ef parameter (for HNSW).
// For indexes that don't support ef, this should behave like Search.
SearchWithEf(query []float32, k int, ef int) ([]IndexResult, error)
// Count returns the number of vectors in the index.
Count() int
// Type returns the index type name.
Type() string
}
Index is the interface for vector search indexes. Implementations can provide different algorithms (brute-force, HNSW, etc.).
type IndexResult ¶ added in v0.2.0
IndexResult represents a search result from an index.
type MemoryStorage ¶
type MemoryStorage struct {
// contains filtered or unexported fields
}
MemoryStorage is an in-memory storage implementation. Data is not persisted and will be lost when the database is closed.
func NewMemoryStorage ¶
func NewMemoryStorage() *MemoryStorage
NewMemoryStorage creates a new in-memory storage.
func (*MemoryStorage) Close ¶
func (m *MemoryStorage) Close() error
Close is a no-op for memory storage.
func (*MemoryStorage) Load ¶
func (m *MemoryStorage) Load() (*DatabaseSnapshot, error)
Load returns the stored snapshot or nil if none exists.
func (*MemoryStorage) Save ¶
func (m *MemoryStorage) Save(snapshot *DatabaseSnapshot) error
Save stores the snapshot in memory.
type NotFoundError ¶
type NotFoundError struct {
Type string // "record", "collection", etc.
ID string // Identifier that was not found
}
NotFoundError provides details about what was not found.
func (*NotFoundError) Error ¶
func (e *NotFoundError) Error() string
func (*NotFoundError) Unwrap ¶
func (e *NotFoundError) Unwrap() error
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures the database.
func WithReadOnly ¶
WithReadOnly opens the database in read-only mode. Write operations will return an error.
func WithSyncOnWrite ¶
WithSyncOnWrite enables automatic sync after each write operation. This is slower but ensures durability.
type Record ¶
type Record struct {
// ID is the unique identifier for this record.
ID uint64
// Vector is the embedding vector.
Vector []float32
// Payload contains arbitrary metadata associated with the vector.
Payload map[string]any
// CreatedAt is when the record was inserted.
CreatedAt time.Time
// UpdatedAt is when the record was last updated.
UpdatedAt time.Time
}
Record represents a stored vector with its metadata.
type RecordSnapshot ¶
type RecordSnapshot struct {
// ID is the record's unique identifier.
ID uint64
// Vector is the embedding vector.
Vector []float32
// Payload contains arbitrary metadata.
Payload map[string]any
// CreatedAt is when the record was inserted.
CreatedAt time.Time
// UpdatedAt is when the record was last updated.
UpdatedAt time.Time
}
RecordSnapshot is the serializable state of a record.
type Result ¶
type Result struct {
// Record is the matched record.
Record *Record
// Score is the similarity/distance score.
// For cosine/dot: higher is more similar.
// For euclidean: lower is more similar.
Score float32
}
Result represents a search result with its similarity score.
type SearchExplanation ¶ added in v0.2.0
type SearchExplanation struct {
// Results contains the search results.
Results []Result
// IndexType is the type of index used (none, hnsw).
IndexType string
// NodesVisited is the number of nodes visited during search.
// Only populated for HNSW searches.
NodesVisited int
// LayersVisited is the number of HNSW layers visited.
// Only populated for HNSW searches.
LayersVisited int
// Duration is how long the search took.
Duration time.Duration
// BruteForce indicates whether brute-force search was used.
BruteForce bool
}
SearchExplanation provides details about how a search was performed.
type SearchOption ¶
type SearchOption interface {
// contains filtered or unexported methods
}
SearchOption configures search behavior.
func Threshold ¶
func Threshold(t float32) SearchOption
Threshold sets the minimum similarity score for results. For cosine/dot: results with score >= threshold are returned. For euclidean: results with score <= threshold are returned.
func TopK ¶
func TopK(k int) SearchOption
TopK sets the maximum number of results to return. Default is 10.
func WithEfSearch ¶ added in v0.2.0
func WithEfSearch(ef int) SearchOption
WithEfSearch sets the efSearch parameter for HNSW search. Higher values improve recall at the cost of speed. Has no effect on collections without HNSW index.
func WithFilter ¶
func WithFilter(f Filter) SearchOption
WithFilter adds a filter to the search. Multiple filters are combined with AND logic.
func WithFilters ¶
func WithFilters(filters ...Filter) SearchOption
WithFilters adds multiple filters to the search. All filters are combined with AND logic.
type Storage ¶
type Storage interface {
// Load reads the database from storage.
// Returns nil, nil if the database doesn't exist yet.
Load() (*DatabaseSnapshot, error)
// Save writes the database to storage.
Save(snapshot *DatabaseSnapshot) error
// Close releases any resources held by the storage.
Close() error
}
Storage is the interface for database persistence.
type StorageError ¶
StorageError wraps storage-related errors with context.
func (*StorageError) Error ¶
func (e *StorageError) Error() string
func (*StorageError) Unwrap ¶
func (e *StorageError) Unwrap() error
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
veclite
command
Command veclite provides a CLI for interacting with VecLite databases.
|
Command veclite provides a CLI for interacting with VecLite databases. |
|
internal
|
|
|
floats
Package floats provides optimized floating-point vector operations.
|
Package floats provides optimized floating-point vector operations. |
|
hnsw
Package hnsw implements the Hierarchical Navigable Small World graph algorithm for approximate nearest neighbor search.
|
Package hnsw implements the Hierarchical Navigable Small World graph algorithm for approximate nearest neighbor search. |