store

package
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 11 Imported by: ? modules, 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 store holds the three ways a graph is kept: by similarity, by edge, and by assertion. They are separate interfaces because they answer separate questions, and a deployment may back them with one engine or three.

Index

Constants

View Source
const Space = "space"

Space is the metadata key a namespace is written under. A namespace is a filter, not a second kind of store: tag a vector with it on the way in and ask for it on the way out.

m.Put(ctx, "a", v, map[string]any{store.Space: "docs"})
m.Search(ctx, store.Query{Vec: q, K: 5, Filter: store.Filter{}.Eq(store.Space, "docs")})

Variables

View Source
var (
	Vectors = &Drivers[Vector]{}
	Graphs  = &Drivers[Graph]{}
	Triples = &Drivers[Triple]{}
)

Vectors, Graphs and Triples hold the drivers of each kind. A store that answers more than one question registers under each of them.

View Source
var (
	// ErrID means an identifier was blank.
	ErrID = errors.New("store: empty id")
	// ErrTerm means a triple was missing a subject, predicate or object.
	ErrTerm = errors.New("store: empty term")
	// ErrDim means a vector's length differs from the store's.
	ErrDim = errors.New("store: vector dimension")
	// ErrDriver means a driver is named but this build cannot serve it.
	ErrDriver = errors.New("store: driver unavailable")
)

What a store refuses to do. Test for these with errors.Is.

Functions

func Cos added in v0.2.0

func Cos(a, b []float32) float64

Cos is the cosine of the angle between two vectors. A zero vector points nowhere, so it scores 0 against everything rather than dividing by zero.

func Dist added in v0.2.0

func Dist(a, b []float32) float64

Dist is the Euclidean distance between two vectors.

func Dot added in v0.2.0

func Dot(a, b []float32) float64

Dot is the inner product of two vectors.

func Norm added in v0.2.0

func Norm(v []float32) float64

Norm is the Euclidean length of a vector.

func Unit added in v0.2.0

func Unit(v []float32) []float32

Unit returns v scaled to length 1, as a new slice. A zero vector has no direction, so it is returned unchanged rather than turned into NaNs.

Types

type Cond added in v0.2.0

type Cond struct {
	Field string
	Op    Op
	Value any
}

Cond is one comparison against one metadata field.

type Drivers added in v0.2.0

type Drivers[T any] struct {
	// contains filtered or unexported fields
}

Drivers names the implementations of one kind of store, so a program can be told at run time which one to use. A driver in another package adds itself in an init, and a caller reaches it by importing that package for its effect:

import _ "github.com/hanzoai/semantic/store/qdrant"

v, err := store.Vectors.Open("qdrant", "http://localhost:6333/docs")

The zero value is an empty set of drivers, ready to use.

func (*Drivers[T]) Add added in v0.2.0

func (d *Drivers[T]) Add(name string, open func(dsn string) (T, error))

Add registers a driver under a name, replacing whatever was there. A nil open registers the name alone: Open then reports ErrDriver, so a caller can tell a store this build cannot serve from one nobody has heard of.

func (*Drivers[T]) Has added in v0.2.0

func (d *Drivers[T]) Has(name string) bool

Has reports whether a name is registered, whether or not it can be opened.

func (*Drivers[T]) Names added in v0.2.0

func (d *Drivers[T]) Names() []string

Names lists every registered driver, in order.

func (*Drivers[T]) Open added in v0.2.0

func (d *Drivers[T]) Open(name, dsn string) (T, error)

Open builds the store a driver names from a data source name, whose shape the driver decides: a path, a URL, or nothing at all.

type File added in v0.2.0

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

File keeps a store in one file on disk. It answers every question Mem does, from memory, and owes its durability to a log: each write is appended as one JSON record and flushed before the call returns, so reopening the file replays exactly what was acknowledged.

A process that dies mid-write leaves a partial last line. A record counts only if it is terminated and decodes, so the partial line is discarded on the next open and the file is truncated back to the last whole record — the write that never returned never happened.

The log grows with every write. Compact folds it into a single snapshot record, written beside the file and renamed over it, so a crash during compaction leaves the old log intact.

func Open added in v0.2.0

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

