corvid

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 5 Imported by: 0

README

corvid-go

The Go binding for corvid — an embedded database with a typed C ABI. It links the engine's published FFI artifacts (the platform cdylib and corvid.h) over cgo and carries an idiomatic Go API on top — and it proves, continuously and outside the engine repo, that the published artifacts drive a real Go consumer to the same verdicts the engine's own suite produces: the golden-suite port in golden_test.go replays the engine's 267-line fixture suite through this binding.

Documentation: the corvid docs site is canonical — the C ABI section documents every symbol this binding links (handles, ownership, errors, threading), and docs/PLAN.md records this binding's architecture ruling and lifetime mapping.

The architecture ruling: cgo over the C ABI, release artifacts only

Deliberately different from the node/python bindings (Rust-source builds): Go users expect a system/shared library or a bundled download, not a Rust toolchain. make deps fetches the pinned engine release archive for the host platform, sha256-verifies it against the release's checksums.txt, byte-compares the release's golden fixtures against the ones vendored here, and normalizes corvid.h + the cdylib into gitignored deps/current/ (on Windows the MSVC import library is also copied under the libcorvid.dll.a name so mingw-w64's ld finds it). Requirements stop at "a C compiler" — which cgo already needs.

  • No Rust toolchain, ever.
  • One exact engine pinv0.4.1, living in one variable per fetch script (CORVID_VERSION in fetch.sh, $CorvidVersion in fetch.ps1), stamped into deps/version.txt.
  • No vendored binaries in git (deps/ is gitignored) and no network at build time.
  • Published-artifact defects are findings, never local patches.

Quick start

Requirements: Go ≥ 1.26 (CI exercises 1.27.x and 1.26.x), a C compiler (CGO enabled — the default when one is present), curl + shasum/sha256sum (macOS/Linux) or PowerShell 5+ (Windows).

make deps          # fetch + verify corvid v0.4.1 into deps/current
go test ./...      # the golden suite (267 executable lines, 8 fixtures)

On Windows (PowerShell), make deps is ./fetch.ps1; there is no rpath there, so put the cdylib on the DLL search path before building or testing:

./fetch.ps1
$env:PATH = "$(Get-Location)\deps\current;$env:PATH"
go test ./...

A taste of the API:

package main

import (
	"fmt"

	"github.com/corvid-db/corvid-go"
)

func main() {
	db, err := corvid.OpenMemory()
	if err != nil {
		panic(err)
	}
	defer db.Close()

	docs, err := db.Collection("docs")
	if err != nil {
		panic(err)
	}
	defer docs.Close()

	// map[string]any / []any / []float32 / []byte / string / int64 /
	// float64 / bool / nil — NaN and ±inf cross bit-exactly.
	err = docs.Insert([]byte("p1"), map[string]any{
		"name": "ada",
		"v":    []float32{1, 0, 0},
	})

	if err := docs.CreateVectorIndex("v", corvid.MetricCosine); err != nil {
		panic(err)
	}

	// hybrid: filter + vector + text, RRF-fused, MMR-reranked
	rows, err := docs.Query().
		Filter(corvid.Field("name").Eq("ada")).
		Vector("v", []float32{1, 0, 0}, 3, corvid.MetricCosine).
		Select("name").
		Run()
	if err != nil {
		panic(err)
	}
	for _, r := range rows {
		fmt.Println(string(r.Key), r.Doc, r.Score)
	}

	n, _ := docs.Query().Filter(corvid.Field("name").StartsWith("a")).Count()
	fmt.Println("matched:", n)
}

Errors are *corvid.CorvidError (implements error + Code()) — Go errors, never panics. Db and Collection are safe for concurrent use; Query/Predicate builders are single-goroutine, build-once, consumed-by-the-terminal. Close deliberately on every handle; the runtime finalizers are backstops only. Concurrent use carries the FFI §6 close caveat: close a Db/Collection only after every concurrent operation on it has completed — freeing engine memory while another thread is inside a call on it is undefined behavior, and the binding's closed-handle gate (checkOpen) is TOCTOU by design, a loud rejection of use-after-close, not a lock.

Documents and maps

Engine v0.3.0 added the map-key iterator (corvid_value_map_keys, the §4.4 erratum): every decode in this binding enumerates map keys through it — Get/Scan/Page/query rows decode documents COMPLETE on any database, whatever wrote the data, unknown and UTF-8 keys included (mapkeys_test.go pins the across-a-reopen shape that the v0.2.2-era candidate-key oracle could not do; the decision-log row in docs/PLAN.md records the collapse). Retrieval queries still return Row.Doc == nil without Query.Select(...) (retrieval carries keys and scores; read the document explicitly), and (*Collection).PhraseSearch rows always carry documents.

Installing the engine system-wide (alternative to deps/)

If corvid is installed as a system library (e.g. from a source build), point cgo at it instead of running make deps:

export CGO_CFLAGS="-I/usr/local/include"
export CGO_LDFLAGS="-L/usr/local/lib -lcorvid"
# macOS may additionally need: export DYLD_LIBRARY_PATH=/usr/local/lib
go build ./...

CI

A linux/macos/windows × Go {1.27.x, 1.26.x} matrix (.github/workflows/ci.yml): fetch + verify the pinned artifacts, go vet, and go test ./... (the golden suite) on every leg; golangci-lint on Linux.

Surface manifest (docs/SURFACE.tsv)

Every construct of the engine's public surface (the radar-enforced list the engine publishes as scripts/bindings/surface.tsv at each release tag) is resolved in docs/SURFACE.tsv: the Go API exposing it plus the test that proves it (golden fixture line references), or N/A + reason where the v1 binding deliberately does not expose it. scripts/surface-gate.sh fails CI when a line is unresolved, a cell is empty, or the N/A count drifts from the committed baseline — so an engine pin bump that changes the surface lands in this gate, not in a user's bug report.

Versioning

The engine pin lives in one variable in the fetch scripts (CORVID_VERSION=v0.4.1). Artifacts always come from that exact tag's GitHub release and are sha256-verified; deps/ is never committed.

License

MIT — see LICENSE.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FFIVersion

func FFIVersion() uint32

FFIVersion returns the ABI version of the loaded library (bindings verify it equals 1 before anything else — FFI.md §4.1).

Types

type Collection

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

Collection is a handle to one collection of a Db. It is safe for concurrent use, under the same §6 close caveat as Db: Close only after every concurrent operation on it has completed — freeing the engine handle while another thread is inside a call on it is undefined behavior, and the Db's checkOpen gate is TOCTOU by design.

func (*Collection) Close

func (coll *Collection) Close()

Close releases the collection handle. Idempotent; a runtime finalizer performs it as a backstop for leaked handles. Note that live collection handles make Db.Compact answer ErrBusy.

func (*Collection) CompareAndSet

func (coll *Collection) CompareAndSet(key []byte, expected, replacement any) (applied bool, err error)

CompareAndSet atomically tests-and-sets key: applied reports whether expected matched. A nil expected means "key must be absent"; a nil replacement means "delete on match". Equality is the engine's semantic equality (NaN == NaN regardless of payload, -0.0 == 0.0).

func (*Collection) CreateCompoundIndex

func (coll *Collection) CreateCompoundIndex(fields ...string) error

CreateCompoundIndex indexes the concatenation of fields.

func (*Collection) CreateGeoIndex

func (coll *Collection) CreateGeoIndex(field string) error

CreateGeoIndex indexes a geo field (lat/lon array or map) for radius/bbox/nearest queries.

func (*Collection) CreateScalarIndex

func (coll *Collection) CreateScalarIndex(field string) error

CreateScalarIndex indexes a scalar field for comparisons.

func (*Collection) CreateTextIndex

func (coll *Collection) CreateTextIndex(field string) error

CreateTextIndex indexes a text field for BM25 queries (in-memory).

func (*Collection) CreateTextIndexOnDisk

func (coll *Collection) CreateTextIndexOnDisk(field string) error

CreateTextIndexOnDisk is CreateTextIndex with an on-disk index.

func (*Collection) CreateVectorIndex

func (coll *Collection) CreateVectorIndex(field string, metric Metric) error

CreateVectorIndex indexes a vector field under metric.

func (*Collection) CreateVectorIndexOnDisk

func (coll *Collection) CreateVectorIndexOnDisk(field string, metric Metric) error

CreateVectorIndexOnDisk is CreateVectorIndex with an on-disk index.

func (*Collection) CreateVectorIndexOnDiskPQ

func (coll *Collection) CreateVectorIndexOnDiskPQ(field string, metric Metric, subspaces, centroids int) error

CreateVectorIndexOnDiskPQ is CreateVectorIndexPQ with an on-disk index.

func (*Collection) CreateVectorIndexOnDiskQuantized

func (coll *Collection) CreateVectorIndexOnDiskQuantized(field string, metric Metric, quant Quant) error

CreateVectorIndexOnDiskQuantized combines on-disk and quantization.

func (*Collection) CreateVectorIndexPQ

func (coll *Collection) CreateVectorIndexPQ(field string, metric Metric, subspaces, centroids int) error

CreateVectorIndexPQ trains a product-quantization index (subspaces × centroids codebooks).

func (*Collection) CreateVectorIndexQuantized

func (coll *Collection) CreateVectorIndexQuantized(field string, metric Metric, quant Quant) error

CreateVectorIndexQuantized indexes a vector field with storage quantization.

func (*Collection) Delete

func (coll *Collection) Delete(key []byte) (existed bool, err error)

Delete removes key, reporting whether it existed.

func (*Collection) DeleteBatch

func (coll *Collection) DeleteBatch(keys ...[]byte) (removed int, err error)

DeleteBatch removes the given keys in one call, returning how many existed.

func (*Collection) DeleteWhere

func (coll *Collection) DeleteWhere(pred *Predicate) (removed int, err error)

DeleteWhere removes every document matching pred (which the call consumes, even on failure) and returns how many went.

func (*Collection) GeoNearest

func (coll *Collection) GeoNearest(field string, lat, lon float64, k int) ([]GeoHit, error)

GeoNearest returns the k documents nearest to (lat, lon).

func (*Collection) GeoWithinBBox

func (coll *Collection) GeoWithinBBox(field string, minLat, minLon, maxLat, maxLon float64) ([]GeoHit, error)

GeoWithinBBox returns the documents inside the axis-aligned box (inclusive bounds). Inverted boxes fail with ErrArgument.

func (*Collection) GeoWithinRadius

func (coll *Collection) GeoWithinRadius(field string, lat, lon, radiusKm float64) ([]GeoHit, error)

GeoWithinRadius returns the documents within radiusKm of (lat, lon), nearest first, ties by key, boundary inclusive.

func (*Collection) Get

func (coll *Collection) Get(key []byte) (doc any, err error)

Get returns the document at key (nil, nil when absent), decoded per the values.go mapping. Map keys enumerate through the engine's corvid_value_map_keys (v0.3.0): every document this engine can read decodes COMPLETE — on any database, whatever wrote it.

func (*Collection) GetFields

func (coll *Collection) GetFields(key []byte, fields ...string) (map[string]any, error)

GetFields returns the named fields (dot paths; all-digit segments index arrays) of the document at key, as a map holding exactly the fields that are present.

func (*Collection) GetTTL

func (coll *Collection) GetTTL(key []byte) (expiresAt int64, has bool, err error)

GetTTL reports a key's expiry instant, if any.

func (*Collection) InNeighbors

func (coll *Collection) InNeighbors(to []byte, relation string) ([][]byte, error)

InNeighbors lists the incoming sources of to under relation.

func (*Collection) Insert

func (coll *Collection) Insert(key []byte, doc any) error

Insert stores doc under key, replacing any previous document.

func (*Collection) InsertAuto

func (coll *Collection) InsertAuto(doc any) ([]byte, error)

InsertAuto stores doc under a fresh engine-generated key (20-digit, zero-padded, strictly monotonic per collection) and returns it.

func (*Collection) InsertTTL

func (coll *Collection) InsertTTL(key []byte, doc any, expiresAt int64) error

InsertTTL stores doc under key with an expiry instant (Unix seconds). A plain Insert over the key later clears the expiry.

func (*Collection) Len

func (coll *Collection) Len() (int, error)

Len returns the number of live documents.

func (coll *Collection) Link(from []byte, relation string, to []byte) error

Link adds a directed edge from→to under relation.

func (*Collection) LinkWeighted

func (coll *Collection) LinkWeighted(from []byte, relation string, to []byte, weight float64) error

LinkWeighted adds a directed weighted edge.

func (*Collection) Name

func (coll *Collection) Name() string

Name returns the collection's name (the handle's own record).

func (*Collection) Neighbors

func (coll *Collection) Neighbors(from []byte, relation string) ([][]byte, error)

Neighbors lists the outgoing targets of from under relation, in engine (key) order.

func (*Collection) NeighborsWeighted

func (coll *Collection) NeighborsWeighted(from []byte, relation string) ([]Weighted, error)

NeighborsWeighted lists the outgoing weighted edges of from.

func (*Collection) Page

func (coll *Collection) Page(after []byte, limit int) (rows []Row, next []byte, err error)

Page returns up to limit rows ordered by key, starting after the after cursor (nil to start at the beginning), plus the next cursor (nil means the end was reached). Pass the returned cursor back as after to resume.

func (*Collection) Patch

func (coll *Collection) Patch(key []byte, patch any) error

Patch merges patch (a map) into the document at key, creating it when absent.

func (*Collection) PhraseSearch

func (coll *Collection) PhraseSearch(field, phrase string, k int) ([]Row, error)

PhraseSearch is the DIRECT positional text search (engine v0.3.0's §4.6 addition; no query handle): documents whose field TEXT contains phrase as a consecutive, IN-ORDER run of analyzed tokens, most relevant first, ties by key, up to k rows. The engine's analysis applies to the phrase too, and stop words collapse out of adjacency ("embedded the database" matches "embedded database"). k == 0 answers an empty slice — inert, never an error. Each Row carries the hit's document and its BM25 phrase score (Row.Score — the phrase scale, NOT the builder's fused RRF scale; the two rows producers keep their own scales).

func (*Collection) PurgeExpired

func (coll *Collection) PurgeExpired(now int64) (int, error)

PurgeExpired removes every key whose expiry instant is ≤ now (inclusive boundary) and returns how many went.

func (*Collection) PutMany

func (coll *Collection) PutMany(keys [][]byte, docs []any) error

PutMany stores key/doc pairs in ONE transaction: either all pairs land or the batch rolls back (a schema violation anywhere fails the whole call with nothing stored).

func (*Collection) Query

func (coll *Collection) Query() *Query

Query starts a query over this collection.

func (*Collection) Scan

func (coll *Collection) Scan(fn func(key []byte, doc any) bool) error

Scan streams every key/document pair in key order. fn returning false stops the scan early (not an error).

func (*Collection) Schema

func (coll *Collection) Schema() ([]FieldDef, error)

Schema returns the declared schema (nil when none is declared).

func (*Collection) SetSchema

func (coll *Collection) SetSchema(defs ...FieldDef) error

SetSchema declares (or replaces) the collection's schema.

func (*Collection) SetTTL

func (coll *Collection) SetTTL(key []byte, expiresAt int64) error

SetTTL sets (or moves) the expiry instant of an existing key.

func (*Collection) Traverse

func (coll *Collection) Traverse(start []byte, relation string, hops int) ([][]byte, error)

Traverse walks the relation graph breadth-first up to hops levels, de-duplicated, cycle-safe.

func (coll *Collection) Unlink(from []byte, relation string, to []byte) (removed bool, err error)

Unlink removes one edge, reporting whether it existed. Deleting a key always cascades its edges.

func (*Collection) Update

func (coll *Collection) Update(key []byte, fn func(current any) (any, error)) error

Update runs a read-modify-write on key under the engine's consistency: fn receives the current document (nil when absent, decoded per the values.go mapping) and returns the replacement, or nil to delete the key. Returning an error aborts with ErrArgument and writes nothing. The callback must not call back into the engine (FFI.md §1.6).

type CorvidError

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

CorvidError is the error type returned by every failing corvid call. It carries the ABI's detailed error code and the message the engine recorded for the failure. Use Code to branch on failure classes:

var ce *corvid.CorvidError
if errors.As(err, &ce) && ce.Code() == corvid.ErrSchemaViolation { ... }

func (*CorvidError) Code

func (e *CorvidError) Code() ErrCode

Code returns the detailed corvid error code (FFI.md §1.3): 1–18 map 1:1 onto the engine's error variants, 19 (ErrBusy) is FFI-only.

func (*CorvidError) Error

func (e *CorvidError) Error() string

Error implements the error interface.

func (*CorvidError) Message

func (e *CorvidError) Message() string

Message returns the failure detail the engine recorded.

type Db

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

Db is an open corvid database (file-backed via Open, in-memory via OpenMemory). It is safe for concurrent use. Call Close when done; the finalizer is only a backstop.

Close caveat (FFI.md §6): close only after every concurrent operation on this Db has completed — freeing the engine handle while another thread is inside a call on it is undefined behavior. The checkOpen gate that rejects calls on a closed Db is TOCTOU by design (a loud use-after-close rejection, not a lock); sequencing Close against in-flight calls is the caller's contract.

func Open

func Open(path string) (*Db, error)

Open opens (or creates) a file-backed database at path.

func OpenMemory

func OpenMemory() (*Db, error)

OpenMemory opens a private in-memory database.

func (*Db) Backup

func (db *Db) Backup(path string) error

Backup copies the database file to path (which must not already exist — ErrBackupTargetExists otherwise). Safe while writers are active.

func (*Db) Close

func (db *Db) Close() error

Close closes the database (idempotent). Derived Collection handles keep the engine alive through their own reference (FFI.md §2); close them too. The runtime finalizer calls Close as a backstop if a Db is leaked — treat explicit Close as the only supported path.

func (*Db) Collection

func (db *Db) Collection(name string) (*Collection, error)

Collection acquires a handle to the named collection (created on first write). Reserved and invalid names surface at write time, not here — exactly like the ABI (FFI.md §4.2). The returned Collection is safe for concurrent use; Close it when finished.

func (*Db) Collections

func (db *Db) Collections() ([]string, error)

Collections lists the database's collection names in engine order.

func (*Db) Compact

func (db *Db) Compact() (movedOut bool, err error)

Compact reclaims dead data; movedOut reports whether anything moved. The engine answers ErrBusy while derived collection handles are live: close them first (FFI.md §4.13).

func (*Db) Dump

func (db *Db) Dump(path string) error

Dump writes a portable dump of the whole database to path.

func (*Db) Load

func (db *Db) Load(path string) error

Load merges a dump file (as written by Dump) into this database.

func (*Db) LoadWithRenames

func (db *Db) LoadWithRenames(path string, renames map[string]string) error

LoadWithRenames merges a dump file into this database, renaming source collections on the fly. A rename to a reserved or invalid name fails with ErrReservedCollection / ErrInvalidName before the stream is read (FFI.md §4.13).

type ErrCode

type ErrCode uint32

ErrCode is a detailed corvid error code (FFI.md §1.3). Codes 1–18 map 1:1 onto the engine's error variants; 19 (ErrBusy) is FFI-only.

const (
	ErrNone               ErrCode = C.CORVID_E_OK
	ErrDatabase           ErrCode = C.CORVID_E_DATABASE
	ErrTransaction        ErrCode = C.CORVID_E_TRANSACTION
	ErrTable              ErrCode = C.CORVID_E_TABLE
	ErrStorage            ErrCode = C.CORVID_E_STORAGE
	ErrCommit             ErrCode = C.CORVID_E_COMMIT
	ErrSetDurability      ErrCode = C.CORVID_E_SET_DURABILITY
	ErrCompaction         ErrCode = C.CORVID_E_COMPACTION
	ErrDecode             ErrCode = C.CORVID_E_DECODE
	ErrCorruptIndex       ErrCode = C.CORVID_E_CORRUPT_INDEX
	ErrReservedCollection ErrCode = C.CORVID_E_RESERVED_COLLECTION
	ErrInvalidName        ErrCode = C.CORVID_E_INVALID_NAME
	ErrArgument           ErrCode = C.CORVID_E_ARGUMENT
	ErrIncompatibleFormat ErrCode = C.CORVID_E_INCOMPATIBLE_FORMAT
	ErrEmptyIndexTraining ErrCode = C.CORVID_E_EMPTY_INDEX_TRAINING
	ErrSchemaViolation    ErrCode = C.CORVID_E_SCHEMA_VIOLATION
	ErrInvalidDump        ErrCode = C.CORVID_E_INVALID_DUMP
	ErrBackupTargetExists ErrCode = C.CORVID_E_BACKUP_TARGET_EXISTS
	ErrIO                 ErrCode = C.CORVID_E_IO
	ErrBusy               ErrCode = C.CORVID_E_BUSY
)

type FieldDef

type FieldDef struct {
	Name     string
	Type     FieldType
	Required bool
	Unique   bool
}

FieldDef declares one schema field.

type FieldExpr

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

FieldExpr is the fluent entry for field predicates.

func Field

func Field(path string) FieldExpr

Field starts a predicate over a document field (dot path).

func (FieldExpr) Between

func (f FieldExpr) Between(lo, hi any) *Predicate

Between matches lo <= field <= hi.

func (FieldExpr) Contains

func (f FieldExpr) Contains(substr string) *Predicate

Contains matches a text field's substring.

func (FieldExpr) Eq

func (f FieldExpr) Eq(v any) *Predicate

Eq matches field == v (the engine's semantic equality).

func (FieldExpr) Exists

func (f FieldExpr) Exists() *Predicate

Exists matches documents that carry the field.

func (FieldExpr) Ge

func (f FieldExpr) Ge(v any) *Predicate

Ge matches field >= v.

func (FieldExpr) GeoWithin

func (f FieldExpr) GeoWithin(lat, lon, radiusKm float64) *Predicate

GeoWithin matches documents whose geo field lies within radiusKm of (lat, lon).

func (FieldExpr) Gt

func (f FieldExpr) Gt(v any) *Predicate

Gt matches field > v.

func (FieldExpr) In

func (f FieldExpr) In(vals ...any) *Predicate

In matches field ∈ vals.

func (FieldExpr) Le

func (f FieldExpr) Le(v any) *Predicate

Le matches field <= v.

func (FieldExpr) Lt

func (f FieldExpr) Lt(v any) *Predicate

Lt matches field < v.

func (FieldExpr) Ne

func (f FieldExpr) Ne(v any) *Predicate

Ne matches field != v.

func (FieldExpr) StartsWith

func (f FieldExpr) StartsWith(prefix string) *Predicate

StartsWith matches a text field's prefix.

type FieldType

type FieldType uint32

FieldType is the declared type of a schema field (FFI.md §1.4).

type GeoHit

type GeoHit struct {
	Key        []byte
	DistanceKm float64
	Doc        any
}

GeoHit is one geo query hit (nil Doc for weighted-neighbor cursors, which carry no document).

type Group

type Group struct {
	Key   string
	Value float64
}

Group is one group-aggregate result, in engine order.

type Metric

type Metric uint32

Metric is the vector distance metric (FFI.md §1.4).

const (
	MetricCosine Metric = C.CORVID_METRIC_COSINE
	MetricDot    Metric = C.CORVID_METRIC_DOT
	MetricL2     Metric = C.CORVID_METRIC_L2
)

type Predicate

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

Predicate is a filter tree node. Build one from a Field expression (Field("n").Eq(5), Field("body").StartsWith("rust"), ...), combine with And/Or/Not. A Predicate is consumed by the Query.Filter, Collection.DeleteWhere, And/Or/Not — exactly once; Close frees a never-consumed root. Single-goroutine use.

func (*Predicate) And

func (p *Predicate) And(q *Predicate) *Predicate

And combines p and q (consuming both).

func (*Predicate) Close

func (p *Predicate) Close()

Close frees a never-consumed predicate (idempotent; the runtime finalizer is a backstop for abandoned builders).

func (*Predicate) Not

func (p *Predicate) Not() *Predicate

Not negates p (consuming it).

func (*Predicate) Or

func (p *Predicate) Or(q *Predicate) *Predicate

Or combines p and q disjunctively (consuming both).

type Quant

type Quant uint32

Quant is the stored-vector quantization mode (FFI.md §1.4).

const (
	QuantNone   Quant = C.CORVID_QUANT_NONE
	QuantBinary Quant = C.CORVID_QUANT_BINARY
	QuantScalar Quant = C.CORVID_QUANT_SCALAR
)

type Query

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

Query is a single-shot query builder over one Collection. Chain the shaping methods, then call exactly one terminal (Run or an aggregation) — the terminal consumes the query. Single-goroutine use (FFI.md §6); builders are cheap.

func (*Query) Approx

func (q *Query) Approx() *Query

Approx relaxes vector execution to approximate scanning (same answers for small corpora).

func (*Query) Avg

func (q *Query) Avg(field string) (avg float64, ok bool, err error)

Avg returns the mean of field's numeric values, or ok=false when no document carries a numeric value there (terminal).

func (*Query) Close

func (q *Query) Close()

Close frees an abandoned builder without running it (idempotent; finalizer backstop).

func (*Query) Count

func (q *Query) Count() (int, error)

Count returns the number of matching documents (terminal).

func (*Query) CountDistinct

func (q *Query) CountDistinct(field string) (int, error)

CountDistinct returns the number of distinct values of field (terminal).

func (*Query) Filter

func (q *Query) Filter(pred *Predicate) *Query

Filter constrains the query with pred (consuming it).

func (*Query) FuseRRF

func (q *Query) FuseRRF(k float32) *Query

FuseRRF fuses multiple sources with reciprocal-rank fusion (k is the RRF constant, e.g. 60).

func (*Query) GroupAvg

func (q *Query) GroupAvg(groupField, valueField string) ([]Group, error)

GroupAvg averages valueField per distinct value of groupField (terminal).

func (*Query) GroupCount

func (q *Query) GroupCount(field string) ([]Group, error)

GroupCount counts per distinct value of field (terminal).

func (*Query) GroupSum

func (q *Query) GroupSum(groupField, valueField string) ([]Group, error)

GroupSum sums valueField per distinct value of groupField (terminal).

func (*Query) Limit

func (q *Query) Limit(n int) *Query

Limit caps the number of rows.

func (*Query) Max

func (q *Query) Max(field string) (any, error)

Max returns field's maximum value (nil, nil when absent) (terminal).

func (*Query) Min

func (q *Query) Min(field string) (any, error)

Min returns field's minimum value (nil, nil when absent) (terminal).

func (*Query) Offset

func (q *Query) Offset(n int) *Query

Offset skips the first n rows.

func (*Query) OrderBy

func (q *Query) OrderBy(field string, descending bool) *Query

OrderBy sorts by field: numbers first in value order, rows missing the field last, ties by key; descending reverses within class only.

func (*Query) RerankMMR

func (q *Query) RerankMMR(lambda float32) *Query

RerankMMR reranks fused sources with maximal-marginal-relevance (lambda trades relevance against diversity).

func (*Query) Run

func (q *Query) Run() ([]Row, error)

Run executes the query and returns its rows (consuming the query). Row.Doc is non-nil only under Select — see the file comment.

func (*Query) Select

func (q *Query) Select(fields ...string) *Query

Select projects rows to the named top-level fields — the only shape in which Run materializes documents (Row.Doc decodes from exactly these fields).

func (*Query) Sum

func (q *Query) Sum(field string) (float64, error)

Sum returns the sum of field's numeric values (terminal).

func (*Query) Text

func (q *Query) Text(field, text string, k int) *Query

Text adds a BM25 text source over field (top-k).

func (*Query) Vector

func (q *Query) Vector(field string, query []float32, k int, metric Metric) *Query

Vector adds an ANN vector source over field (top-k, metric).

type Row

type Row struct {
	Key   []byte
	Doc   any
	Score float32
}

Row is one query result: the key, the projected document (nil unless Select was called), and the relevance score (0 for non-scoring queries).

type Weighted

type Weighted struct {
	Key    []byte
	Weight float64
}

Weighted is one weighted graph edge.

Directories

Path Synopsis
examples
geo command
geo — points, radius, bbox, nearest-k with real coordinates.
geo — points, radius, bbox, nearest-k with real coordinates.
graph command
graph — directed edges over a small corpus, and delete cascade.
graph — directed edges over a small corpus, and delete cascade.
hybrid command
hybrid — the flagship: filter + vector + BM25, RRF fusion, MMR rerank, limit.
hybrid — the flagship: filter + vector + BM25, RRF fusion, MMR rerank, limit.
quickstart command
quickstart — the README tour as a runnable file.
quickstart — the README tour as a runnable file.
text-search command
text-search — BM25 ranking, English and CJK.
text-search — BM25 ranking, English and CJK.
vector-index command
vector-index — three vector-index families, ANN vs exact.
vector-index — three vector-index families, ANN vs exact.

Jump to

Keyboard shortcuts

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