hnsw

package
v1.30.0 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package hnsw implements an in-memory Hierarchical Navigable Small World graph (Malkov & Yashunin) for approximate nearest neighbor search over float32 vectors. Scores use the same arithmetic as vec.Score, so a document found approximately carries exactly the score exact search would give it.

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 New

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

New creates an empty graph for metric.

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) Len

func (g *Graph) Len() int

Len returns the number of vectors.

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; selective filters may traverse an entire connected rejected region.

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
}

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

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.

Jump to

Keyboard shortcuts

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