Open opens the store at path, creating it if it is not there, and replays what was written.

func (*File) Assert added in v0.2.0

func (s *File) Assert(ctx context.Context, sub, pred, obj string) error

Assert records one triple. See Mem.Assert.

func (*File) Close added in v0.2.0

func (s *File) Close() error

Close flushes and closes the file.

func (*File) Compact added in v0.2.0

func (s *File) Compact() error

Compact rewrites the file as one snapshot, discarding a log that has grown longer than the state it describes. The snapshot is written beside the file and renamed over it, so an interrupted compaction leaves the store as it was.

func (*File) Components added in v0.2.0

func (s *File) Components() [][]string

Components groups the nodes into connected components. See Mem.Components.

func (*File) Cut added in v0.2.0

func (s *File) Cut(ctx context.Context, id string) error

Cut removes a node and every edge that touched it. See Mem.Cut.

func (*File) Degree added in v0.2.0

func (s *File) Degree(id string) (in, out int)

Degree counts the edges into and out of a node. See Mem.Degree.

func (*File) Drop added in v0.2.0

func (s *File) Drop(ctx context.Context, ids ...string) error

Drop removes vectors. See Mem.Drop.

func (*File) Dump added in v0.2.0

func (s *File) Dump() Snap

Dump returns everything the store holds. See Mem.Dump.

func (*File) Edge added in v0.2.0

func (s *File) Edge(ctx context.Context, from, to, label string) error

Edge links two nodes under a label. See Mem.Edge.

func (*File) Edges added in v0.2.0

func (s *File) Edges(from, to, label string) []Link

Edges lists the links that match a pattern. See Mem.Edges.

func (*File) Get added in v0.2.0

func (s *File) Get(id string) ([]float32, map[string]any, bool)

Get returns a vector and its metadata. See Mem.Get.

func (*File) In added in v0.2.0

func (s *File) In(ctx context.Context, id string) ([]string, error)

In lists the nodes that point at this one. See Mem.In.

func (*File) Match added in v0.2.0

func (s *File) Match(ctx context.Context, sub, pred, obj string) ([][3]string, error)

Match returns the triples that fit a pattern. See Mem.Match.

func (*File) Metric added in v0.2.0

func (s *File) Metric() Metric

Metric reports how nearness is measured. See Mem.Metric.

func (*File) Name added in v0.2.0

func (s *File) Name() string

Name is the path the store is kept at, as os.File reports its own.

func (*File) Near added in v0.2.0

func (s *File) Near(ctx context.Context, v []float32, k int) ([]Match, error)

Near returns the k nearest vectors. See Mem.Near.

func (*File) Node added in v0.2.0

func (s *File) Node(ctx context.Context, id string, props map[string]any) error

Node writes a node and its properties. See Mem.Node.

func (*File) Nodes added in v0.2.0

func (s *File) Nodes() []string

Nodes lists every node. See Mem.Nodes.

func (*File) Out added in v0.2.0

func (s *File) Out(ctx context.Context, id string) ([]string, error)

Out lists the nodes this one points at. See Mem.Out.

func (*File) Path added in v0.2.0

func (s *File) Path(ctx context.Context, from, to string) ([]string, error)

Path returns a shortest path between two nodes. See Mem.Path.

func (*File) Props added in v0.2.0

func (s *File) Props(id string) (map[string]any, bool)

Props returns a node's properties. See Mem.Props.

func (*File) Put added in v0.2.0

func (s *File) Put(ctx context.Context, id string, v []float32, meta map[string]any) error

Put writes a vector under an id. See Mem.Put.

func (*File) Rank added in v0.2.0

func (s *File) Rank(v Metric) error

Rank sets how nearness is measured and records the choice, so a store reopened later ranks the way it was told to.

func (*File) Reach added in v0.2.0

func (s *File) Reach(ctx context.Context, id string, hops int) ([]string, error)

Reach lists the nodes within hops steps of one. See Mem.Reach.

func (*File) Retract added in v0.2.0

func (s *File) Retract(ctx context.Context, sub, pred, obj string) error

Retract removes the triples that match a pattern. See Mem.Retract.

func (*File) Scan added in v0.2.0

func (s *File) Scan(offset, limit int) []Match

Scan pages through the stored vectors. See Mem.Scan.

func (*File) Search added in v0.2.0

func (s *File) Search(ctx context.Context, q Query) ([]Match, error)

Search returns the matches a query admits. See Mem.Search.

func (*File) Stat added in v0.2.0

func (s *File) Stat() Stat

Stat counts what the store holds. See Mem.Stat.

func (s *File) Unlink(ctx context.Context, from, to, label string) error

Unlink removes the edges that match a pattern. See Mem.Unlink.

type Filter added in v0.2.0

type Filter []Cond

Filter is a conjunction: metadata passes when every condition holds. The zero value passes everything, so a query with no filter is not a special case.

Conditions are added by the builder methods, each returning the extended filter, so a filter reads as the question it asks:

f := store.Filter{}.Eq("lang", "en").Ge("year", 2020)

func (Filter) Add added in v0.2.0

func (f Filter) Add(field string, op Op, v any) Filter

Add appends one condition.

func (Filter) Eq added in v0.2.0

func (f Filter) Eq(field string, v any) Filter

Eq requires the field to equal v.

func (Filter) Ge added in v0.2.0

func (f Filter) Ge(field string, v any) Filter

Ge requires the field to be greater than or equal to v.

func (Filter) Gt added in v0.2.0

func (f Filter) Gt(field string, v any) Filter

Gt requires the field to be greater than v.

func (Filter) Has added in v0.2.0

func (f Filter) Has(field string, v any) Filter

Has requires the field to contain v: a substring of a string field, or a member of a list field.

func (Filter) In added in v0.2.0

func (f Filter) In(field string, list ...any) Filter

In requires the field to equal one of the values in list.

func (Filter) Le added in v0.2.0

func (f Filter) Le(field string, v any) Filter

Le requires the field to be less than or equal to v.

func (Filter) Lt added in v0.2.0

func (f Filter) Lt(field string, v any) Filter

Lt requires the field to be less than v.

func (Filter) Match added in v0.2.0

func (f Filter) Match(meta map[string]any) bool

Match reports whether metadata satisfies every condition. A field the metadata does not carry fails, whatever the operator — an absent field is not evidence of inequality — so Ne is "present and different", not "not equal or missing".

func (Filter) Ne added in v0.2.0

func (f Filter) Ne(field string, v any) Filter

Ne requires the field to be present and differ from v.

type Graph

type Graph interface {
	Node(ctx context.Context, id string, props map[string]any) error
	Edge(ctx context.Context, from, to, label string) error
	Out(ctx context.Context, id string) ([]string, error)
}

Graph answers "what is connected to this".

type Item added in v0.2.0

type Item struct {
	ID   string
	Vec  []float32
	Meta map[string]any
}

Item is an identifier and what is known about it: a vector and its metadata, or — with no vector — a graph node and its properties.

type Link struct {
	From  string
	To    string
	Label string
}

Link is one edge: which node points at which, under what label.

type Match

type Match struct {
	ID    string
	Score float64
	Meta  map[string]any
}

Match is a neighbour and how near it is.

func Blend added in v0.2.0

func Blend(w []float64, lists ...[]Match) []Match

Blend merges ranked lists by weighted sum of the scores they already carry, which is the right combination when the sources score on one scale. A weight missing for a list counts as an equal share, 1/n.

func Fuse added in v0.2.0

func Fuse(k int, lists ...[]Match) []Match

Fuse merges ranked lists by reciprocal rank: an item scores the sum, over the lists it appears in, of 1/(k+rank), counting rank from 1. It needs no scores, only orders, which is what makes it the way to combine answers from sources that score on different scales — a vector store and a text index, say.

k damps how much the head of any one list decides the outcome; 60 is the constant from the original description and is used when k is not positive. Metadata comes from the first list an item appeared in.

type Mem added in v0.2.0

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

Mem keeps a store in memory and implements all three of Vector, Graph and Triple, so a caller that wants one of them and a caller that wants all three use the same object. It is the default every other driver is measured against, and the store a program uses when it has no database.

The zero value is an empty store, ready to use, ranking by cosine. Every method is safe for concurrent use.

func (*Mem) Assert added in v0.2.0

