vector

package
v0.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: LGPL-3.0 Imports: 9 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package vector stores embedding vectors and finds the closest ones. Store is the port: its documents live in collections, each found by a Coord, an opaque index (the hard isolation boundary, e.g. a tenant) and two opaque coordinates within it, partition and collection. MemStore in this package is a brute-force in-memory Store for tests, tiny corpora and evaluation; the production Stores live in subpackages: sqlitevec (SQLite with the sqlite-vec extension, requires CGO) and pgvec (Postgres with the pgvector extension). vectortest is the conformance suite all three pass.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrDimensions reports a vector whose length is not the store's: a
	// query or chunk from another model, or a store opened with other
	// dimensions than its tables were built with.
	ErrDimensions = errors.New("vector: wrong number of dimensions")
	// ErrInvalidVector reports a vector that cannot be compared by cosine:
	// one holding a NaN or an infinity, the zero vector, which has no
	// direction, or one whose float32 norm underflows or overflows (see
	// Validate).
	ErrInvalidVector = errors.New("vector: invalid vector")
	// ErrModelMismatch reports a write or a search naming another model than
	// the one a collection's vectors were made with.
	ErrModelMismatch = errors.New("vector: collection holds another model's vectors")
	// ErrLegacySchema reports an index a SQL store finds in the tables of
	// the schema of v0.1.1 and earlier.
	// Every read and write of it is refused until DeleteIndex drops those
	// tables, or the store is opened WithGeneration for a table set of its
	// own; then it is indexed again.
	ErrLegacySchema = errors.New("vector: index has tables of the schema before this version")
	// ErrEmptyIndex reports a Coord, or an index handed to DeleteIndex,
	// whose index is empty: the index is the isolation boundary and must be
	// named. Every method of every Store checks it first.
	ErrEmptyIndex = errors.New("vector: empty index")
	// ErrInvalidID reports a document id, a partition, a collection or a
	// model that no Store can keep alike: one that is not valid UTF-8 or
	// holds a NUL byte (a Postgres TEXT column refuses both, and SQLite's
	// JSON id lists turn invalid bytes into U+FFFD), and an empty document
	// id. Every method of every Store checks the strings it is handed
	// before it reads or writes anything (see CheckCoord and CheckID).
	ErrInvalidID = errors.New("vector: invalid id")
)

Functions

func CheckCoord

func CheckCoord(c Coord) error

CheckCoord checks the Coord every method of a Store is handed, the same way in each: a non-empty index (ErrEmptyIndex), and a partition and a collection that are valid UTF-8 without NUL bytes (ErrInvalidID). The index itself may hold any bytes: the SQL stores hash it into their table names and never store it. It is for implementations of Store.

func CheckDocs

func CheckDocs(c Coord, after string) error

CheckDocs checks what a Store's Docs is handed: c passes CheckCoord and after is empty (the first page) or passes CheckID. It is for implementations of Store.

func CheckID

func CheckID(id string) error

CheckID checks a document id a Store is handed: not empty, valid UTF-8 and without NUL bytes (ErrInvalidID). It is for implementations of Store and for callers that want to refuse such an id before they do any work for it.

func CheckRead

func CheckRead(c Coord, ids ...string) error

CheckRead checks what a Store's reads and deletes are handed: c passes CheckCoord and every id passes CheckID. It is for implementations of Store.

func CheckSearch

func CheckSearch(c Coord, dims int, q Query) error

CheckSearch checks what every Store's Search is handed, the same way in each: a Coord that passes CheckCoord, a model and Only and Exclude ids as CheckWrite and CheckID take them, and at least one query vector, each of which passes Validate for dims. It is for implementations of Store.

func CheckWrite

func CheckWrite(c Coord, model string, dims int, docs []Doc) error

CheckWrite checks what every Store's Upsert is handed, the same way in each: a Coord that passes CheckCoord, a model that is valid UTF-8 without NUL bytes, distinct document ids that pass CheckID, and chunk vectors that pass Validate for dims. It is for implementations of Store.

