Documentation
¶
Overview ¶
Package qdb examples and documentation.
Basic Usage ¶
Here's a simple example of using QDB for key-value operations:
package main import ( "context" "fmt" "log" "github.com/mew-sh/qdb" ) func main() { ctx := context.Background() // Create database with default config db, err := qdb.New(qdb.DefaultConfig()) if err != nil { log.Fatal(err) } defer db.Close() // Store values db.Set(ctx, "user:1:name", "Alice") db.Set(ctx, "user:1:age", 30) db.Set(ctx, "user:1:score", 95.5) // Retrieve values name, _ := db.Get(ctx, "user:1:name").String() age, _ := db.Get(ctx, "user:1:age").Int() score, _ := db.Get(ctx, "user:1:score").Float() fmt.Printf("User: %s, Age: %d, Score: %.1f\n", name, age, score) }
Vector Search ¶
QDB supports efficient vector similarity search:
// Store vectors with metadata vector1 := []float64{1.0, 2.0, 3.0, 4.0} metadata1 := map[string]interface{}{ "category": "document", "tags": []string{"important", "review"}, } db.SetVector(ctx, "doc1", vector1, metadata1) // Search for similar vectors query := []float64{1.1, 2.1, 3.1, 4.1} results, err := db.SearchVector(ctx, query, 5) if err != nil { log.Fatal(err) } for _, result := range results { fmt.Printf("Key: %s, Score: %.3f\n", result.Key, result.Score) }
Filtered Search ¶
Combine vector search with metadata filtering:
filter := &qdb.FilterCondition{ Field: "category", Operator: "eq", Value: "document", } results, err := db.SearchVector(ctx, query, 5, filter)
Configuration ¶
Customize QDB behavior with configuration options:
config := &qdb.Config{ DatabasePath: "my-database.db", UseMemory: false, // Use file storage HNSWConfig: &qdb.HNSWConfig{ M: 16, EfConstruction: 200, EfSearch: 50, MaxLayers: 6, Ml: 1.0 / math.Log(2.0), }, } db, err := qdb.New(config)
Package qdb provides a high-performance in-memory database with vector search capabilities.
QDB combines Redis-style key-value operations with advanced vector search, all implemented in pure Go without external dependencies.
Features ¶
- Redis-like O(1) hash table operations - Vector search using HNSW (Hierarchical Navigable Small World) algorithm - Exact K-nearest neighbors search - Hybrid queries with filtering - Support for multiple data types (string, int, float64, bool, []byte, slices, maps) - Thread-safe concurrent operations - File-based or in-memory storage
Quick Start ¶
package main import ( "context" "log" "github.com/mew-sh/qdb" ) func main() { ctx := context.Background() // Create database instance config := qdb.DefaultConfig() db, err := qdb.New(config) if err != nil { log.Fatal(err) } defer db.Close() // Basic key-value operations db.Set(ctx, "key", "value") result := db.Get(ctx, "key") value, _ := result.String() // Vector operations vector := []float64{1.0, 2.0, 3.0, 4.0} metadata := map[string]interface{}{"category": "test"} db.SetVector(ctx, "vec1", vector, metadata) query := []float64{1.1, 2.1, 3.1, 4.1} results, _ := db.SearchVector(ctx, query, 5) }
Index ¶
- Variables
- type Config
- type FileStorage
- type FilterCondition
- type HNSW
- type HNSWConfig
- type HNSWNode
- type HashBucket
- type HashEntry
- type HashTable
- type QDB
- func (q *QDB) Close() error
- func (q *QDB) Delete(ctx context.Context, key string) error
- func (q *QDB) Exists(ctx context.Context, key string) (bool, error)
- func (q *QDB) Get(ctx context.Context, key string) *Result
- func (q *QDB) SearchVector(ctx context.Context, query []float64, k int, filters ...*FilterCondition) ([]*SearchResult, error)
- func (q *QDB) SearchVectorExact(ctx context.Context, query []float64, k int, filters ...*FilterCondition) ([]*SearchResult, error)
- func (q *QDB) Set(ctx context.Context, key string, value interface{}) error
- func (q *QDB) SetVector(ctx context.Context, key string, vector []float64, metadata interface{}) error
- type Result
- type SearchResult
- type StorageRecord
- type Vector
- type VectorDB
- func (vdb *VectorDB) SearchANN(query []float64, k int, filters ...*FilterCondition) ([]*SearchResult, error)
- func (vdb *VectorDB) SearchExact(query []float64, k int, filters ...*FilterCondition) ([]*SearchResult, error)
- func (vdb *VectorDB) SetVector(key string, vector []float64, metadata interface{}) error
Constants ¶
This section is empty.
Variables ¶
var ( ErrKeyNotFound = errors.New("key not found") ErrInvalidVector = errors.New("invalid vector") ErrDimensionMismatch = errors.New("vector dimension mismatch") ErrEmptyIndex = errors.New("index is empty") ErrInvalidFilter = errors.New("invalid filter condition") ErrStorageClosed = errors.New("storage is closed") )
Common errors
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct { DatabasePath string HNSWConfig *HNSWConfig UseMemory bool // If true, uses in-memory storage instead of file }
Config holds configuration options for QDB instances. It allows customization of storage backend, HNSW parameters, and operational modes.
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a default configuration DefaultConfig returns a Config with sensible default values for most use cases. The default configuration uses file-based storage with balanced HNSW parameters optimized for both accuracy and performance.
type FileStorage ¶
type FileStorage struct {
// contains filtered or unexported fields
}
FileStorage handles file-based persistence
func NewFileStorage ¶
func NewFileStorage(filePath string, useMemory bool) (*FileStorage, error)
NewFileStorage creates a new file storage instance
func (*FileStorage) Delete ¶
func (fs *FileStorage) Delete(key string) error
Delete removes a record from storage
func (*FileStorage) Load ¶
func (fs *FileStorage) Load(key string) (*StorageRecord, error)
Load retrieves a record by key from storage
func (*FileStorage) LoadAll ¶
func (fs *FileStorage) LoadAll() ([]*StorageRecord, error)
LoadAll loads all records from storage
func (*FileStorage) Store ¶
func (fs *FileStorage) Store(record *StorageRecord) error
Store saves a record to storage
type FilterCondition ¶
type FilterCondition struct { Field string `json:"field"` Operator string `json:"operator"` // "eq", "ne", "gt", "lt", "gte", "lte", "in" Value interface{} `json:"value"` }
FilterCondition represents a filter condition for search FilterCondition defines a filtering condition for vector search operations. It allows filtering vectors based on their metadata using various operators such as equality, comparison, and membership tests.
type HNSW ¶
type HNSW struct {
// contains filtered or unexported fields
}
HNSW implements Hierarchical Navigable Small World graphs
type HNSWConfig ¶
type HNSWConfig struct { M int // Number of bi-directional links created for every new element during construction EfConstruction int // Size of the dynamic candidate list EfSearch int // Size of the dynamic candidate list used during search MaxLayers int // Maximum number of layers Ml float64 // Level generation parameter }
HNSWConfig holds HNSW algorithm parameters
type HNSWNode ¶
type HNSWNode struct { ID int Vector []float64 Level int Connections map[int][]int // layer -> list of connected node IDs }
HNSWNode represents a node in the HNSW graph
type HashBucket ¶
type HashBucket struct {
// contains filtered or unexported fields
}
HashBucket represents a bucket in the hash table
type HashTable ¶
type HashTable struct {
// contains filtered or unexported fields
}
HashTable implements a Redis-style hash table with O(1) operations
type QDB ¶
type QDB struct {
// contains filtered or unexported fields
}
QDB represents the main database instance that provides both key-value storage and vector search capabilities. It combines a Redis-style hash table for O(1) key-value operations with HNSW-based vector indexing for efficient similarity search.
QDB is thread-safe and supports concurrent operations through fine-grained locking. It can operate in memory-only mode for maximum performance or with file-based persistence for data durability.
func New ¶
New creates a new QDB instance with the specified configuration. It initializes the hash table, vector database, and storage backend. If config is nil, DefaultConfig() is used.
Returns an error if the storage backend cannot be initialized or if existing data cannot be loaded.
func (*QDB) SearchVector ¶
func (q *QDB) SearchVector(ctx context.Context, query []float64, k int, filters ...*FilterCondition) ([]*SearchResult, error)
SearchVector performs ANN search using HNSW
func (*QDB) SearchVectorExact ¶
func (q *QDB) SearchVectorExact(ctx context.Context, query []float64, k int, filters ...*FilterCondition) ([]*SearchResult, error)
SearchVectorExact performs exact K-NN search
type Result ¶
type Result struct {
// contains filtered or unexported fields
}
Result represents a query result Result wraps the result of a Get operation, providing type-safe methods to extract values in various formats. It implements a fluent interface for easy value conversion and error handling.
type SearchResult ¶
type SearchResult struct { Key string `json:"key"` Vector []float64 `json:"vector"` Score float64 `json:"score"` Metadata interface{} `json:"metadata"` }
SearchResult represents a search result SearchResult represents a single result from a vector search operation. It contains the key, matching vector, similarity score, and associated metadata.
type StorageRecord ¶
type StorageRecord struct { Key string `json:"key"` Value interface{} `json:"value"` DataType string `json:"data_type"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` }
StorageRecord represents a record in storage
type Vector ¶
type Vector struct { ID int `json:"id"` Key string `json:"key"` Data []float64 `json:"data"` Dimension int `json:"dimension"` Metadata interface{} `json:"metadata"` CreatedAt time.Time `json:"created_at"` }
Vector represents a vector with metadata
type VectorDB ¶
type VectorDB struct {
// contains filtered or unexported fields
}
VectorDB handles vector storage and search operations
func NewVectorDB ¶
func NewVectorDB(storage *FileStorage, config *HNSWConfig) *VectorDB
NewVectorDB creates a new vector database
func (*VectorDB) SearchANN ¶
func (vdb *VectorDB) SearchANN(query []float64, k int, filters ...*FilterCondition) ([]*SearchResult, error)
SearchANN performs approximate nearest neighbor search using HNSW
func (*VectorDB) SearchExact ¶
func (vdb *VectorDB) SearchExact(query []float64, k int, filters ...*FilterCondition) ([]*SearchResult, error)
SearchExact performs exact K-NN search