func (m *Mem) Assert(ctx context.Context, s, p, o string) error

Assert records one triple. The same triple asserted twice is one fact.

func (*Mem) Components added in v0.2.0

func (m *Mem) Components() [][]string

Components groups the nodes into connected components, ignoring edge direction. Each group is sorted, and the groups are ordered by their first node, so the answer is the same on every run.

func (*Mem) Cut added in v0.2.0

func (m *Mem) Cut(ctx context.Context, id string) error

Cut removes a node and every edge that touched it, because an edge to a node that is gone is not a fact about anything.

func (*Mem) Degree added in v0.2.0

func (m *Mem) Degree(id string) (in, out int)

Degree counts the edges into and out of a node, the simplest measure of how central it is.

func (*Mem) Drop added in v0.2.0

func (m *Mem) Drop(ctx context.Context, ids ...string) error

Drop removes vectors. Ids the store does not hold are ignored.

func (*Mem) Dump added in v0.2.0

func (m *Mem) Dump() Snap

Dump returns everything the store holds, in the order it was written.

func (*Mem) Edge added in v0.2.0

func (m *Mem) Edge(ctx context.Context, from, to, label string) error

Edge links two nodes under a label, creating either endpoint if it is new. The same link asserted twice is one edge.

func (*Mem) Edges added in v0.2.0

func (m *Mem) Edges(from, to, label string) []Link

Edges lists the links that match a pattern, first written first. An empty from, to or label matches any.

func (*Mem) Get added in v0.2.0

func (m *Mem) Get(id string) ([]float32, map[string]any, bool)

Get returns a vector and its metadata, and whether the store holds the id.

func (*Mem) In added in v0.2.0

func (m *Mem) In(ctx context.Context, id string) ([]string, error)

In lists the nodes that point at this one, first linked first.

func (*Mem) Load added in v0.2.0

func (m *Mem) Load(ctx context.Context, s Snap) error

Load replaces everything the store holds with a snapshot. It is the other half of Dump: what one writes, the other reads back.

func (*Mem) Match added in v0.2.0

func (m *Mem) Match(ctx context.Context, s, p, o string) ([][3]string, error)

Match returns the triples that fit a pattern, first asserted first. An empty subject, predicate or object matches any, so Match(ctx, "", "", "") returns everything.

func (*Mem) Metric added in v0.2.0

func (m *Mem) Metric() Metric

Metric reports how nearness is measured.

func (*Mem) Near added in v0.2.0

func (m *Mem) Near(ctx context.Context, v []float32, k int) ([]Match, error)

Near returns the k nearest vectors to v, nearest first. A k of zero or less returns every vector the store holds, ranked.

func (*Mem) Node added in v0.2.0

func (m *Mem) Node(ctx context.Context, id string, props map[string]any) error

Node writes a node and its properties, creating it if the store has not heard of it. Properties given replace those of the same name; the rest are left alone, so a caller may set one field without reading the others.

func (*Mem) Nodes added in v0.2.0

func (m *Mem) Nodes() []string

Nodes lists every node in the order it was first written.

func (*Mem) Out added in v0.2.0

func (m *Mem) Out(ctx context.Context, id string) ([]string, error)

Out lists the nodes this one points at, first linked first.

func (*Mem) Path added in v0.2.0

func (m *Mem) Path(ctx context.Context, from, to string) ([]string, error)

Path returns a shortest path from one node to another, both ends included, following edges in their own direction. It is nil when there is no path; a node to itself is a path of one.

func (*Mem) Props added in v0.2.0

func (m *Mem) Props(id string) (map[string]any, bool)

Props returns a node's properties and whether the store holds it.

func (*Mem) Put added in v0.2.0

func (m *Mem) Put(ctx context.Context, id string, v []float32, meta map[string]any) error

Put writes a vector under an id, replacing whatever was there. The first vector fixes the store's dimension; a later one of a different length is refused with ErrDim, because a store whose vectors do not share a space cannot rank them. A vector of no components names no point and is refused for the same reason.

func (*Mem) Rank added in v0.2.0

func (m *Mem) Rank(v Metric)

Rank sets how nearness is measured. The zero value of a store ranks by cosine.

func (*Mem) Reach added in v0.2.0

func (m *Mem) Reach(ctx context.Context, id string, hops int) ([]string, error)

Reach lists the nodes within hops steps of one, in either direction and excluding the node itself, nearest first. Zero hops reaches nothing.

func (*Mem) Retract added in v0.2.0

func (m *Mem) Retract(ctx context.Context, s, p, o string) error

Retract removes the triples that fit a pattern, on the same wildcards as Match.

func (*Mem) Scan added in v0.2.0

func (m *Mem) Scan(offset, limit int) []Match

Scan pages through the stored vectors in the order they were written, which is how a caller walks a whole store without ranking it. Scores are zero: nothing was asked for, so nothing is near.

func (*Mem) Search added in v0.2.0

func (m *Mem) Search(ctx context.Context, q Query) ([]Match, error)

Search returns the matches a query admits, nearest first when it asks for nearness and in insertion order when it does not.

func (*Mem) Stat added in v0.2.0

func (m *Mem) Stat() Stat

Stat counts what the store holds.

func (m *Mem) Unlink(ctx context.Context, from, to, label string) error

Unlink removes the edges that match a pattern. An empty from, to or label matches any, so Unlink(ctx, "a", "", "") cuts everything leaving a.

type Metric added in v0.2.0

type Metric string

Metric names how nearness is measured. The zero value is Cosine, so a store that states no metric compares directions.

const (
	// Cosine is the angle between two vectors: 1 when they point the same
	// way, 0 when they are orthogonal, -1 when opposed. Length is ignored.
	Cosine Metric = "cosine"
	// Inner is the dot product, so length counts as well as direction.
	Inner Metric = "inner"
	// Euclid is straight-line distance, negated so that larger still means
	// nearer and one comparison orders every metric.
	Euclid Metric = "euclid"
)

func (Metric) Score added in v0.2.0

func (m Metric) Score(a, b []float32) float64

Score reports how near b is to a. Larger is nearer under every metric, so callers rank the same way whichever one is in use. An unknown metric scores as Cosine.

type Op added in v0.2.0

type Op string

Op is how a condition compares a metadata field to a value.

const (
	Eq  Op = "eq"  // field equals value
	Ne  Op = "ne"  // field differs from value
	Gt  Op = "gt"  // field is greater than value
	Ge  Op = "ge"  // field is greater than or equal to value
	Lt  Op = "lt"  // field is less than value
	Le  Op = "le"  // field is less than or equal to value
	In  Op = "in"  // field is one of the values in a list
	Has Op = "has" // field contains value: a substring, or a member of a list
)

type Query added in v0.2.0

type Query struct {
	Vec    []float32
	K      int
	Filter Filter
	// Metric overrides the store's own. Empty uses the store's.
	Metric Metric
}

Query asks for the nearest vectors that also match a filter.

A nil Vec ranks nothing and returns whatever the filter admits, in the order it was written, which is how a metadata-only lookup is asked for. A K of zero or less asks for every match rather than none, so a filter stands on its own.

type Snap added in v0.2.0

type Snap struct {
	Metric Metric
	Items  []Item
	Nodes  []Item
	Links  []Link
	Facts  [][3]string
}

Snap is everything a store holds. A durable store writes one to make a snapshot and reads one back to restore.

type Stat added in v0.2.0

type Stat struct {
	Vectors int
	Nodes   int
	Edges   int
	Facts   int
}

Stat counts what a store holds.

type Triple

type Triple interface {
	Assert(ctx context.Context, s, p, o string) error
	Match(ctx context.Context, s, p, o string) ([][3]string, error)
}

Triple answers "what was asserted".

type Vector

type Vector interface {
	Put(ctx context.Context, id string, v []float32, meta map[string]any) error
	Near(ctx context.Context, v []float32, k int) ([]Match, error)
}

Vector answers "what is like this".

Directories

Path Synopsis
Package qdrant keeps vectors in Qdrant, over its JSON HTTP API.
Package qdrant keeps vectors in Qdrant, over its JSON HTTP API.
Package sparql keeps a graph on a SPARQL 1.1 endpoint over HTTP.
Package sparql keeps a graph on a SPARQL 1.1 endpoint over HTTP.

Jump to

Keyboard shortcuts

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