func Validate

func Validate(vec []float32, dims int) error

Validate reports whether vec can be stored or searched with in a store of dims dimensions: it must have exactly dims entries (ErrDimensions), all of them finite, and a sum of squares that is neither 0 nor infinite when computed in float32, as the SQL backends compute the norm (ErrInvalidVector). The zero vector fails so, and so does one too small or too large for a float32 norm, such as {1e-25, 1e-25} or {1e20, 1e20}, which a backend would score as infinite, NaN or 0 whatever its direction.

Types

type Chunk

type Chunk struct {
	Seq    int
	Text   string
	Vector []float32
}

Chunk is one embedded piece of a document as handed to a Store: its position within the document, the text that was embedded, and its vector.

type Coord

type Coord struct {
	Index      string
	Partition  string
	Collection string
}

Coord locates one collection: Index is the hard isolation boundary and must not be empty; Partition and Collection place the collection within it. An empty Partition or Collection is a value like any other: it matches only the empty one, never every one.

func (Coord) String

func (c Coord) String() string

String implements fmt.Stringer for error messages.

type Doc

type Doc struct {
	ID     string
	Hash   string
	Chunks []Chunk
}

Doc is one document as handed to Upsert: its id, the caller's fingerprint of its content, and its chunks. A document without chunks keeps its hash and is never found.

type DocInfo

type DocInfo struct {
	ID   string
	Hash string
}

DocInfo is one document as Docs lists it.

type Match

type Match struct {
	Coord Coord
	DocID string
	Seq   int
	Text  string
	Score float64
	Query int
}

Match is one search hit: the best-scoring chunk of a document, its cosine score, and Query, the index in Query.Vectors of the vector it scored that against. Coord says which collection the document is in, which tells apart two documents of one id in a search that spans several.

type MemStore

type MemStore struct {
	// contains filtered or unexported fields
}

MemStore is a Store that keeps everything in memory and answers searches by brute force, scoring every chunk in scope with exact cosine similarity. It suits tests, tiny corpora and evaluation, where no approximate index may colour the results. An index's dimensions are those of the first vector written to it, as a SQL store's tables have the dimensions they were built with, until DeleteIndex forgets it. It is safe for concurrent use.

func NewMemStore

func NewMemStore() *MemStore

NewMemStore returns an empty MemStore.

func (*MemStore) Chunks

func (s *MemStore) Chunks(_ context.Context, c Coord, id string) ([]Chunk, error)

Chunks implements Store; the vectors are copies.

func (*MemStore) Delete

func (s *MemStore) Delete(_ context.Context, c Coord, ids ...string) error

Delete implements Store.

func (*MemStore) DeleteCollection

func (s *MemStore) DeleteCollection(_ context.Context, c Coord) error

DeleteCollection implements Store.

func (*MemStore) DeleteIndex

func (s *MemStore) DeleteIndex(_ context.Context, index string) error

DeleteIndex implements Store.

func (*MemStore) Docs

func (s *MemStore) Docs(_ context.Context, c Coord, after string, limit int) ([]DocInfo, error)

Docs implements Store.

func (*MemStore) Hashes

func (s *MemStore) Hashes(_ context.Context, c Coord, ids ...string) (map[string]string, error)

Hashes implements Store.

func (*MemStore) Model

func (s *MemStore) Model(_ context.Context, c Coord) (string, error)

Model implements Store.

func (*MemStore) Search

func (s *MemStore) Search(_ context.Context, c Coord, q Query) ([]Match, error)

Search implements Store, scoring every chunk in scope against every query vector.

func (*MemStore) Upsert

func (s *MemStore) Upsert(_ context.Context, c Coord, model string, docs ...Doc) error

Upsert implements Store. It keeps copies of the chunks, so the caller may reuse its slices.

type Query

type Query struct {
	Vectors        [][]float32
	Limit          int
	AllPartitions  bool
	AllCollections bool
	Only           []string
	Exclude        []string
	Model          string
}

