hnsw

package
v1.80.1 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 16 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 hnsw implements a Hierarchical Navigable Small World graph (Malkov & Yashunin) for approximate nearest neighbor search over float32 vectors. By default graphs are built and traversed with int8 codes (QuantizationInt8), and search rescores its candidates with the float32 vectors using the same arithmetic as vec.Score, so a document found approximately carries exactly the score exact search would give it. Graphs live on the heap, or are used in place from memory such as a mapped file with WriteMappedTo and Map.

Index

Constants

View Source
const (
	DefaultM              = 16
	DefaultEfConstruction = 200
	DefaultEfSearch       = 100
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Graph

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

Graph holds vectors and their navigable layers. Add is not safe for concurrent use; once building is done, Search is safe for concurrent use.

func Build added in v1.50.0

func Build(ctx context.Context, metric vec.Metric, params Params, ids []uint64, data []float32,
	workers int) (*Graph, error)

Build returns a graph of the vectors in data, node-major, for document ids in order, inserted by up to workers goroutines. Node levels are drawn in order, as by Add. With one worker the graph equals Adding the vectors in order; with more, nodes are inserted in a fixed shuffled order and links depend on scheduling, so graphs differ between runs with the same quality. The graph keeps ids and data. Cancellation of ctx stops the build with its error.

func BuildFrom added in v1.50.0

func BuildFrom(ctx context.Context, base *Graph, mapping []uint32, ids []uint64, data []float32,
	workers int) (*Graph, error)

BuildFrom is Build reusing base, a graph of a subset of the vectors, as Lucene does when merging segments: mapping[i] is the node in ids and data of base's node i, whose vector must be equal. Base's links are copied and only the other nodes are inserted, so the cost is that of the inserts. The graph takes base's metric and parameters; base is not modified.

func Map added in v1.50.0

func Map(b []byte) (*Graph, error)

Map returns the graph written by WriteMappedTo in b, which must hold exactly its bytes. Ids, vectors and codes are used in place when b is suitably aligned on a little-endian machine, so b must stay valid and unmodified while the graph is used; only links are decoded. The checksum is verified first, then the structure, so corrupt input returns an error. Add copies the arrays before growing them.

func New

func New(metric vec.Metric, params Params) (*Graph, error)

New creates an empty graph for metric.

func Read added in v1.33.0

func Read(r io.Reader) (*Graph, error)

Read restores a graph written by WriteTo, consuming exactly its bytes. Input is checksummed and structurally validated, so a corrupt or foreign stream returns an error rather than a graph that could panic in Search.

func ReadLinks(r io.Reader, ids []uint64, data []float32) (*Graph, error)

ReadLinks restores a graph written by WriteLinksTo, consuming exactly its bytes. ids and data, node-major with the graph's dimension, must be those of the written graph; a mismatch is an error. The graph keeps data.

func (*Graph) Add

func (g *Graph) Add(id uint64, vector []float32) error

Add inserts vector for document id. Every vector must share one dimension; the same id may be added more than once.

func (*Graph) IDs added in v1.50.0

func (g *Graph) IDs() []uint64

IDs returns the document id of each node, in node order. It must not be modified.

func (*Graph) Len

func (g *Graph) Len() int

Len returns the number of vectors.

func (*Graph) Metric added in v1.33.0

func (g *Graph) Metric() vec.Metric

Metric returns the graph's similarity metric.

func (*Graph) Params added in v1.33.0

func (g *Graph) Params() Params

Params returns the graph's parameters with defaults applied.

func (*Graph) Search

func (g *Graph) Search(query []float32, k, ef int, accept func(uint64) bool) ([]vec.Match, error)

Search returns up to k documents, best first with ties by ascending id; repeated ids keep their best score. ef bounds the candidate list (0 uses the graph's EfSearch; k raises it). accept optionally filters results with the traversal semantics documented by SearchContext.

func (*Graph) SearchContext

func (g *Graph) SearchContext(ctx context.Context, query []float32, k, ef int,
	accept func(uint64) bool) ([]vec.Match, error)

SearchContext is Search with cancellation during descent and layer expansion. Discovered rejected nodes are always expanded as bridges, even with a full accepted beam. Accepted nodes remain score-pruned, so search is approximate. Once a filtered search has visited more nodes than an exact scan would cost, estimated from the accepted share of the visited nodes, it scores every accepted node exactly instead, as Lucene and Weaviate do for selective filters and heavily deleted segments; results are then exact.

func (*Graph) WriteLinksTo added in v1.40.0

func (g *Graph) WriteLinksTo(w io.Writer) (int64, error)

WriteLinksTo serializes the graph without its ids and vectors; ReadLinks restores it given the same ids and vectors. It may run concurrently with Search but not with Add.

func (*Graph) WriteMappedTo added in v1.50.0

func (g *Graph) WriteMappedTo(w io.Writer) (int64, error)

WriteMappedTo serializes the graph with its vectors for Map. It may run concurrently with Search but not with Add.

func (*Graph) WriteTo added in v1.33.0

func (g *Graph) WriteTo(w io.Writer) (int64, error)

WriteTo serializes the graph to w; Read restores it. Graphs built by the same Adds before and after a WriteTo/Read round trip are identical. WriteTo may run concurrently with Search but not with Add.

type Params

type Params struct {
	// M is the maximum number of neighbors per node above level 0; level 0
	// keeps 2*M. Larger values raise recall and memory. Minimum 2.
	M int
	// EfConstruction is the candidate list size while inserting.
	EfConstruction int
	// EfSearch is the candidate list size while searching; k raises it when larger.
	EfSearch int
	// Quantization selects the vectors compared while building and
	// traversing; the zero value is QuantizationInt8.
	Quantization Quantization
	// ConcurrentAccept declares a search filter safe for concurrent use, so
	// an index searching segments in parallel calls it without a shared
	// lock. Graph itself ignores it; it is not persisted.
	ConcurrentAccept bool
}

Params tunes graph construction and search. Zero fields take the defaults.

func ReadParams added in v1.50.0

func ReadParams(r io.Reader) (vec.Metric, Params, error)

ReadParams reads the metric and parameters at the start of a graph written by WriteTo, WriteLinksTo or WriteMappedTo, without reading or checking the rest.

func (Params) Validate

func (p Params) Validate() error

Validate rejects negative values, M below 2, and overflow of the 2*M level-0 limit.

func (Params) WithDefaults

func (p Params) WithDefaults() Params

WithDefaults fills zero fields.

type Quantization added in v1.50.0

type Quantization uint8

Quantization selects the vectors a graph compares while it is built and traversed. Search always rescores its candidates with the float32 vectors, so returned scores stay exact either way.

const (
	// QuantizationInt8, the default, compares one signed byte per value,
	// scaled per vector by its largest magnitude, as Lucene's int8 HNSW does.
	// Codes take a quarter of the float32 size and need no training, so
	// graphs keep growing with Add.
	QuantizationInt8 Quantization = iota
	// QuantizationNone compares the float32 vectors.
	QuantizationNone
)

func (Quantization) String added in v1.50.0

func (q Quantization) String() string

Jump to

Keyboard shortcuts

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