Query is what Search ranks. Vectors are the query vectors, at least one: a document scores its best chunk against any of them, so a search with the chunks of one document, or the frames of one video, ranks in one pass what one search per vector would (see Store). By default it ranks the documents of exactly the collection Search is given; AllPartitions and AllCollections open that coordinate, so the search spans every partition or collection of the index. A non-empty Only keeps the documents with those ids, and Exclude leaves its ids out (e.g. the document a "more like this" search starts from). A non-empty Model must be the model the collections in scope were written with (see Store).

type Store

type Store interface {
	Upsert(ctx context.Context, c Coord, model string, docs ...Doc) error
	Delete(ctx context.Context, c Coord, ids ...string) error
	DeleteCollection(ctx context.Context, c Coord) error
	DeleteIndex(ctx context.Context, index string) error
	Hashes(ctx context.Context, c Coord, ids ...string) (map[string]string, error)
	Docs(ctx context.Context, c Coord, after string, limit int) ([]DocInfo, error)
	Chunks(ctx context.Context, c Coord, id string) ([]Chunk, error)
	Model(ctx context.Context, c Coord) (string, error)
	Search(ctx context.Context, c Coord, q Query) ([]Match, error)
}

Store persists the chunk vectors of documents in collections and ranks them against one or more query vectors by cosine. Implementations must never let one index's data appear in another's, and must be safe for concurrent use.

Upsert stores docs in c in one atomic step, each replacing what was stored under its id; when model is not empty, the write records it as the collection's model, and while the collection holds documents (in any of its partitions, which share one model) a write or search with another non-empty model fails with ErrModelMismatch. A collection without documents holds no model: the next write records its own, so emptying a collection (DeleteCollection) is how it moves to another model. Model returns the model of c's collection, "" when it records none or holds no documents, so a caller can find a mismatch before it spends time on embedding.

Delete removes the documents of the given ids, DeleteCollection every document of c (its partition and collection, other partitions of the collection untouched), and DeleteIndex every collection of an index; unknown ids, collections and indexes are no error. Hashes returns the stored hash of each of the given ids it knows. Docs returns the documents of c ordered by id (byte by byte), at most limit of them (all when limit <= 0) and only those after the id after, so a caller can page through a collection, e.g. to find what it deleted while the store was away; the number of documents is the length of the full list. Chunks returns a document's stored chunks, vectors included, ordered by Seq, so a caller can search with what is already indexed instead of embedding it again; an unknown document has none.

Search scores every chunk in scope by its best cosine against any of q.Vectors and returns the best chunk of each of the q.Limit best-scoring documents, in descending score, then by document id, then by Seq; a document's best chunk is the lowest Seq among its best-scoring ones, and Match.Query the lowest index among the vectors that score it so. That is what merging one search per query vector gives, keeping each document's best match, in one pass over the chunks. Vectors must pass Validate for the store's dimensions, or the call fails with ErrDimensions or ErrInvalidVector. Reads of an index never written return nothing and create nothing.

Every method checks its arguments before it reads or writes anything, the same way in every implementation (CheckCoord, CheckID, CheckRead, CheckDocs, CheckWrite, CheckSearch): an empty index is ErrEmptyIndex, and a document id, partition, collection or model no backend can keep alike is ErrInvalidID. An error of the database underneath comes back wrapped with "vector:", the backend's name and the operation.

Directories

Path Synopsis
internal
sqlstore
Package sqlstore implements vector.Store on database/sql for the databases a Dialect describes.
Package sqlstore implements vector.Store on database/sql for the databases a Dialect describes.
Package pgvec is a vector.Store backed by Postgres with the pgvector extension.
Package pgvec is a vector.Store backed by Postgres with the pgvector extension.
Package sqlitevec is a vector.Store backed by SQLite with the sqlite-vec extension.
Package sqlitevec is a vector.Store backed by SQLite with the sqlite-vec extension.
Package vectortest is the conformance suite for vector.Store.
Package vectortest is the conformance suite for vector.Store.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL