search

package
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 77 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

Author: Codex implementation lane, 2026-10-27 (NOR-148).

Author: Codex implementation lane, 2026-10-26 (NOR-148). Author of change relevance: #1683 lane (Claude), 2026-10-30 (NOR-148). Author of change relevance: #1683 review-correction lane (DeepSeek), 2026-11-02 (NOR-148).

Package search provides full-text indexing with BM25 scoring.

Checkpoint admission validation: Codex NOR-283 implementation lane, 29 October 2026.

Author: #1683 implementation lane (Codex), 2026-11-01.

Package search - HNSW configuration and quality presets.

Package search provides HNSW vector indexing for fast approximate nearest neighbor search.

HNSW Delete/Update Policy:

Delete:

  • Remove() tombstones a vector via a dense `deleted []bool` flag
  • Neighbor lists are not eagerly rewired (tombstones keep deletes cheap)
  • Entry point is re-selected if the removed node was the entry point

Update:

  • Current policy: Remove() + Add() pattern
  • Call Remove(id) then Add(id, newVector) to update a vector
  • This ensures the graph structure is correctly maintained
  • Future: A dedicated Update() method may be added for efficiency

Graph Quality:

  • High-churn workloads (many updates/deletes) can degrade graph quality
  • Periodic rebuilds are recommended (see NORNICDB_VECTOR_ANN_REBUILD_INTERVAL)
  • Rebuilds restore optimal graph structure and improve recall

Package search - Kalman filter integration for stable search ranking.

This file provides the KalmanAdapter that enhances the search service with:

  • Similarity score smoothing: Reduce noise in vector similarity scores
  • Ranking stability: Prevent results from jumping around between queries
  • Trend detection: Identify documents becoming more/less relevant
  • Latency prediction: Smooth query latency for better resource planning

Why Smooth Search Scores?

Vector similarity scores can be noisy due to:

  • Embedding model variability (same query, slightly different embeddings)
  • Approximation in ANN (approximate nearest neighbor) indexes
  • Edge cases where documents are equidistant from query

Kalman filtering smooths these variations to provide:

  • More consistent rankings across similar queries
  • Gradual relevance transitions (not sudden jumps)
  • Confidence estimates for borderline results

Integration Architecture

┌─────────────────────────────────────────────────────────────┐
│                  Kalman Search Adapter                       │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────────┐    ┌─────────────────────────────────┐ │
│  │  Search Service │───▶│ Kalman Filter (scores)          │ │
│  │  (raw scores)   │    │ - Per-document filters          │ │
│  └────────┬────────┘    │ - Score history smoothing       │ │
│           │             └─────────────────────────────────┘ │
│           │                                                 │
│           ▼                                                 │
│  ┌─────────────────────────────────────────────────────────┐│
│  │     Ranking Stabilizer                                  ││
│  │  • Detect score ties                                    ││
│  │  • Apply stability boost to consistent docs             ││
│  │  • Prevent rank oscillation                             ││
│  └─────────────────────────────────────────────────────────┘│
│           │                                                 │
│           ▼                                                 │
│  ┌─────────────────────────────────────────────────────────┐│
│  │     Latency Predictor                                   ││
│  │  • Smooth query latency measurements                    ││
│  │  • Predict P99 latency                                  ││
│  │  • Resource scaling suggestions                         ││
│  └─────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────┘

ELI12 (Explain Like I'm 12)

Imagine you're searching Google for "cute cats":

**Without Kalman:**

  • Search 1: Cat A is #1, Cat B is #2
  • Search 2: Cat B is #1, Cat A is #2 (they swapped!)
  • Search 3: Cat C is #1 (where did that come from?!)

**With Kalman:**

  • Kalman remembers: "Cat A has been top 3 for a while"
  • When Cat B briefly gets a tiny score boost, Kalman says: "That's probably noise. Cat A stays #1 until I see a REAL trend."
  • Result: Rankings stay consistent, you find things where you expect them!

It's like having a wise librarian who remembers "this book was popular before" instead of reshuffling the entire library every time someone asks a question.

Package search - K-means cluster routing candidate generator.

This file implements KMeansCandidateGen, which uses k-means clustering to route queries to the most relevant clusters, then generates candidates from those clusters. This is optimal for very large datasets (N > 100K) where cluster routing provides significant speedup over HNSW.

Trigger Policies:

K-means clustering is triggered automatically:

  • After bulk loads: When BuildIndexes() completes, clustering runs automatically
  • Periodic clustering: Background timer runs clustering at regular intervals (configurable via clustering interval)
  • Manual trigger: Call TriggerClustering() after bulk data loading

The candidate generator automatically uses k-means routing when:

  • Clustering is enabled (EnableClustering() called)
  • ClusterIndex is clustered (Cluster() has been run)
  • Dataset is large enough to benefit (typically N > 100K)

For smaller datasets, the pipeline automatically falls back to HNSW or brute-force.

Package search — Plan 04-05-05 observability wiring.

AttachMetrics injects an *observability.SearchMetrics bag into the Service. observeSearch is the single chokepoint helper called from Search() / rrfHybridSearch() at the per-stage boundaries to record requests_total + duration_seconds{stage} + candidates_rows observations.

The chokepoint design preserves AGENTS.md §7 DRY — every search code path (vector-only, BM25-only, hybrid, fallbacks) flows through Search() and the per-stage timings are picked off the same SearchMetrics bag. No per-mode-method duplication.

Database label: today the Service does not carry a database name; the observation helper flows database="" and the bag's tenantLabelsEnabled-aware Bind helpers drop the empty arg when the bag was constructed with tenantLabelsEnabled=false (Plan 04-05-06 wires tenantLabelsEnabled from cfg.Observability.Metrics.TenantLabelsEnabled). Multi-database observation is a future enhancement; M1 ships single-DB observation per CONTEXT MET-21 omission discussion.

Stage mapping per CONTEXT D-15b / MET-13 closed enum AllowedSearchStages = {embed, index, fuse}:

  • index: vector + BM25 lookup (launch-to-join wall time while the two indexes execute concurrently; capacity planning wants the joint stage budget, while response metrics retain each branch's duration)
  • fuse: RRF + MMR + rerank
  • embed: NOT observed here (the embedder call lives in pkg/embed and is already covered by nornicdb_embed_duration_seconds — Plan 04-05-02). The search stage enum reserves "embed" for completeness; a future refactor that pushes the embed call into Search would observe it under search_duration_seconds{stage="embed"} too.

MET-25 hot path discipline: per-stage observation pays one WithLabelValues lookup per Search call (NOT per request — Search is called once per logical user request). The bag's BindDuration is the pre-bound entry point; for tenant-OFF (single global database) the BoundLatencyObserver is cached at AttachMetrics time so the per-stage observation pays zero per-call lookup.

Package search provides cross-encoder reranking for improved search quality.

Cross-encoder reranking is a two-stage retrieval approach:

  1. Stage 1 (Fast): Bi-encoder retrieval - vector similarity + BM25 - Uses pre-computed embeddings for O(log N) search - Returns top-K candidates (e.g., 100)

  2. Stage 2 (Accurate): Cross-encoder reranking - Passes (query, document) pairs through a cross-encoder model - Model sees both query and document together → more accurate - Re-scores and re-ranks the top-K candidates - Returns final top-N results (e.g., 10)

Why Cross-Encoder?

Bi-encoders (like embeddings) encode query and document separately:

query_emb  = encode(query)
doc_emb    = encode(document)
score      = cosine(query_emb, doc_emb)

Cross-encoders encode them together:

score = cross_encode(query, document)  // sees interaction!

The cross-encoder can capture fine-grained semantic relationships that bi-encoders miss, but it's slower (O(N) vs O(log N)).

ELI12 (Explain Like I'm 12):

Imagine finding a book in a library:

  • Bi-encoder (Stage 1): Like using the card catalog. Fast lookup by category/keywords, but might miss nuances.

  • Cross-encoder (Stage 2): Like actually reading each book's summary. More accurate, but takes longer. So we only do it for the top candidates from Stage 1.

Reference: Nogueira & Cho (2019) "Passage Re-ranking with BERT"

Package search provides unified hybrid search with Reciprocal Rank Fusion (RRF).

This package implements the same hybrid search approach used by production systems like Azure AI Search, Elasticsearch, and Weaviate: combining vector similarity search with BM25 full-text search using Reciprocal Rank Fusion.

Search Capabilities:

  • Vector similarity search (cosine similarity with HNSW index)
  • BM25 full-text search (keyword matching with TF-IDF)
  • RRF hybrid search (fuses vector + BM25 results)
  • Adaptive weighting based on query characteristics
  • Automatic fallback when one method fails

Example Usage:

// Create search service
svc := search.NewService(storageEngine, search.DefaultVectorDimensions, nil)

// Build indexes from existing nodes
if err := svc.BuildIndexes(ctx); err != nil {
	log.Fatal(err)
}

// Perform hybrid search
query := "machine learning algorithms"
embedding := embedder.Embed(ctx, query) // Get from embed package
opts := search.DefaultSearchOptions()

response, err := svc.Search(ctx, query, embedding, opts)
if err != nil {
	log.Fatal(err)
}

for _, result := range response.Results {
	fmt.Printf("[%.3f] %s\n", result.RRFScore, result.Title)
}

How RRF Works:

RRF (Reciprocal Rank Fusion) combines rankings from multiple search methods. Instead of merging scores directly (which can be incomparable), RRF uses rank positions to create a unified ranking.

Formula: RRF_score = Σ (weight / (k + rank))

Where:

  • k is a constant (typically 60) to reduce the impact of high ranks
  • rank is the position in the result list (1-indexed)
  • weight allows emphasizing one method over another

Example: A document ranked #1 in vector search and #3 in BM25:

RRF = (1.0 / (60 + 1)) + (1.0 / (60 + 3))
    = (1.0 / 61) + (1.0 / 63)
    = 0.0164 + 0.0159
    = 0.0323

Documents that appear in both result sets get boosted scores.

ELI12 (Explain Like I'm 12):

Imagine two friends ranking pizza places:

  • Friend A (vector search) ranks by taste similarity to your favorite
  • Friend B (BM25) ranks by matching your description "spicy pepperoni"

They might disagree! Friend A says place X is #1 (tastes similar), while Friend B says it's #5 (doesn't match keywords well).

RRF solves this by: 1. If a place appears in BOTH lists, it gets bonus points 2. Higher ranks (being at the top) give more points 3. The magic number 60 prevents #1 from completely dominating

This way, a place that's #2 in both lists beats a place that's #1 in one but missing from the other!

Index persistence and WAL alignment:

NornicDB storage uses a write-ahead log (WAL) for durability; graph state is recovered from WAL (and snapshots) on startup. Search indexes (BM25 and vector) are built or loaded after storage recovery, so they always reflect the WAL-consistent state. Index files use semver format versioning (Qdrant-style): only indexes with the same format version are loaded; older or newer versions are rejected so the caller can rebuild. Persisted indexes are saved on a debounced schedule after mutations and on shutdown.

Result caching:

Search() results are cached in-process by query + options (limit, types, rerank, MMR, etc.), with the same semantics as the Cypher query cache: LRU eviction (default 1000 entries and 64 MiB retained), TTL (default 5 minutes), and full invalidation on IndexNode/RemoveNode so results stay correct after index changes. All call paths (HTTP search API, Cypher vector procedures, MCP, etc.) share this cache, so repeated identical searches return immediately.

Package search provides file-backed vector storage for memory-efficient indexing.

VectorFileStore implements append-only vector storage: vectors are written to a fixed-stride .vec file and only ID-to-ordinal metadata is kept in RAM. This allows BuildIndexes to index large datasets without holding 2–3× vector data in memory. Vectors are stored normalized (one copy per id, cosine-only) per the indexing-memory plan.

Package search provides vector indexing with cosine similarity search.

This file implements a simple but effective vector similarity search index using brute-force cosine similarity calculation. While not as sophisticated as HNSW or other approximate methods, it provides exact results and is suitable for moderate-sized datasets.

Key Features:

  • Exact cosine similarity search
  • Automatic vector normalization for performance
  • Thread-safe concurrent operations
  • Context-aware search with cancellation
  • Configurable similarity thresholds

Example Usage:

// Create vector index for 1024-dimensional embeddings
index := search.NewVectorIndex(1024)

// Add vectors to the index
embedding1 := make([]float32, 1024)
// ... populate embedding1 ...
index.Add("doc-1", embedding1)

embedding2 := make([]float32, 1024)
// ... populate embedding2 ...
index.Add("doc-2", embedding2)

// Search for similar vectors
query := make([]float32, 1024)
// ... populate query vector ...
results, err := index.Search(ctx, query, 10, 0.7)
if err != nil {
	log.Fatal(err)
}

// Process results (sorted by similarity)
for _, result := range results {
	fmt.Printf("ID: %s, Similarity: %.3f\n", result.ID, result.Score)
}

Algorithm Details:

The index uses cosine similarity, which measures the cosine of the angle between two vectors. It's particularly effective for high-dimensional embeddings where magnitude is less important than direction.

Cosine Similarity Formula:

similarity = (A · B) / (||A|| × ||B||)

Where:

  • A · B is the dot product of vectors A and B
  • ||A|| is the magnitude (L2 norm) of vector A
  • ||B|| is the magnitude (L2 norm) of vector B

Optimization:

Vectors are normalized when added to the index, so cosine similarity
becomes just the dot product, making search much faster.

Performance Characteristics:

  • Add: O(d) where d is vector dimensions
  • Search: O(n×d) where n is number of vectors
  • Memory: O(n×d) for storing normalized vectors
  • Thread-safe: Uses RWMutex for concurrent access

When to Use:

✅ Exact similarity search required
✅ Moderate dataset sizes (<100K vectors)
✅ High-dimensional embeddings (>100 dimensions)
✅ Simplicity and reliability preferred
❌ Very large datasets (>1M vectors)
❌ Approximate search acceptable
❌ Sub-linear search time required

Future Improvements:

  • HNSW implementation for O(log n) search
  • GPU acceleration for large batches
  • Quantization for memory efficiency
  • Incremental index updates

ELI12 (Explain Like I'm 12):

Think of vector similarity like comparing the "direction" things are pointing:

  1. **Vectors**: Like arrows pointing in different directions in space. Each arrow represents a document, image, or piece of text.

  2. **Cosine similarity**: Measures how much two arrows point in the same direction. If they point exactly the same way, similarity = 1. If they point opposite ways, similarity = -1.

  3. **Normalization**: We make all arrows the same length so we only care about direction, not how "strong" they are.

  4. **Search**: When you give us a query arrow, we check how similar its direction is to all the arrows we've stored, then give you the most similar ones.

It's like finding documents that "point in the same direction" as your search!

Package search - Vector search pipeline with CandidateGen + ExactScore interfaces.

This file implements the unified vector search pipeline as described in the hybrid-ann-plan.md. It provides:

  • CandidateGenerator interface for approximate candidate generation (brute/HNSW)
  • ExactScorer interface for exact scoring of candidates (CPU/GPU)
  • Auto strategy selection (HNSW by default; brute-force via explicit thresholds)
  • GPU-accelerated exact scoring when available

Index

Constants

View Source
const (
	// EnvSearchQueryMaxChunks bounds how many chunks of a long query are
	// embedded and searched (each costs an embedding call, and a rerank call
	// when reranking). Default 32.
	EnvSearchQueryMaxChunks = "NORNICDB_SEARCH_QUERY_MAX_CHUNKS"
	// EnvSearchQueryChunkOverflow chooses what a query with more chunks than
	// that does: "truncate" (the default) searches the first chunks and
	// reports the rest as dropped; "error" fails the search.
	EnvSearchQueryChunkOverflow = "NORNICDB_SEARCH_QUERY_CHUNK_OVERFLOW"
)
View Source
const (
	// EnvSearchRerankMaxDocumentChars bounds each candidate sent to a reranker,
	// in characters (Unicode code points), so the same setting yields the same
	// amount of text for Latin, Cyrillic or CJK content.
	EnvSearchRerankMaxDocumentChars = "NORNICDB_SEARCH_RERANK_MAX_DOCUMENT_CHARS"
	// EnvSearchRerankMaxDocumentBytes is the deprecated predecessor of
	// EnvSearchRerankMaxDocumentChars. It is honoured when the new variable is
	// unset and its value is interpreted as a character count.
	EnvSearchRerankMaxDocumentBytes = "NORNICDB_SEARCH_RERANK_MAX_DOCUMENT_BYTES"

	// EnvSearchRerankContextProperties lists the short identifying properties
	// (comma-separated) placed in front of every rerank candidate so the
	// reranker knows which document a passage belongs to.
	EnvSearchRerankContextProperties = "NORNICDB_SEARCH_RERANK_CONTEXT_PROPERTIES"
)
View Source
const (
	// EnvSearchLogTimings enables per-query timing logs for search stages.
	// When true, logs vector/BM25/fusion/total timing to help identify bottlenecks.
	EnvSearchLogTimings = "NORNICDB_SEARCH_LOG_TIMINGS"
	// EnvSearchResultCacheEnabled controls caching of complete Search responses.
	// Disable it when callers require every request to execute the retrieval pipeline.
	EnvSearchResultCacheEnabled = "NORNICDB_SEARCH_RESULT_CACHE_ENABLED"
)
View Source
const (
	// SearchMatchChunk is a SearchMatch of an embedding chunk.
	SearchMatchChunk = "chunk"
	// SearchMatchTerm is a SearchMatch of a query term occurrence.
	SearchMatchTerm = "term"
)
View Source
const (
	SearchContinuationRanked       SearchContinuationMode = "ranked"
	SearchContinuationRankedThenID SearchContinuationMode = "ranked_then_id"
	SearchContinuationID           SearchContinuationMode = "id"

	SearchContinuationRankedPhase  = "ranked"
	SearchContinuationCatalogPhase = "catalog"

	SearchContinuationMoreResults        = "more_results"
	SearchContinuationCandidateComplete  = "candidate_pool_exhausted"
	SearchContinuationCollectionComplete = "eligible_population_exhausted"
	SearchContinuationMaxResultsComplete = "max_results_reached"
)
View Source
const (
	VectorIndexPopulating = "POPULATING"
	VectorIndexOnline     = "ONLINE"
	VectorIndexFailed     = "FAILED"
)

Vector index population states, as Neo4j 5.26 reports and enforces them.

View Source
const DefaultMinEmbeddingsForClustering = 1000

DefaultMinEmbeddingsForClustering is the default minimum number of embeddings needed before k-means clustering provides any benefit. Below this threshold, the default non-clustered vector strategy avoids cluster overhead.

This value can be overridden per-service using SetMinEmbeddingsForClustering().

Performance Scaling (Real-World Benchmarks):

  • <1000 embeddings: Clustering overhead > speedup benefit
  • 2,000 embeddings: ~14% faster with clustering
  • 4,500 embeddings: ~26% faster with clustering
  • 10,000+ embeddings: 10-50x faster with clustering

Tuning Guidelines:

  • 1000 (default): Safe for most workloads, proven performance benefit
  • 500-1000: Use for latency-sensitive apps (14-26% speedup range)
  • 100-500: Testing or small datasets (verify clustering works)
  • 2000+: Very large datasets (maximize speedup, delay until more data)

Environment Variable: NORNICDB_KMEANS_MIN_EMBEDDINGS (overrides default)

View Source
const DefaultVectorDimensions = 1024

DefaultVectorDimensions is the embedding size used by NewService (e.g. bge-m3). Pass schema/query-derived dimensions to NewService when your model differs.

View Source
const (
	// NSmallMax is the default maximum dataset size for automatic CPU brute-force
	// search. Zero makes HNSW the default unless NORNICDB_VECTOR_CPU_BRUTE_MAX_N
	// opts into CPU brute-force for datasets below that threshold.
	NSmallMax = 0
)

Configuration constants for the vector search pipeline.

Variables

View Source
var ErrCUDANotAvailableForBuild = errors.New("cuda: CUDA HNSW build acceleration not available (build without cuda tag or unsupported platform)")

ErrCUDANotAvailableForBuild is returned when CUDA HNSW build acceleration is not available on this platform or build configuration.

View Source
var (
	ErrDimensionMismatch = errors.New("vector dimension mismatch")
)
View Source
var ErrFilterEvaluation = errors.New("search filter evaluation failed")

ErrFilterEvaluation marks the error of a caller's Where or RelationshipWhere that could not decide a candidate. It ends the search that asked: no fallback, retry or other query chunk replaces it (finalSearchError), since a different candidate set would silently leave out the candidate the filter could not decide. The filter's own error stays its cause.

View Source
var ErrIndexMemoryBudgetExceeded = errors.New("search: index memory budget exceeded")

ErrIndexMemoryBudgetExceeded identifies a per-database index capacity rejection.

View Source
var ErrRelationshipSearchDisabled = errors.New("relationship search is not enabled")

ErrRelationshipSearchDisabled is returned for a relationship search on a database whose relationship indexing is off.

View Source
var ErrRelationshipSnapshotUpgradeRequired = errors.New("relationship snapshot upgrade required; back up the data and restart with --upgrade-storage")

ErrRelationshipSnapshotUpgradeRequired means a persisted relationship snapshot still uses the historical gob format.

View Source
var ErrSearchIndexBuilding = errors.New("search index being built, please try again when they are complete")
View Source
var ErrVectorDisabled = errors.New("search: vector search disabled for this database")

ErrVectorDisabled signals that the per-DB vector master switch is off and the caller must skip not just the vector store write but every downstream vector-side bookkeeping step (node→vector ID maps, GPU, HNSW, cluster index, etc.). indexNodeLocked branches on this so a vector-disabled service incurs only the flag-check cost per node, not the full vector traversal of every property.

View Source
var ErrVectorIndexFailed = errors.New("search: vector index population failed")

ErrVectorIndexFailed is a query of a vector index whose population failed: it answers nothing until it is dropped and created again.

View Source
var ErrVectorIndexNotOnline = errors.New("search: vector index not online")

ErrVectorIndexNotOnline is a query of a vector index still populating when its wait for the index ran out.

View Source
var SearchableProperties = []string{
	"content",
	"text",
	"title",
	"name",
	"description",
	"path",
	"workerRole",
	"requirements",
}

SearchableProperties defines PRIORITY properties for full-text search ranking. These properties are indexed first for better BM25 ranking. Note: ALL node properties are indexed, but these get priority weighting. These match Neo4j's fulltext index configuration.

Functions

func BuildIVFPQFromVectorStore

func BuildIVFPQFromVectorStore(ctx context.Context, vfs *VectorFileStore, profile IVFPQProfile, seedEntryIDs []string) (*IVFPQIndex, *IVFPQBuildStats, error)

BuildIVFPQFromVectorStore builds a full IVF/PQ index from VectorFileStore.

func ConvertSearchIndexDirFromGobToMsgpack

func ConvertSearchIndexDirFromGobToMsgpack(rootDir string) error

ConvertSearchIndexDirFromGobToMsgpack converts search index .gob files under rootDir to msgpack and removes the .gob extension (writes to vectors, hnsw, hnsw_ivf/0, 1, ...). It also converts each db directory's bm25.v2.relationships, and the same file under its g- generation directories, from gob to msgpack in place. rootDir should be the search index root (e.g. data/test/search). Back up the directory before running.

func DeriveIVFCentroidsFromClusters

func DeriveIVFCentroidsFromClusters(hnswPath string, vectorLookup VectorLookup) (centroids [][]float32, idToCluster map[string]int, err error)

DeriveIVFCentroidsFromClusters builds centroids and idToCluster from the persisted generation's cluster files and vectors from the vector index. No separate centroid file. Returns (nil, nil, nil) if no generation was persisted or derivation fails.

func LimitQueryChunks

func LimitQueryChunks(chunks []string) ([]string, error)

LimitQueryChunks keeps the chunks of a query that are searched: all of them, or the first QueryMaxChunks. Over the limit it fails instead when NORNICDB_SEARCH_QUERY_CHUNK_OVERFLOW=error, so a caller never gets a ranking for part of its query without knowing it.

func NodeChunkVectorKey

func NodeChunkVectorKey(nodeID string, chunk int) string

NodeChunkVectorKey is the vector-entry key of chunk index of nodeID (chunk 0 is the node's main vector), for callers outside this package that build HNSW or cluster indexes keyed like the search service's own.

func QueryMaxChunks

func QueryMaxChunks() int

QueryMaxChunks is the configured most chunks of one query that are embedded and searched.

func ReadFulltextCandidates

func ReadFulltextCandidates[T any](ctx context.Context, d FulltextDocuments, node T, reader FulltextLiteralReader[T], visit func(string, *FulltextDocument) error) error

ReadFulltextCandidates visits a conservative candidate superset. The visit must still run the dialect's exact matcher; collisions never establish matches or scores. Complete-corpus statistics are independent of this selected population.

func RefreshIndexes

func RefreshIndexes[Scope RefreshScope](ctx context.Context, scope Scope, request RefreshRequest) error

RefreshIndexes refreshes the indexes for a mutation a caller committed or made visible. It is the one path from a producer to Service.RefreshNode and Service.RefreshEdge: the scope decides whether the request happens now or after a commit, and the refresh itself reads the current stored state, so a newer write or delete wins over this request.

A request naming nothing is a no-op and resolves no service. When the scope defers the request, the deferring owner refreshes it. Otherwise the node is refreshed before the relationship. Both are attempted even if the node fails; the node's error is the one returned, as before.

func RequireAllQueryChunks

func RequireAllQueryChunks(chunks []string) error

RequireAllQueryChunks fails a query with more chunks than are searched, whatever NORNICDB_SEARCH_QUERY_CHUNK_OVERFLOW says: for a caller whose results have no place to report dropped chunks.

func SaveIVFHNSW

func SaveIVFHNSW(hnswPath string, graphs map[int]*HNSWIndex) error

SaveIVFHNSW persists one generation of per-cluster HNSW indexes to disk under hnsw_ivf/ alongside hnsw, graph-only, described by a manifest written last. hnswPath is the full path to the single HNSW file (e.g. data/search/dbname/hnsw).

func SaveIVFHNSWWithContext added in v1.1.8

func SaveIVFHNSWWithContext(ctx context.Context, hnswPath string, graphs map[int]*HNSWIndex) error

SaveIVFHNSWWithContext captures every graph before writing any file, so the generation saved is the graphs as they were at the call; callers that change the graphs concurrently capture them under their own exclusion (Service persistence: snapshotClusterGenerationLocked).

func SaveIVFPQBundle

func SaveIVFPQBundle(basePath string, idx *IVFPQIndex) error

SaveIVFPQBundle persists an IVFPQ index as an atomic multipart bundle.

func SearchMatchValues

func SearchMatchValues(matches []SearchMatch) []any

SearchMatchValues is matches as Value lists them.

func UpgradeRelationshipSnapshot

func UpgradeRelationshipSnapshot(path string, allowUpgrade bool, syncDirectory func(string) error) error

UpgradeRelationshipSnapshot validates and, when authorized, converts a historical relationship-vector snapshot to MessagePack. syncDirectory may be nil to use the platform's default directory durability operation. A successful rename followed by a failed sync is retried on the next call. The caller must stop services writing the file before conversion. A missing file is a no-op; an unauthorized gob file returns ErrRelationshipSnapshotUpgradeRequired and remains unchanged.

err := UpgradeRelationshipSnapshot("data/search/nornic/bm25.v2.relationships", true, nil)

Types

type ANNQuality

type ANNQuality string

ANNQuality selects the high-level ANN strategy mode.

const (
	ANNQualityFast       ANNQuality = "fast"
	ANNQualityBalanced   ANNQuality = "balanced"
	ANNQualityAccurate   ANNQuality = "accurate"
	ANNQualityCompressed ANNQuality = "compressed"
)

func ANNQualityFromEnv

func ANNQualityFromEnv() ANNQuality

ANNQualityFromEnv parses the global ANN quality selector. Unknown values default to fast to preserve historical behavior.

type ANNResult

type ANNResult struct {
	ID    string
	Score float32
}

ANNResult is a minimal search result from the ANN index (HNSW).

This intentionally stays small (ID + float32 score) to keep per-request allocations and copy costs low. Higher-level layers can enrich results as needed (labels, properties, etc.).

type Analyzer

type Analyzer interface {
	Analyze(text string) []string
	Fingerprint() AnalyzerFingerprint
}

Analyzer converts text into BM25 terms.

func DefaultTextAnalyzer

func DefaultTextAnalyzer() Analyzer

DefaultTextAnalyzer returns NornicDB's language-neutral BM25 analyzer.

func NewStemmedTextAnalyzer

func NewStemmedTextAnalyzer(reg stemmer.Registration) Analyzer

NewStemmedTextAnalyzer returns a BM25 analyzer backed by a registered stemmer.

type AnalyzerFingerprint

type AnalyzerFingerprint struct {
	Tokenizer         string
	StemmerID         string
	StemmerAPIVersion int
	StemmerVersion    string
	StemmerSHA256     string
}

AnalyzerFingerprint identifies the tokenization and stemming contract used to build a BM25 index.

func (AnalyzerFingerprint) BuildSettings

func (f AnalyzerFingerprint) BuildSettings() string

BuildSettings renders the stable persisted-index compatibility fragment.

type BruteForceCandidateGen

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

BruteForceCandidateGen implements CandidateGenerator using brute-force search.

This is available for explicit brute-force paths. The default vector pipeline uses HNSW unless NORNICDB_VECTOR_CPU_BRUTE_MAX_N is set above zero.

func NewBruteForceCandidateGen

func NewBruteForceCandidateGen(vectorIndex *VectorIndex) *BruteForceCandidateGen

NewBruteForceCandidateGen creates a new brute-force candidate generator.

func (*BruteForceCandidateGen) SearchCandidates

func (b *BruteForceCandidateGen) SearchCandidates(ctx context.Context, query []float32, k int, minSimilarity float64) ([]Candidate, error)

SearchCandidates generates candidates using brute-force search.

type BuildProgress

type BuildProgress struct {
	Ready           bool
	Building        bool
	Phase           string
	ProcessedNodes  int64
	TotalNodes      int64
	RateNodesPerSec float64
	ETASeconds      int64 // -1 when unknown
}

BuildProgress reports in-progress indexing state for UI/ops visibility.

type CPUExactScorer

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

CPUExactScorer implements ExactScorer using CPU-based exact scoring.

Uses SIMD-optimized dot product for cosine similarity computation.

func NewCPUExactScorer

func NewCPUExactScorer(getter VectorGetter) *CPUExactScorer

NewCPUExactScorer creates a new CPU-based exact scorer. getter can be *VectorIndex or any type that implements GetVector (e.g. file-store lookup adapter).

func (*CPUExactScorer) ScoreCandidates

func (c *CPUExactScorer) ScoreCandidates(ctx context.Context, query []float32, candidates []Candidate) ([]ScoredCandidate, error)

ScoreCandidates computes exact scores for candidates using CPU.

type CPUHNSWBuildAccelerator added in v1.1.7

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

CPUHNSWBuildAccelerator is the CPU build kernel: exact all-pairs scoring of a build batch, parallel across queries. The HNSW build uses it when no GPU is enabled or available.

func NewCPUHNSWBuildAccelerator added in v1.1.7

func NewCPUHNSWBuildAccelerator() *CPUHNSWBuildAccelerator

NewCPUHNSWBuildAccelerator creates a CPU implementation of the build accelerator interface.

func (*CPUHNSWBuildAccelerator) CandidateSearch added in v1.1.7

func (a *CPUHNSWBuildAccelerator) CandidateSearch(ctx context.Context, queries [][]float32, frontier [][]float32, topK int) ([][]int, [][]float32, error)

func (*CPUHNSWBuildAccelerator) Close added in v1.1.7

func (a *CPUHNSWBuildAccelerator) Close() error

func (*CPUHNSWBuildAccelerator) Prepare added in v1.1.7

func (a *CPUHNSWBuildAccelerator) Prepare(dim int, _ int) error

type Candidate

type Candidate struct {
	ID    string
	Score float64 // Approximate score from candidate generation
}

Candidate represents a candidate vector with approximate score.

type CandidateGenerator

type CandidateGenerator interface {
	// SearchCandidates generates candidate vectors for the given query.
	//
	// Parameters:
	//   - ctx: Context for cancellation
	//   - query: Normalized query vector
	//   - k: Desired number of results
	//   - minSimilarity: Minimum similarity threshold (approximate, may be relaxed)
	//
	// Returns:
	//   - candidates: Candidate IDs with approximate scores (may be more than k)
	//   - error: Context cancellation or other errors
	SearchCandidates(ctx context.Context, query []float32, k int, minSimilarity float64) ([]Candidate, error)
}

CandidateGenerator generates candidate vectors for approximate search.

Implementations:

  • BruteForceCandidateGen: Exact search over all vectors (explicit opt-in)
  • HNSWCandidateGen: Approximate search using HNSW graph (default)

The generator returns candidate IDs and approximate scores. These candidates will be re-scored exactly by ExactScorer before final ranking.

type ChunkQueryFunc added in v1.3.3

type ChunkQueryFunc func(ctx context.Context, query string) ([]string, error)

ChunkQueryFunc splits a text query into embedding-safe chunks.

type ChunkedSearchErrorPolicy added in v1.3.3

type ChunkedSearchErrorPolicy struct {
	FatalEmbeddingError func(error) bool
	FatalSearchError    func(error) bool
	// Transport identifies the caller in fallback warning logs.
	Transport string
}

ChunkedSearchErrorPolicy identifies adapter-specific errors that must not fall back.

type CompleteContinuationPolicy added in v1.3.3

type CompleteContinuationPolicy struct {
	MaxScannedNodes     int
	MaxMembers          int
	MaxPassages         int
	MaxBuildBytes       int64
	MaxBuildDuration    time.Duration
	MaxConcurrentBuilds int64
}

CompleteContinuationPolicy bounds exact population materialization. A zero field uses its default so callers can override one limit independently.

type CompressedANNProfile

type CompressedANNProfile struct {
	Quality             ANNQuality
	Active              bool
	Dimensions          int
	VectorCount         int
	IVFLists            int
	PQSegments          int
	PQBits              int
	NProbe              int
	RerankTopK          int
	TrainingSampleMax   int
	KMeansMaxIterations int
	OverflowMax         int
	SeedMaxTerms        int
	SeedDocsPerTerm     int
	RoutingMode         string
	Diagnostics         []CompressedActivationDiagnostic
}

CompressedANNProfile is the resolved runtime contract for compressed ANN mode.

func ResolveCompressedANNProfile

func ResolveCompressedANNProfile(vectorCount, dimensions int, vectorStoreReady bool) CompressedANNProfile

type CompressedActivationDiagnostic

type CompressedActivationDiagnostic struct {
	Code    string
	Message string
}

CompressedActivationDiagnostic captures deterministic activation decisions.

type CrossEncoder

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

CrossEncoder performs cross-encoder reranking.

func NewCrossEncoder

func NewCrossEncoder(config *CrossEncoderConfig) *CrossEncoder

NewCrossEncoder creates a new cross-encoder reranker.

func (*CrossEncoder) Config

func (ce *CrossEncoder) Config() *CrossEncoderConfig

Config returns the current configuration.

func (*CrossEncoder) Enabled

func (ce *CrossEncoder) Enabled() bool

func (*CrossEncoder) IsAvailable

func (ce *CrossEncoder) IsAvailable(ctx context.Context) bool

IsAvailable checks if the reranking service is available.

func (*CrossEncoder) Name

func (ce *CrossEncoder) Name() string

func (*CrossEncoder) Rerank

func (ce *CrossEncoder) Rerank(ctx context.Context, query string, candidates []RerankCandidate) (_ []RerankResult, err error)

Rerank takes a query and candidates, returns reranked results.

type CrossEncoderConfig

type CrossEncoderConfig struct {
	// Enabled turns on cross-encoder reranking
	Enabled bool

	// APIURL is the reranking service endpoint
	// Supports: Cohere, HuggingFace TEI, local models
	APIURL string

	// APIKey for authentication (if required)
	APIKey string

	// Model name (e.g., "cross-encoder/ms-marco-MiniLM-L-6-v2")
	Model string

	// TopK is how many candidates to rerank (default: 100)
	TopK int

	// Timeout for reranking requests
	Timeout time.Duration

	// MinScore is the minimum rerank score to include (0-1)
	MinScore float64
}

CrossEncoderConfig configures the cross-encoder reranker.

func DefaultCrossEncoderConfig

func DefaultCrossEncoderConfig() *CrossEncoderConfig

DefaultCrossEncoderConfig returns sensible defaults.

type CudaHNSWBuildAccelerator added in v1.1.11

type CudaHNSWBuildAccelerator struct{}

CudaHNSWBuildAccelerator is a stub used when CUDA is not available.

func NewCudaHNSWBuildAccelerator added in v1.1.11

func NewCudaHNSWBuildAccelerator() (*CudaHNSWBuildAccelerator, error)

NewCudaHNSWBuildAccelerator always returns an error in stub mode.

func (*CudaHNSWBuildAccelerator) CandidateSearch added in v1.1.11

func (a *CudaHNSWBuildAccelerator) CandidateSearch(context.Context, [][]float32, [][]float32, int) ([][]int, [][]float32, error)

func (*CudaHNSWBuildAccelerator) Close added in v1.1.11

func (a *CudaHNSWBuildAccelerator) Close() error

func (*CudaHNSWBuildAccelerator) Prepare added in v1.1.11

func (a *CudaHNSWBuildAccelerator) Prepare(int, int) error

type EdgeMutation

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

EdgeMutation is NodeMutation for a relationship's vector and relationship search entries.

type EmbedQueryFunc added in v1.3.3

type EmbedQueryFunc func(ctx context.Context, query string) ([]float32, error)

EmbedQueryFunc embeds one query chunk. A nil or empty vector is unavailable.

type ExactScorer

type ExactScorer interface {
	// ScoreCandidates computes exact similarity scores for the given candidates.
	//
	// Parameters:
	//   - ctx: Context for cancellation
	//   - query: Normalized query vector
	//   - candidates: Candidate IDs to score (may include approximate scores for reference)
	//
	// Returns:
	//   - scored: Candidates with exact scores
	//   - error: Context cancellation or other errors
	ScoreCandidates(ctx context.Context, query []float32, candidates []Candidate) ([]ScoredCandidate, error)
}

ExactScorer computes exact similarity scores for candidate vectors.

Implementations:

  • CPUExactScorer: CPU-based exact scoring (SIMD-optimized)
  • GPUExactScorer: GPU-accelerated exact scoring (when available)

The scorer takes candidate IDs and returns exact scores using the true metric (cosine/dot/euclid), ensuring final ranking accuracy.

type FileStoreBruteForceCandidateGen

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

FileStoreBruteForceCandidateGen implements CandidateGenerator using brute-force search directly over the file-backed vector store.

func NewFileStoreBruteForceCandidateGen

func NewFileStoreBruteForceCandidateGen(vectorStore *VectorFileStore) *FileStoreBruteForceCandidateGen

NewFileStoreBruteForceCandidateGen creates a brute-force candidate generator over VectorFileStore.

func (*FileStoreBruteForceCandidateGen) SearchCandidates

func (b *FileStoreBruteForceCandidateGen) SearchCandidates(ctx context.Context, query []float32, k int, minSimilarity float64) ([]Candidate, error)

SearchCandidates scans all vectors from the file store and returns top candidates by exact cosine score.

type FulltextBatchEntry

type FulltextBatchEntry struct {
	ID   string
	Text string
}

FulltextBatchEntry is one (id, text) pair for IndexBatch.

type FulltextDocument

type FulltextDocument struct {
	Text   string
	Tokens int
	Value  any
	// MatchFields aliases the immutable normalized field view used by the dialect.
	// Literal exclusion includes these fields as well as Text; exact matching and
	// scoring remain the dialect's responsibility. No copied field map is needed.
	MatchFields map[string]string
	// RetainedBytes forecasts the dialect field representation, including Text.
	// Zero uses the body plus a document header for generic consumers.
	RetainedBytes int64
}

FulltextDocument is an immutable document supplied by a query dialect. The service owns its maintenance; the dialect owns its existing matching/scoring. Text is the canonical scoring body, and Value holds the dialect's field view.

type FulltextDocumentBuilder

type FulltextDocumentBuilder func(*storage.Node, *storage.Edge) *FulltextDocument

FulltextDocumentBuilder adapts a stored node or relationship to a dialect's document. Exactly one argument is non-nil. A nil result excludes the entity.

type FulltextDocumentScope

type FulltextDocumentScope struct {
	Name, Definition string
	// NodeLabels limits population to the union of these label indexes.
	// Membership remains the dialect builder's responsibility.
	NodeLabels []string
	// QueryNodes returns row metadata without decoding stored chunk vectors.
	QueryNodes    bool
	Relationships bool
	Fresh         bool
	Ordered       bool
	// EntityRows asks for request-scoped output images, independently of the
	// retained scoring representation. Images never survive the request lease.
	EntityRows bool
	Retain     func(string) bool
	// Candidate reports whether an entity image can be one of the
	// projection's documents; the builder returns nil for every other image.
	// Changes to entities that are neither candidates nor current documents
	// of any projection are not journaled. Nil journals every change.
	Candidate func(*storage.Node, *storage.Edge) bool
}

FulltextDocumentScope describes one schema projection and its read view. Fresh selects a request-scoped view for time-dependent visibility. Retain tells the service which named schema projections still exist.

type FulltextDocuments

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

FulltextDocuments presents either leased complete statistics or an ordered acquisition for this request. The service owns the read context it accepts and supplies it to the read callback; callers must not retain this value or mutate documents.

func (FulltextDocuments) AverageLength

func (d FulltextDocuments) AverageLength() float64

func (FulltextDocuments) BodyDocumentFrequencies

func (d FulltextDocuments) BodyDocumentFrequencies(ctx context.Context, terms []string) (map[string]int, error)

BodyDocumentFrequencies counts the scoring documents whose body literally contains each requested term, exactly as the release's strings.Contains predicate does. Retained literal signatures narrow possible bodies before that exact check; small/request-local corpora use one shared counting pass. Short and empty terms retain the same predicate. Every visited document and posting block observes cancellation. A failure returns no counts at all.

The view keeps the most recent term set's counts, bounded by one query's unique terms, and reuses them only for exactly that term set. The returned map belongs to the caller; the retained copy is private, and changing the result never changes it.

func (FulltextDocuments) Count

func (d FulltextDocuments) Count() int

Count and AverageLength describe the complete scoped corpus, before limits and eligibility filtering, as required by the dialect's score calculation.

func (FulltextDocuments) Each

func (d FulltextDocuments) Each(ctx context.Context, visit func(string, *FulltextDocument) error) error

Each supplies every scoring document to the dialect's existing evaluator on the caller's context, and returns its cancellation or the visit's error. Body counts are never a substitute for the evaluator's field population.

func (FulltextDocuments) Entity

Entity materializes an emitted row on the caller's context. A population already holds its original image for this request; a reuse hydrates from its short-certified committed capture. It never obtains a later live image. A callback may be reevaluated once through the original population if a captured row is unavailable.

func (FulltextDocuments) VisitEdges

func (d FulltextDocuments) VisitEdges(ctx context.Context, visit func(*storage.Edge) error) error

func (FulltextDocuments) VisitNodes

func (d FulltextDocuments) VisitNodes(ctx context.Context, visit func(*storage.Node) error) error

VisitNodes and VisitEdges carry the caller's context and stop directly into the issued native/fallback reader.

type FulltextIndexV2

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

FulltextIndexV2 provides BM25-based full-text search. It stores compact postings (docNum/tf) and uses bounded prefix expansion + top-k scoring.

func NewFulltextIndexV2WithAnalyzer

func NewFulltextIndexV2WithAnalyzer(analyzer Analyzer) *FulltextIndexV2

NewFulltextIndexV2WithAnalyzer creates a full-text search index with the supplied analyzer. A nil analyzer selects the default analyzer.

func (*FulltextIndexV2) Clear

func (f *FulltextIndexV2) Clear()

func (*FulltextIndexV2) Count

func (f *FulltextIndexV2) Count() int

func (*FulltextIndexV2) GetDocument

func (f *FulltextIndexV2) GetDocument(id string) (string, bool)

func (*FulltextIndexV2) Index

func (f *FulltextIndexV2) Index(id, text string, terms []string, frequency map[string]int, prepared bool)

Index adds or updates a document. When prepared is false, it analyzes text itself and ignores terms and frequency. When prepared is true, those inputs must contain the analyzer's tokens and their frequencies for the text.

func (*FulltextIndexV2) IndexBatch

func (f *FulltextIndexV2) IndexBatch(entries []FulltextBatchEntry)

IndexBatch adds or updates many documents under one lock and updates avgDocLength once at the end. Use this during bulk build to reduce lock contention and avoid O(N) avg updates.

func (*FulltextIndexV2) IsDirty

func (f *FulltextIndexV2) IsDirty() bool

func (*FulltextIndexV2) LexicalSeedDocIDs

func (f *FulltextIndexV2) LexicalSeedDocIDs(maxTerms, docsPerTerm int) []string

func (*FulltextIndexV2) LexicalSeedHints

func (f *FulltextIndexV2) LexicalSeedHints(maxTerms, docsPerTerm int) []LexicalSeedHint

LexicalSeedHints returns ranked compact lexical metadata directly from the inverted index, without executing a BM25 search for each document.

func (*FulltextIndexV2) Load

func (f *FulltextIndexV2) Load(path string) error

Load replaces the fulltext index with the one stored at path (msgpack format). A missing file leaves the index as it is and no error is returned; a file that is not a compatible BM25 snapshot empties the index so the caller rebuilds it from graph storage. Only unexpected I/O (e.g. permission denied) returns an error.

func (*FulltextIndexV2) PhraseSearch

func (f *FulltextIndexV2) PhraseSearch(phrase string, limit int) []indexResult

func (*FulltextIndexV2) Remove

func (f *FulltextIndexV2) Remove(id string)

func (*FulltextIndexV2) Save

func (f *FulltextIndexV2) Save(path string) error

func (*FulltextIndexV2) SaveNoCopy

func (f *FulltextIndexV2) SaveNoCopy(path string) error

func (*FulltextIndexV2) Search

func (f *FulltextIndexV2) Search(query string, limit int) []indexResult

func (*FulltextIndexV2) SearchAllowed

func (f *FulltextIndexV2) SearchAllowed(query string, limit int, allowed func(docID string) bool) []indexResult

SearchAllowed is Search over the documents allowed accepts: a document it rejects is never scored or returned, so the top limit are the best allowed documents however many better ones it rejects (#938). allowed is called at most once per document, while the index's read lock is held; nil allows every document.

func (*FulltextIndexV2) TermIDF

func (f *FulltextIndexV2) TermIDF(term string) float64

TermIDF is the BM25 IDF of an analyzed term, the weight a match on it gets: higher for a rarer term, 0 for one no live document holds.

type FulltextLiteralNode

type FulltextLiteralNode struct {
	Op       FulltextLiteralOperation
	Text     string
	Children int
}

FulltextLiteralNode describes one source node without copying its children. Children is the source's indexed child range, including children Child skips.

type FulltextLiteralOperation

type FulltextLiteralOperation uint8

FulltextLiteralOperation describes conservative positive candidate selection. Exact field predicates, exclusions and scoring remain in the query dialect.

const (
	FulltextAllCandidates FulltextLiteralOperation = iota
	FulltextLiteral
	FulltextAllOf
	FulltextAnyOf
)

type FulltextLiteralReader

type FulltextLiteralReader[T any] interface {
	Describe(context.Context, T) (FulltextLiteralNode, error)
	Child(context.Context, T, FulltextLiteralOperation, int) (T, bool, error)
}

FulltextLiteralReader exposes pure syntax metadata to the candidate compiler. Describe and Child must not read storage or retain request state. The compiler owns cancellation, compiled storage and execution. A dialect can supply its existing immutable syntax nodes directly, avoiding another allocated tree.

type FulltextLiteralSelector

type FulltextLiteralSelector struct {
	Op       FulltextLiteralOperation
	Text     string
	Children []FulltextLiteralSelector
}

FulltextLiteralSelector is a conservative candidate expression. A literal refers to byte-substring presence in Text or MatchFields. AllOf intersects child populations; AnyOf unions them. Never complement a lossy candidate set for a prohibited clause. The zero value admits the complete corpus. For example, a mandatory exact term can use {Op: FulltextLiteral, Text: "otel"}.

type FulltextLiteralTree

type FulltextLiteralTree struct{}

FulltextLiteralTree reads an explicitly constructed selector tree. For example, ReadFulltextCandidates(ctx, documents, selector, FulltextLiteralTree{}, visit). Dialects with their own syntax trees implement FulltextLiteralReader directly.

func (FulltextLiteralTree) Describe

type FulltextRetentionStatus

type FulltextRetentionStatus struct {
	Index         string `json:"index"`
	Relationships bool   `json:"relationships"`
	Retained      bool   `json:"retained"`
	StorageReads  bool   `json:"storage_reads"`
	Documents     int    `json:"documents"`
	Bytes         int64  `json:"estimated_bytes"`
	MemoryUsed    int64  `json:"memory_used_bytes"`
	MemoryLimit   int64  `json:"memory_limit_bytes"`
	MemorySource  string `json:"memory_source"`
}

FulltextRetentionStatus describes an optional procedure corpus. Released indexes remain searchable: the same acquisition reads their data from storage.

type GPUBruteForceCandidateGen

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

GPUBruteForceCandidateGen uses gpu.EmbeddingIndex.Search() as an exact candidate generator.

Note: gpu.EmbeddingIndex.Search() does not currently accept a context, so this generator cannot cancel mid-kernel. It checks ctx before invoking the search.

func NewGPUBruteForceCandidateGen

func NewGPUBruteForceCandidateGen(embeddingIndex *gpu.EmbeddingIndex) *GPUBruteForceCandidateGen

func (*GPUBruteForceCandidateGen) SearchCandidates

func (g *GPUBruteForceCandidateGen) SearchCandidates(ctx context.Context, query []float32, k int, minSimilarity float64) ([]Candidate, error)

type GPUExactScorer

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

GPUExactScorer implements ExactScorer using GPU-accelerated exact scoring.

Falls back to CPU if GPU is unavailable or unhealthy.

func NewGPUExactScorer

func NewGPUExactScorer(embeddingIndex *gpu.EmbeddingIndex, cpuFallback *CPUExactScorer) *GPUExactScorer

NewGPUExactScorer creates a new GPU-based exact scorer.

func (*GPUExactScorer) ScoreCandidates

func (g *GPUExactScorer) ScoreCandidates(ctx context.Context, query []float32, candidates []Candidate) ([]ScoredCandidate, error)

ScoreCandidates computes exact scores for candidates using GPU when available.

Note: Since EmbeddingIndex.Search() searches all vectors, we use it for candidate scoring by searching with a large k, then filtering to only the candidates we care about. This is not optimal but works with the current EmbeddingIndex API. A future PR will add ScoreSubset() for true subset scoring.

type GPUKMeansCandidateGen

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

GPUKMeansCandidateGen routes queries to the nearest k-means clusters and then scores only the vectors in those clusters using the GPU embedding index when available.

This is used as a high-throughput fallback when:

  • GPU brute-force is enabled but the dataset is outside the configured full-scan range, and
  • clustering is available (centroids + cluster membership already built).

It preserves correctness by returning exact cosine scores for the candidate set. When the GPU cannot score (not synced / unhealthy), ScoreSubset falls back to CPU.

func NewGPUKMeansCandidateGen

func NewGPUKMeansCandidateGen(clusterIndex *gpu.ClusterIndex, numClustersToSearch int) *GPUKMeansCandidateGen

func (*GPUKMeansCandidateGen) SearchCandidates

func (g *GPUKMeansCandidateGen) SearchCandidates(ctx context.Context, query []float32, k int, minSimilarity float64) ([]Candidate, error)

func (*GPUKMeansCandidateGen) SetClusterSelector

func (g *GPUKMeansCandidateGen) SetClusterSelector(fn func(ctx context.Context, query []float32, defaultN int) []int) *GPUKMeansCandidateGen

SetClusterSelector sets an optional custom cluster selector used for routing.

func (*GPUKMeansCandidateGen) SetServing

func (g *GPUKMeansCandidateGen) SetServing(lock sync.Locker, view func(context.Context) (context.Context, clusterView, func())) *GPUKMeansCandidateGen

SetServing makes the generator serve each query from the cluster generation the query holds (see clusterServing); the selector is then called with lock held.

type HNSWBuildAccelerator added in v1.1.7

type HNSWBuildAccelerator interface {
	Prepare(dim int, maxNodes int) error
	CandidateSearch(ctx context.Context, queries [][]float32, frontier [][]float32, topK int) (indices [][]int, distances [][]float32, err error)
	Close() error
}

HNSWBuildAccelerator scores a build batch against itself for HNSW construction (CandidateSearch with the batch as both queries and frontier): a dense all-pairs product, which suits a GPU. The graph search for neighbours already in the index runs on the CPU, and the CPU performs all graph mutation and reciprocal linking, so persisted artifacts are identical in format to CPU-built indexes.

type HNSWCandidateGen

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

HNSWCandidateGen implements CandidateGenerator using HNSW approximate search.

This is the default vector-search candidate generator.

func NewHNSWCandidateGen

func NewHNSWCandidateGen(hnswIndex *HNSWIndex) *HNSWCandidateGen

NewHNSWCandidateGen creates a new HNSW candidate generator.

func (*HNSWCandidateGen) SearchCandidates

func (h *HNSWCandidateGen) SearchCandidates(ctx context.Context, query []float32, k int, minSimilarity float64) ([]Candidate, error)

SearchCandidates generates candidates using HNSW approximate search.

type HNSWConfig

type HNSWConfig struct {
	// Quantization controls coordinate compression independently of graph quality.
	Quantization HNSWQuantizationConfig

	M                         int     // Max connections per node per layer (default: 16)
	EfConstruction            int     // Candidate list size during construction (default: 200)
	EfSearch                  int     // Candidate list size during search (default: 100)
	SearchBeamFactor          int     // Search beam multiplier relative to requested candidates (default: 4)
	LevelMultiplier           float64 // Level multiplier = 1/ln(M)
	UseGPUBuild               bool    // Attempt GPU-assisted construction when available
	GPUBuildBatchSize         int     // Number of vectors per GPU construction batch
	GPUBuildCandidateK        int     // Minimum GPU candidate depth (at least M and EfConstruction)
	GPUBuildDistancePrecision string  // Distance precision for GPU build kernels (currently fp32)
}

HNSWConfig contains configuration parameters for the HNSW index.

func DefaultHNSWConfig

func DefaultHNSWConfig() HNSWConfig

DefaultHNSWConfig returns sensible defaults for HNSW index.

func HNSWConfigFromEnv

func HNSWConfigFromEnv() HNSWConfig

HNSWConfigFromEnv loads HNSW configuration from environment variables.

Environment Variables:

  • NORNICDB_VECTOR_ANN_QUALITY: Quality preset (fast|balanced|accurate|compressed, default: fast)
  • NORNICDB_VECTOR_HNSW_M: Max connections per node (default: based on preset)
  • NORNICDB_VECTOR_HNSW_EF_CONSTRUCTION: Candidate list size during construction (default: based on preset)
  • NORNICDB_VECTOR_HNSW_EF_SEARCH: Candidate list size during search (default: based on preset)
  • NORNICDB_VECTOR_HNSW_BEAM_FACTOR: Search beam multiplier relative to requested candidates (default: 4)
  • NORNICDB_HNSW_BUILD_GPU_ENABLED: Attempt GPU-assisted construction (default: true)
  • NORNICDB_HNSW_BUILD_GPU_BATCH_SIZE: GPU build batch size (default: 2048)
  • NORNICDB_HNSW_BUILD_GPU_CANDIDATE_K: GPU candidate count per vector (default: 128)

Quality Presets:

  • fast: M=16, efConstruction=100, efSearch=50 (faster, lower recall)
  • balanced: M=16, efConstruction=200, efSearch=100 (good balance)
  • accurate: M=32, efConstruction=400, efSearch=200 (slower, higher recall)
  • compressed: parsed at ANN quality layer; maps to fast HNSW defaults until compressed ANN strategy routing is active

Example:

// Use fast preset
os.Setenv("NORNICDB_VECTOR_ANN_QUALITY", "fast")
config := HNSWConfigFromEnv()

// Override specific parameter
os.Setenv("NORNICDB_VECTOR_ANN_QUALITY", "balanced")
os.Setenv("NORNICDB_VECTOR_HNSW_EF_SEARCH", "150")
config := HNSWConfigFromEnv()

type HNSWGraphBuildAccelerator added in v1.1.7

type HNSWGraphBuildAccelerator interface {
	CandidateSearchGraph(ctx context.Context, queries [][]float32, graph *hnswBuildGraphSnapshot, topK int) (indices [][]uint32, distances [][]float32, err error)
}

type HNSWIndex

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

HNSWIndex provides fast approximate nearest neighbor search using HNSW algorithm.

func LoadHNSWIndex

func LoadHNSWIndex(path string, vectorLookup VectorLookup) (*HNSWIndex, error)

LoadHNSWIndex loads an HNSW index from path (msgpack format) and returns it. For the graph-only format, vectorLookup must be non-nil and vectors are resolved by ID at search time (no in-memory vector copy in HNSW). Older graph topologies are rejected so callers rebuild them. If the file does not exist or decode fails, returns (nil, nil) so the caller can rebuild. Returns an error only for unexpected I/O (e.g. permission denied).

func LoadIVFHNSWCluster

func LoadIVFHNSWCluster(hnswPath string, clusterID int, vectorLookup VectorLookup) (*HNSWIndex, error)

LoadIVFHNSWCluster loads one cluster's HNSW index of the persisted generation in lookup mode (no vector copy in HNSW RAM). Returns (nil, nil) if there is no generation, no file for the cluster, or it is invalid (caller can build). hnswPath is the full path to the single HNSW file.

func NewHNSWIndex

func NewHNSWIndex(dimensions int, config HNSWConfig) *HNSWIndex

NewHNSWIndex creates a new HNSW index with the given dimensions and config.

func (*HNSWIndex) Add

func (h *HNSWIndex) Add(id string, vec []float32) error

Add inserts a vector into the index.

func (*HNSWIndex) Clear

func (h *HNSWIndex) Clear()

Clear removes all vectors from the index and resets it to an empty state. This frees memory by clearing all internal arrays and maps. Use this when you need to completely reset the index (e.g., after deleting a collection).

func (*HNSWIndex) Config

func (h *HNSWIndex) Config() HNSWConfig

Config returns a copy of the index configuration.

func (*HNSWIndex) GetDimensions

func (h *HNSWIndex) GetDimensions() int

GetDimensions returns the vector dimension of the index.

func (*HNSWIndex) QuantizationBytes

func (h *HNSWIndex) QuantizationBytes() int

QuantizationBytes reports encoded coordinates, scales and codebooks only. It excludes graph metadata, original coordinates, storage caches and RSS.

func (*HNSWIndex) Remove

func (h *HNSWIndex) Remove(id string)

Remove removes a vector from the index by ID.

func (*HNSWIndex) Save

func (h *HNSWIndex) Save(path string) error

Save writes graph structure, IDs and any compressed model to path (msgpack). Original vectors remain in their canonical vector store and are resolved on load. Dir is created if needed. Copies index data under a short read lock so I/O does not block Search/Add/Remove.

func (*HNSWIndex) Search

func (h *HNSWIndex) Search(ctx context.Context, query []float32, k int, minSimilarity float64) ([]ANNResult, error)

Search finds the k nearest neighbors to the query vector.

func (*HNSWIndex) SearchWithEf

func (h *HNSWIndex) SearchWithEf(ctx context.Context, query []float32, k int, minSimilarity float64, ef int) ([]ANNResult, error)

SearchWithEf finds the k nearest neighbors using a caller-provided `ef`.

In Qdrant terms, `ef` is the beam size for HNSW search: larger values improve recall and usually increase latency. If `ef <= 0`, this falls back to the index's configured `EfSearch`.

func (*HNSWIndex) SearchWithEfFromEntries

func (h *HNSWIndex) SearchWithEfFromEntries(ctx context.Context, query []float32, k int, minSimilarity float64, ef int, entryIDs []string) ([]ANNResult, error)

SearchWithEfFromEntries searches with the normal hierarchical entry point plus known relevant vector IDs as additional layer-zero entry points. Missing and duplicate IDs are ignored. Hybrid retrieval uses this to enter semantic regions already identified by its lexical ranking without changing cosine scoring or final result ordering.

func (*HNSWIndex) SetBuildLexicalHints

func (h *HNSWIndex) SetBuildLexicalHints(hints []LexicalSeedHint)

SetBuildLexicalHints installs compact lexical metadata used to make deterministic diversity choices between vector-distance ties. The hints do not affect distance ordering. They remain compact enough to guide later live insertions and maintenance rebuilds without retaining BM25 postings here. Hint IDs are vector-entry keys; document hints are projected by the key owner.

func (*HNSWIndex) SetQuantization

func (h *HNSWIndex) SetQuantization(ctx context.Context, cfg HNSWQuantizationConfig) error

SetQuantization configures approximate graph scoring. Construction, including lexical ordering and diversity, continues to use original vectors. Use the vector search pipeline to rescore candidates and apply exact score thresholds. For example, scalar compression keeps one byte per coordinate plus a scale:

err := index.SetQuantization(ctx, HNSWQuantizationConfig{Mode: HNSWQuantizationScalar})

An empty Mode restores original-coordinate scoring. Mutations update codes under the same lock as graph/vector mutations. Changing mode rebuilds codes.

func (*HNSWIndex) SetVectorLookup

func (h *HNSWIndex) SetVectorLookup(lookup VectorLookup)

SetVectorLookup sets an optional lookup so vectors are resolved by ID at search time instead of from the in-memory slice. When set, Add does not store vectors (vecOff = -1); Load can leave vectors empty and use the lookup. Saves one full vector copy in RAM.

func (*HNSWIndex) ShouldRebuild

func (h *HNSWIndex) ShouldRebuild() bool

ShouldRebuild returns true if the index has accumulated too many tombstones and should be rebuilt to free memory. Threshold is 50% deleted vectors.

func (*HNSWIndex) Size

func (h *HNSWIndex) Size() int

Size returns the number of vectors in the index.

func (*HNSWIndex) SupportsGPUBuild added in v1.1.7

func (h *HNSWIndex) SupportsGPUBuild() bool

SupportsGPUBuild reports whether this index can be constructed through the GPU-assisted builder. The persisted index format is unchanged either way.

func (*HNSWIndex) TombstoneRatio

func (h *HNSWIndex) TombstoneRatio() float64

TombstoneRatio returns the ratio of deleted vectors to total vectors. Returns 0.0 if there are no vectors. A high ratio (>0.5) indicates the index should be rebuilt to free memory.

func (*HNSWIndex) Update

func (h *HNSWIndex) Update(id string, vec []float32) error

Update updates an existing vector in the index.

Update policy: Remove + Add pattern

  • Removes the old vector and all its connections
  • Adds the new vector with fresh connections
  • This ensures graph structure is correctly maintained

If the vector doesn't exist, this is equivalent to Add().

Performance: O(M * log(N)) where M is max connections, N is dataset size For high-churn workloads, consider periodic rebuilds to restore graph quality.

type HNSWQualityPreset

type HNSWQualityPreset string

HNSWQualityPreset defines quality presets for HNSW tuning.

const (
	// QualityFast prioritizes speed over recall.
	// Lower efSearch, lower candidate_multiplier for faster queries.
	QualityFast HNSWQualityPreset = "fast"

	// QualityBalanced provides a good balance between speed and recall.
	// Default preset with reasonable defaults.
	QualityBalanced HNSWQualityPreset = "balanced"

	// QualityAccurate prioritizes recall over speed.
	// Higher efSearch and/or bigger candidate pool for better accuracy.
	QualityAccurate HNSWQualityPreset = "accurate"
)

type HNSWQuantization

type HNSWQuantization string

HNSWQuantization selects the coordinate representation used for graph search. Original coordinates still own construction and exact rescoring.

const (
	// HNSWQuantizationNone uses original coordinates for traversal.
	HNSWQuantizationNone HNSWQuantization = ""
	// HNSWQuantizationScalar stores signed int8 coordinates and per-vector scales.
	HNSWQuantizationScalar HNSWQuantization = "scalar"
	// HNSWQuantizationProduct stores product codes against shared codebooks.
	HNSWQuantizationProduct HNSWQuantization = "pq"
	// HNSWQuantizationBinary stores one sign bit per coordinate.
	HNSWQuantizationBinary HNSWQuantization = "binary"
)

type HNSWQuantizationConfig

type HNSWQuantizationConfig struct {
	Mode               HNSWQuantization
	BinaryQueryBits    int // 1 (default), 4 or 8; stored binary coordinates remain one bit.
	PQCompression      int
	TrainingSampleMax  int
	TrainingIterations int
}

HNSWQuantizationConfig controls graph coordinate compression independently of the graph quality preset. PQCompression is the float32-to-code byte ratio: 16 means four dimensions per one-byte code. For example:

cfg := HNSWQuantizationConfig{Mode: HNSWQuantizationProduct, PQCompression: 16}
err := index.SetQuantization(ctx, cfg)

Scalar and binary use 8 and 1 bits per dimension respectively. Codebooks, scalar scales, graph links and retained originals are additional storage.

func HNSWQuantizationConfigFromEnv

func HNSWQuantizationConfigFromEnv() HNSWQuantizationConfig

HNSWQuantizationConfigFromEnv resolves coordinate compression (scalar int8 by default) without changing the fast/balanced/accurate graph preset or the legacy IVF-PQ mode.

NORNICDB_VECTOR_HNSW_QUANTIZATION selects none, scalar (default), pq or binary. NORNICDB_VECTOR_HNSW_BINARY_QUERY_BITS selects 1 (default), 4 or 8. NORNICDB_VECTOR_HNSW_PQ_COMPRESSION selects 4/8/16/32/64 (default 16). NORNICDB_VECTOR_HNSW_PQ_TRAINING_SAMPLE_MAX and _TRAINING_ITERATIONS control PQ training (defaults 10000 and 10). Invalid models fail activation rather than silently selecting an uncompressed benchmark path.

Example: NORNICDB_VECTOR_HNSW_QUANTIZATION=scalar keeps the chosen graph preset and uses int8 coordinates for candidate discovery, then exact reranking.

type HNSWResidentBuildAccelerator

type HNSWResidentBuildAccelerator interface {
	ResidentReady() bool
	// AppendInserted stores normalized vectors as the next internal IDs.
	AppendInserted(vecs [][]float32) error
	// CandidateSearchInserted returns each query's topK closest inserted
	// vectors by internal ID, closest first, with cosine distances.
	CandidateSearchInserted(ctx context.Context, queries [][]float32, topK int) (indices [][]uint32, distances [][]float32, err error)
}

HNSWResidentBuildAccelerator keeps every vector the build has inserted on the device, by internal ID, so a batch's level-0 candidates are its exact nearest inserted vectors from one scoring pass, with nothing re-uploaded. A graph search (HNSWGraphBuildAccelerator) uploads the vectors of each round's candidates instead, which dominates a large build. ResidentReady reports whether the device is prepared to retain inserted vectors; otherwise the build uses the accelerator's graph search.

type IVFHNSWCandidateGen

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

IVFHNSWCandidateGen implements IVF-HNSW: centroid routing (IVF) into per-cluster HNSW indexes.

This is designed for large CPU-only datasets:

  • K-means provides a coarse routing layer (choose nearest clusters)
  • Per-cluster HNSW provides fast ANN within each cluster

For GPU-enabled setups, prefer the existing GPU brute-force and GPU k-means paths.

func NewIVFHNSWCandidateGen

func NewIVFHNSWCandidateGen(clusterIndex *gpu.ClusterIndex, getClusterHNSW clusterHNSWLookup, numClustersToSearch int) *IVFHNSWCandidateGen

func (*IVFHNSWCandidateGen) SearchCandidates

func (g *IVFHNSWCandidateGen) SearchCandidates(ctx context.Context, query []float32, k int, minSimilarity float64) ([]Candidate, error)

func (*IVFHNSWCandidateGen) SetClusterSelector

func (g *IVFHNSWCandidateGen) SetClusterSelector(fn func(ctx context.Context, query []float32, defaultN int) []int) *IVFHNSWCandidateGen

SetClusterSelector sets an optional custom cluster selector used for routing.

func (*IVFHNSWCandidateGen) SetServing

func (g *IVFHNSWCandidateGen) SetServing(lock sync.Locker, view func(context.Context) (context.Context, clusterView, func())) *IVFHNSWCandidateGen

SetServing makes the generator serve each query from the cluster generation the query holds (see clusterServing); the selector is then called with lock held and must not lock it.

type IVFPQBuildStats

type IVFPQBuildStats struct {
	VectorCount         int
	TrainingSampleCount int
	ListCount           int
	AvgListSize         float64
	MaxListSize         int
	BytesPerVector      float64
	BuildDuration       time.Duration
}

IVFPQBuildStats captures build observability for acceptance gates.

type IVFPQCandidateGen

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

IVFPQCandidateGen implements CandidateGenerator using IVF/PQ compressed ANN.

func NewIVFPQCandidateGen

func NewIVFPQCandidateGen(index *IVFPQIndex, nprobe int) *IVFPQCandidateGen

func NewIVFPQCandidateGenWithOverlay

func NewIVFPQCandidateGenWithOverlay(index *IVFPQIndex, nprobe int, overlay *annMutationOverlay) *IVFPQCandidateGen

NewIVFPQCandidateGenWithOverlay creates a compressed candidate generator that merges live mutations with the immutable IVF/PQ base index.

func (*IVFPQCandidateGen) SearchCandidates

func (g *IVFPQCandidateGen) SearchCandidates(ctx context.Context, query []float32, k int, minSimilarity float64) ([]Candidate, error)

type IVFPQIndex

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

IVFPQIndex stores a compressed IVF/PQ ANN structure.

func LoadIVFPQBundle

func LoadIVFPQBundle(basePath string) (*IVFPQIndex, error)

LoadIVFPQBundle loads an IVFPQ multipart snapshot bundle.

func (*IVFPQIndex) Count

func (i *IVFPQIndex) Count() int

func (*IVFPQIndex) Profile

func (i *IVFPQIndex) Profile() IVFPQProfile

func (*IVFPQIndex) SearchApprox

func (i *IVFPQIndex) SearchApprox(ctx context.Context, query []float32, k int, minSimilarity float64, nprobe int) ([]Candidate, error)

SearchApprox searches compressed IVF/PQ lists and returns approximate candidates.

type IVFPQProfile

type IVFPQProfile struct {
	Dimensions          int
	IVFLists            int
	PQSegments          int
	PQBits              int
	NProbe              int
	RerankTopK          int
	TrainingSampleMax   int
	KMeansMaxIterations int
	OverflowMax         int
}

IVFPQProfile is the concrete runtime profile used to build/query compressed ANN.

type IdentityExactScorer

type IdentityExactScorer struct{}

IdentityExactScorer is used when the candidate generator already returns exact scores.

func (*IdentityExactScorer) ScoreCandidates

func (i *IdentityExactScorer) ScoreCandidates(ctx context.Context, query []float32, candidates []Candidate) ([]ScoredCandidate, error)

type KMeansCandidateGen

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

KMeansCandidateGen implements CandidateGenerator using k-means cluster routing.

This candidate generator:

  1. Finds the top numClustersToSearch clusters nearest to the query
  2. Gets all node IDs from those clusters as candidates
  3. Returns candidates with approximate scores (centroid similarity)

This is optimal for very large datasets (N > 100K) where cluster routing provides significant speedup. For smaller datasets, HNSW or brute-force may be faster.

func NewKMeansCandidateGen

func NewKMeansCandidateGen(clusterIndex *gpu.ClusterIndex, vectorIndex *VectorIndex, numClustersToSearch int) *KMeansCandidateGen

NewKMeansCandidateGen creates a new k-means candidate generator.

Parameters:

  • clusterIndex: The GPU ClusterIndex (must be clustered)
  • vectorIndex: The VectorIndex for ID mapping and fallback
  • numClustersToSearch: Number of clusters to search (default: 3)

func (*KMeansCandidateGen) SearchCandidates

func (k *KMeansCandidateGen) SearchCandidates(ctx context.Context, query []float32, limit int, minSimilarity float64) ([]Candidate, error)

SearchCandidates generates candidates using k-means cluster routing.

Algorithm:

  1. Find top numClustersToSearch clusters nearest to query (centroid similarity)
  2. Get all node IDs from those clusters
  3. Return candidates with approximate scores (centroid similarity)

If clustering is not available or not clustered, falls back to brute-force.

func (*KMeansCandidateGen) SetClusterSelector

func (k *KMeansCandidateGen) SetClusterSelector(fn func(ctx context.Context, query []float32, defaultN int) []int) *KMeansCandidateGen

SetClusterSelector sets an optional custom cluster selector used for routing. When nil, the generator uses the default nearest-centroid routing.

func (*KMeansCandidateGen) SetServing

func (k *KMeansCandidateGen) SetServing(lock sync.Locker, view func(context.Context) (context.Context, clusterView, func())) *KMeansCandidateGen

SetServing makes the generator serve each query from the cluster generation the query holds (see clusterServing); the selector is then called with lock held.

type KalmanSearchAdapter

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

KalmanSearchAdapter wraps a search Service with Kalman filtering.

func NewKalmanSearchAdapter

func NewKalmanSearchAdapter(service *Service, config KalmanSearchConfig) *KalmanSearchAdapter

NewKalmanSearchAdapter creates a new Kalman-enhanced search adapter.

Example:

service := search.NewService(engine, 1024)
adapter := search.NewKalmanSearchAdapter(service, search.DefaultKalmanSearchConfig())

// Search with enhanced ranking
results, _ := adapter.Search(ctx, "semantic search", embedding, &SearchOptions{Limit: 10})

func (*KalmanSearchAdapter) GetDocumentRelevanceTrend

func (ka *KalmanSearchAdapter) GetDocumentRelevanceTrend(docID string) float64

GetDocumentRelevanceTrend returns whether a document is becoming more or less relevant.

Returns:

  • positive velocity: document is becoming more relevant (appearing higher)
  • negative velocity: document is becoming less relevant (appearing lower)
  • zero: stable relevance

func (*KalmanSearchAdapter) GetFallingDocuments

func (ka *KalmanSearchAdapter) GetFallingDocuments(maxVelocity float64) []string

GetFallingDocuments returns documents whose relevance is decreasing.

func (*KalmanSearchAdapter) GetLatencyTrend

func (ka *KalmanSearchAdapter) GetLatencyTrend() float64

GetLatencyTrend returns the current latency velocity (positive = getting slower).

func (*KalmanSearchAdapter) GetPredictedLatency

func (ka *KalmanSearchAdapter) GetPredictedLatency(stepsAhead int) float64

GetPredictedLatency returns the predicted latency for the next query.

func (*KalmanSearchAdapter) GetRisingDocuments

func (ka *KalmanSearchAdapter) GetRisingDocuments(minVelocity float64) []string

GetRisingDocuments returns documents whose relevance is increasing.

func (*KalmanSearchAdapter) GetService

func (ka *KalmanSearchAdapter) GetService() *Service

GetService returns the underlying search service.

func (*KalmanSearchAdapter) GetStats

func (ka *KalmanSearchAdapter) GetStats() SearchAdapterStats

GetStats returns adapter statistics.

func (*KalmanSearchAdapter) Reset

func (ka *KalmanSearchAdapter) Reset()

Reset clears all cached data and filters.

func (*KalmanSearchAdapter) Search

func (ka *KalmanSearchAdapter) Search(ctx context.Context, query string, embedding []float32, opts *SearchOptions) (*SearchResponse, error)

Search performs a Kalman-enhanced search.

The enhancement pipeline:

  1. Execute underlying search
  2. Smooth similarity scores with Kalman filter
  3. Apply ranking stability boost
  4. Track latency for prediction
  5. Return enhanced results

type KalmanSearchConfig

type KalmanSearchConfig struct {
	// EnableScoreSmoothing enables Kalman filtering of similarity scores
	EnableScoreSmoothing bool

	// EnableRankingStability applies stability boost to consistent results
	EnableRankingStability bool

	// EnableLatencyPrediction tracks and predicts query latency
	EnableLatencyPrediction bool

	// SimilarityConfig for score smoothing
	SimilarityConfig filter.Config

	// LatencyConfig for latency prediction
	LatencyConfig filter.Config

	// StabilityBoost is the boost factor for consistently-ranked documents
	StabilityBoost float64

	// StabilityWindow is how many recent queries to consider for stability
	StabilityWindow int

	// ScoreHistoryLimit is max history per document
	ScoreHistoryLimit int
}

KalmanSearchConfig holds configuration for the Kalman-enhanced search adapter.

func DefaultKalmanSearchConfig

func DefaultKalmanSearchConfig() KalmanSearchConfig

DefaultKalmanSearchConfig returns sensible defaults.

type LLMFunc

type LLMFunc func(ctx context.Context, prompt string) (string, error)

LLMFunc is a minimal, dependency-free function signature for calling an LLM. It is intentionally generic so the search package does not depend on Heimdall.

Implementations should be safe for concurrent use.

type LLMReranker

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

LLMReranker performs Stage-2 reranking using an LLM (e.g., Heimdall).

The model is prompted to output JSON ranking information using candidate indices (not IDs) to keep responses short and parsing robust.

func NewLLMReranker

func NewLLMReranker(cfg *LLMRerankerConfig, llm LLMFunc) *LLMReranker

NewLLMReranker creates a new LLM reranker.

func (*LLMReranker) Enabled

func (r *LLMReranker) Enabled() bool

func (*LLMReranker) IsAvailable

func (r *LLMReranker) IsAvailable(ctx context.Context) bool

func (*LLMReranker) Name

func (r *LLMReranker) Name() string

func (*LLMReranker) Rerank

func (r *LLMReranker) Rerank(ctx context.Context, query string, candidates []RerankCandidate) ([]RerankResult, error)

Rerank takes a query and candidates, returns reranked results.

An LLM call error is an error (see Reranker). Parsed output is preserved in full for search.Service to validate before applying MinScore filtering.

type LLMRerankerConfig

type LLMRerankerConfig struct {
	Enabled bool

	// Timeout bounds how long a single LLM rerank call can take.
	Timeout time.Duration

	// MaxCandidates caps how many candidates are included in one prompt.
	// This protects against long prompts on large candidate sets.
	MaxCandidates int

	// MaxDocChars truncates each candidate's text content to this many characters.
	MaxDocChars int

	// MaxQueryChars truncates the query string included in the prompt.
	MaxQueryChars int

	// MinScore filters candidates whose LLM score is below this value.
	// A value of 0 means "no filtering".
	MinScore float64
}

LLMRerankerConfig controls LLM-based reranking behavior.

A failed LLM call is reported as an error. search.Service validates the complete parsed result set and owns fallback reporting.

func DefaultLLMRerankerConfig

func DefaultLLMRerankerConfig() *LLMRerankerConfig

DefaultLLMRerankerConfig returns conservative defaults intended for small local models.

type LexicalSeedHint

type LexicalSeedHint struct {
	ID        string
	Rank      uint32
	Signature uint64
}

LexicalSeedHint is compact build metadata derived directly from the BM25 inverted index. Rank preserves high-IDF selection order, while Signature is a weighted SimHash used only to break equal vector-distance choices.

type LocalReranker

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

LocalReranker performs Stage-2 reranking using a local GGUF reranker model.

func NewLocalReranker

func NewLocalReranker(scorer RerankScorer, cfg *LocalRerankerConfig, admit func(context.Context) (context.Context, func(), error)) *LocalReranker

NewLocalReranker creates a reranker that uses the given scorer (e.g. *localllm.RerankerModel). admit is the scorer owner's admission and is required: there is no untracked mode.

func (*LocalReranker) Enabled

func (r *LocalReranker) Enabled() bool

func (*LocalReranker) IsAvailable

func (r *LocalReranker) IsAvailable(ctx context.Context) bool

func (*LocalReranker) Name

func (r *LocalReranker) Name() string

func (*LocalReranker) Rerank

func (r *LocalReranker) Rerank(ctx context.Context, query string, candidates []RerankCandidate) ([]RerankResult, error)

Rerank scores each candidate with the scorer and returns results sorted by score (desc). A scorer error is an error (see Reranker). The raw scored batch, including entries below MinScore, is retained for Service validation. The caller must supply a non-nil context.

func (*LocalReranker) UnderlyingScorer

func (r *LocalReranker) UnderlyingScorer() RerankScorer

UnderlyingScorer identifies the resource adopted by the DB's provider owner.

type LocalRerankerConfig

type LocalRerankerConfig struct {
	Enabled bool

	Timeout time.Duration

	// MaxCandidates caps how many candidates are scored per query.
	MaxCandidates int

	// MaxDocChars truncates each candidate's content before scoring.
	MaxDocChars int

	// MinScore filters out candidates below this score (0 = no filter).
	MinScore float64
}

LocalRerankerConfig configures local GGUF reranker behavior.

func DefaultLocalRerankerConfig

func DefaultLocalRerankerConfig() *LocalRerankerConfig

DefaultLocalRerankerConfig returns sensible defaults for BGE-style reranking.

type MetalHNSWBuildAccelerator added in v1.1.7

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

MetalHNSWBuildAccelerator uses the existing Metal cosine/top-k kernels for construction candidate search.

func NewMetalHNSWBuildAccelerator added in v1.1.7

func NewMetalHNSWBuildAccelerator() (*MetalHNSWBuildAccelerator, error)

NewMetalHNSWBuildAccelerator creates a Metal-backed HNSW build accelerator.

func (*MetalHNSWBuildAccelerator) AppendInserted

func (a *MetalHNSWBuildAccelerator) AppendInserted(vecs [][]float32) error

AppendInserted copies vecs (normalized) into the resident buffer after the vectors already there, doubling the buffer when the build outgrows maxNodes.

func (*MetalHNSWBuildAccelerator) CandidateSearch added in v1.1.7

func (a *MetalHNSWBuildAccelerator) CandidateSearch(ctx context.Context, queries [][]float32, frontier [][]float32, topK int) ([][]int, [][]float32, error)

func (*MetalHNSWBuildAccelerator) CandidateSearchGraph added in v1.1.7

func (a *MetalHNSWBuildAccelerator) CandidateSearchGraph(ctx context.Context, queries [][]float32, graph *hnswBuildGraphSnapshot, topK int) ([][]uint32, [][]float32, error)

func (*MetalHNSWBuildAccelerator) CandidateSearchInserted

func (a *MetalHNSWBuildAccelerator) CandidateSearchInserted(ctx context.Context, queries [][]float32, topK int) ([][]uint32, [][]float32, error)

CandidateSearchInserted scores the queries against every resident vector (scoreTopK) and keeps each query's topK, at most 256.

func (*MetalHNSWBuildAccelerator) Close added in v1.1.7

func (a *MetalHNSWBuildAccelerator) Close() error

func (*MetalHNSWBuildAccelerator) Prepare added in v1.1.7

func (a *MetalHNSWBuildAccelerator) Prepare(dim int, maxNodes int) error

Prepare sets the dimension and reserves the resident buffer for maxNodes vectors. Without the room, the build uses the graph search.

func (*MetalHNSWBuildAccelerator) ResidentReady

func (a *MetalHNSWBuildAccelerator) ResidentReady() bool

type NodeAuthorizationFunc added in v1.3.3

type NodeAuthorizationFunc func(*storage.Node) (bool, error)

NodeAuthorizationFunc decides whether the current caller may read a node. Adapters supply this trusted predicate; it is never accepted from the wire.

type NodeDecayFilterFunc added in v1.1.0

type NodeDecayFilterFunc func(nodeID string) bool

NodeDecayFilterFunc returns true if the given node ID should be suppressed (filtered out) due to knowledge-layer decay scoring. When nil, no decay filtering is applied to search results.

type NodeIterator

type NodeIterator interface {
	IterateNodes(fn func(*storage.Node) bool) error
}

NodeIterator is an interface for streaming node iteration.

type NodeMutation

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

NodeMutation is an opaque reservation for a node's next index mutation. Keep the reservation with deferred work, including work already drained from a queue. It belongs only to the service that issued it.

type RefreshRequest

type RefreshRequest struct {
	Node storage.NodeID
	Edge storage.EdgeID
	// PostCommit reports that the change is committed and the scope's own
	// writes are no longer what search must read. A scope that defers
	// refreshes while a transaction is open uses it to refresh now instead of
	// deferring again.
	PostCommit bool
	// PostCommitService is the service captured for a transaction's publish.
	// It belongs to this request, not to a long-lived consumer. A nil value is
	// meaningful when no service existed at the start of the publish.
	PostCommitService *Service
}

RefreshRequest is one post-mutation search refresh: the node and/or relationship the caller changed, and whether that change is already visible to the reader serving the refresh.

type RefreshRetry

type RefreshRetry struct {
	Node NodeMutation
	Edge EdgeMutation
}

RefreshRetry is ownership of a node or relationship refresh whose read failed. Its owner must dispatch the same reservation or discard it.

func (RefreshRetry) Current

func (r RefreshRetry) Current() bool

func (RefreshRetry) Discard

func (r RefreshRetry) Discard()

func (RefreshRetry) Key

func (r RefreshRetry) Key() string

func (RefreshRetry) NewerThan

func (r RefreshRetry) NewerThan(other RefreshRetry) bool

NewerThan compares reservations issued for the same entity by one service.

func (RefreshRetry) Retired

func (r RefreshRetry) Retired() bool

Retired distinguishes completed or discarded work from a live predecessor temporarily superseded by a newer reservation.

type RefreshRetryFunc

type RefreshRetryFunc func(nodeID storage.NodeID, edgeID storage.EdgeID, err error)

RefreshRetryFunc is the original notification callback. The reservation is discarded before notification; consumers needing retry ownership use SetRefreshRetryOwner.

type RefreshRetryOwner

type RefreshRetryOwner func(work RefreshRetry, err error)

RefreshRetryOwner takes ownership of the failed reservation, including failures from synchronous consumers and the deferred event drain.

type RefreshScope

type RefreshScope interface {
	// PrepareSearchRefresh returns the service to refresh, or deferred=true
	// when the scope has retained the request for later. A nil service with no
	// error means there is no work to apply. A prepare error is returned.
	PrepareSearchRefresh(ctx context.Context, request RefreshRequest) (svc *Service, deferred bool, err error)
}

RefreshScope decides how a refresh request reaches the service that owns the indexes. It prepares the request once; the operation refreshes what the scope hands back.

type RelationshipEmbedFunc

type RelationshipEmbedFunc func(ctx context.Context, edge *storage.Edge) (RelationshipEmbedding, error)

RelationshipEmbedFunc embeds a relationship's text, one vector per chunk. It returns no vectors for a relationship with no text to embed, and an error when it can't embed now; the relationship is then tried again later.

type RelationshipEmbedding

type RelationshipEmbedding struct {
	Vectors [][]float32
	Spans   []embeddingutil.ChunkSpan
}

RelationshipEmbedding is a relationship's chunk vectors and where each chunk lies in its string properties, as a node's embedding records them.

type RelationshipVectorQueryHit added in v1.1.7

type RelationshipVectorQueryHit struct {
	ID    string
	Score float64
}

RelationshipVectorQueryHit is a lightweight result row for relationship vector queries. ID is the relationship ID.

type RelationshipVectorQuerySpec added in v1.1.7

type RelationshipVectorQuerySpec struct {
	// IndexName is informational only (used for debugging/observability).
	IndexName string

	// Type optionally filters candidate relationships by relationship type.
	Type string

	// Property is the relationship vector property name.
	Property string

	// Similarity is the similarity function name. Supported values:
	// "cosine" (default), "dot", "euclidean".
	Similarity string

	// Limit is the maximum number of results to return.
	Limit int
}

RelationshipVectorQuerySpec describes a Cypher-style relationship vector query.

type RerankCandidate

type RerankCandidate = voyage.Candidate

RerankCandidate represents a document to be reranked.

type RerankResult

type RerankResult = voyage.RankedCandidate

RerankResult is a reranked document with new score.

type RerankScorer

type RerankScorer interface {
	Score(ctx context.Context, query, document string) (float32, error)
}

RerankScorer scores a (query, document) pair for relevance. Implementations are typically *localllm.RerankerModel (loaded from GGUF).

type Reranker

type Reranker interface {
	// Name identifies the reranker implementation for observability.
	// Examples: "cross_encoder", "heimdall_llm".
	Name() string

	// Enabled indicates whether reranking is configured/enabled.
	Enabled() bool

	// IsAvailable is an optional health check. Implementations should keep this
	// cheap; Search() should not call it on the hot path.
	IsAvailable(ctx context.Context) bool

	// Rerank returns the raw provider-selected candidate indices in provider
	// order. A unique in-range subset is valid. Implementations preserve every
	// returned entry; search.Service alone validates it and completes a valid
	// subset with omitted candidates in their original order.
	Rerank(ctx context.Context, query string, candidates []RerankCandidate) ([]RerankResult, error)
}

Reranker is a Stage-2 reranking component.

When reranking cannot be performed (service unavailable, unusable response, timeout), Rerank returns an error instead of a pass-through ranking. The Service owns the fail-open: a search keeps its fused order and reports the fallback (SearchFallbackRerankFailed), and RerankCandidates returns that canonical failure through its existing error result. A disabled reranker passes candidates through unchanged.

type ScoredCandidate

type ScoredCandidate struct {
	ID    string
	Score float64 // Exact score from exact scorer
}

ScoredCandidate represents a candidate with exact score.

type SearchAdapterStats

type SearchAdapterStats struct {
	TotalQueries       int64
	ScoresSmoothed     int64
	StabilityApplied   int64
	LatencyPredictions int64
	AverageLatencyMs   float64
	PredictedLatencyMs float64
}

SearchAdapterStats holds adapter statistics.

type SearchCandidate

type SearchCandidate struct {
	ID    string
	Score float64
}

SearchCandidate is a lightweight vector-search result: just the ID and score.

This is intended for high-throughput call paths that don’t require node enrichment (e.g. Qdrant-compatible gRPC searches that return IDs+scores).

type SearchContinuationMode added in v1.3.3

type SearchContinuationMode string

type SearchContinuationPage added in v1.3.3

type SearchContinuationPage struct {
	// MaxPageSize is the effective registry limit, advertised on page responses.
	MaxPageSize int

	Results             []SearchResult
	QID                 string
	HasMore             bool
	Position            uint64
	Returned            int
	Discovered          int
	Total               *uint64
	ExpiresAt           time.Time
	Released            bool
	SearchMethod        string
	FallbackTriggered   bool
	FallbackReason      SearchFallbackReason
	Mode                SearchContinuationMode
	RankedCount         int
	EligibleCount       *int
	RankedPoolExhausted bool
	CollectionExhausted bool
	Completion          string
	// QueryChunksSearched / QueryChunksTotal are SearchResponse's.
	QueryChunksSearched int
	QueryChunksTotal    int
	// contains filtered or unexported fields
}

SearchContinuationPage is the protocol-neutral continued-search response.

func (*SearchContinuationPage) SearchResponse added in v1.3.3

func (p *SearchContinuationPage) SearchResponse() *SearchResponse

SearchResponse restores the canonical search response with this page's rows.

type SearchContinuationRequest added in v1.3.3

type SearchContinuationRequest struct {
	Owner         string
	Database      string
	QID           string
	N             int
	Discard       bool
	MaxResults    int
	Mode          SearchContinuationMode
	GroupBy       string
	RankedLimit   int
	AuthorizeNode NodeAuthorizationFunc
}

SearchContinuationRequest controls one start, pull, or discard operation. Limit belongs to SearchOptions and is only the initial retrieval depth.

type SearchFallbackReason

type SearchFallbackReason string

SearchFallbackReason is a stable, sanitized explanation of why the selected search path differed from the requested hybrid path.

const (
	SearchFallbackNone                      SearchFallbackReason = ""
	SearchFallbackQueryEmbeddingFailed      SearchFallbackReason = "query_embedding_failed"
	SearchFallbackQueryEmbeddingUnavailable SearchFallbackReason = "query_embedding_unavailable"
	SearchFallbackNoEmbedder                SearchFallbackReason = "no_embedder"
	SearchFallbackNoHybridResults           SearchFallbackReason = "no_hybrid_results"
	SearchFallbackHybridSearchFailed        SearchFallbackReason = "hybrid_search_failed"
	// The requested Stage-2 rerank didn't order the results, which keep
	// their fused order: the reranker failed, gave every candidate nearly
	// the same score, or had no candidate content to score.
	SearchFallbackRerankFailed       SearchFallbackReason = "rerank_failed"
	SearchFallbackRerankScoresFlat   SearchFallbackReason = "rerank_scores_flat"
	SearchFallbackRerankNoCandidates SearchFallbackReason = "rerank_no_candidates"
	// A long query had more chunks than are searched
	// (NORNICDB_SEARCH_QUERY_MAX_CHUNKS): the results are for its first
	// QueryChunksSearched chunks.
	SearchFallbackQueryChunksDropped SearchFallbackReason = "query_chunks_dropped"
)
const SearchFallbackMinRRFScore SearchFallbackReason = "min_rrf_score"

SearchFallbackMinRRFScore: fused results scoring below MinRRFScore were dropped and fewer than the limit remain. A result found by one ranking only scores weight / (RRFK + rank), so with the defaults that ranking's results past rank 40 score under 0.01 (#1092); MinRRFScore 0 keeps them.

type SearchMatch

type SearchMatch struct {
	Kind     string  `json:"kind"`
	Chunk    int     `json:"chunk"`
	Score    float64 `json:"score,omitempty"`
	Term     string  `json:"term,omitempty"`
	Property string  `json:"property,omitempty"`
	Start    int     `json:"start"`
	End      int     `json:"end"`
}

SearchMatch is what made a hit match, and where it lies in the hit's string properties (#1060). A SearchResult lists its matched chunks first, best first, then its term occurrences.

  • Kind "chunk": one of the hit's embedding chunks matched the query vector. Chunk is its index and Score its similarity to the query. A chunk that runs across two properties is one match per property.
  • Kind "term": one occurrence of a query term matched the keyword query. Term is the term as the BM25 analyzer reads it.

[Start, End) counts Unicode code points of the Property value, as Cypher's substring() does. Property is "" for a chunk whose place in the properties is unknown (an embedding made before chunk places were recorded, whose chunk texts weren't kept).

func (SearchMatch) Value

func (m SearchMatch) Value() map[string]any

Value is the match as clients read it, in Cypher and over HTTP: kind; chunk and score, or term; property, start and end, which are null for a chunk whose place in the properties is unknown.

type SearchMetrics

type SearchMetrics struct {
	VectorSearchTimeMs     int `json:"vector_search_time_ms"`
	BM25SearchTimeMs       int `json:"bm25_search_time_ms"`
	FusionTimeMs           int `json:"fusion_time_ms"`
	TotalTimeMs            int `json:"total_time_ms"`
	VectorCandidates       int `json:"vector_candidates"`
	VectorRawCandidates    int `json:"vector_raw_candidates"`
	VectorOverfetchRetries int `json:"vector_overfetch_retries"`
	BM25Candidates         int `json:"bm25_candidates"`
	BM25RawCandidates      int `json:"bm25_raw_candidates"`
	BM25OverfetchRetries   int `json:"bm25_overfetch_retries"`
	FusedCandidates        int `json:"fused_candidates"`
}

SearchMetrics contains timing and statistics.

type SearchOptions

type SearchOptions struct {

	// Limit is the maximum number of results to return
	Limit int

	// MinSimilarity is the minimum similarity threshold for vector search.
	// nil = use service default, otherwise use the provided value.
	MinSimilarity *float64

	// Types filters results by node type (labels)
	Types []string

	// RRF configuration
	RRFK         float64 // RRF constant (default: 60)
	VectorWeight float64 // Weight for vector results (default: 1.0)
	BM25Weight   float64 // Weight for BM25 results (default: 1.0)
	MinRRFScore  float64 // Minimum RRF score threshold (default: 0.01)
	// FallbackEnabled controls vector/full-text fallback after an empty hybrid result.
	// nil preserves the legacy default of enabled.
	FallbackEnabled *bool

	// Adaptive candidate retrieval. CandidateTarget is the unique-node depth
	// requested from each retrieval branch; 0 derives max(Limit*2, 20).
	AdaptiveOverfetch     bool
	CandidateTarget       int
	InitialOverfetchRatio float64
	MaxOverfetchRatio     float64
	OverfetchGrowthFactor float64
	MaxCandidateLimit     int

	// SkipMatches leaves each result's Matches empty, for a caller that
	// doesn't read them (#1060): no hit's chunks are scored, no text scanned.
	SkipMatches bool

	// HNSWEf is this search's HNSW beam width (ef), as Qdrant's per-request
	// hnsw_ef: 0 uses the configured preset (NORNICDB_VECTOR_HNSW_EF_SEARCH and
	// the beam factor). Only HNSW-based strategies read it (global HNSW and the
	// per-cluster graphs of IVF-HNSW); IVF-PQ, k-means routing and brute force
	// don't search a graph and ignore it.
	HNSWEf int

	// QuantizationIgnore searches original coordinates. QuantizationRescore
	// defaults to true; false returns approximate scores for quantized HNSW.
	// QuantizationOversampling expands the exact-reranking candidate pool
	// (0 defaults to 1; explicit values must be finite and at least 1).
	QuantizationIgnore       bool
	QuantizationRescore      *bool
	QuantizationOversampling float64

	// Where admits a candidate node, as a Cypher WHERE on it does: a missing
	// property, a negation or a pattern from the node; nil admits every node. It
	// is applied with Types and Filters to the candidates, before the top-K cut.
	// A search with a Where isn't cached: what it admits can depend on more than
	// the options. Each Search invocation evaluates a candidate once across
	// retrieval branches and widening rounds; subsequent requests reevaluate.
	//
	// ctx is the search that asks: for a continuation page, that page's
	// request, not the one that started the search, so cancelling the page
	// stops the filter. An error admits nothing and ends the search with it:
	// a candidate the filter could not decide is never returned.
	Where func(ctx context.Context, node *storage.Node) (bool, error)

	// RelationshipWhere admits a candidate relationship of a relationship or
	// graph search, given its start and end nodes (nil when not visible), as
	// Where does a node; nil admits every relationship. It is applied with
	// the relationship types, before the limit.
	RelationshipWhere func(ctx context.Context, edge *storage.Edge, start, end *storage.Node) (bool, error)

	// MMR (Maximal Marginal Relevance) diversification
	// When enabled, results are re-ranked to balance relevance with diversity
	MMREnabled bool    // Enable MMR diversification (default: false)
	MMRLambda  float64 // Balance: 1.0 = pure relevance, 0.0 = pure diversity (default: 0.7)

	// Cross-encoder reranking (Stage 2)
	// When enabled, top candidates are re-scored using a cross-encoder model
	// for higher accuracy at the cost of latency
	RerankEnabled  bool    // Enable cross-encoder reranking (default: false)
	RerankTopK     int     // How many candidates to rerank (default: 100)
	RerankMinScore float64 // Minimum rerank score to include; search fallbacks without rerank output are unfiltered (default: 0)
	// RerankMaxChars bounds the content sent for each candidate, in characters. Zero uses
	// NORNICDB_SEARCH_RERANK_MAX_DOCUMENT_CHARS or the 2048-character default.
	RerankMaxChars int

	// Filters pre-filters nodes by property values before top-K selection.
	// Keys are property names; values are acceptable values (OR within a key, AND across keys).
	// Scalar and array property values are both supported. A key with an
	// empty list matches no node, as Cypher's IN [] (nodeMatchesFilters);
	// leave a key out to not constrain it.
	Filters map[string][]string

	// IncludeProperties limits each returned result's Properties map to these
	// keys. Empty includes every property unless excluded below.
	IncludeProperties []string
	// ExcludeProperties removes keys from each returned result's Properties
	// map. Exclusion wins when a key appears in both lists.
	ExcludeProperties []string

	// Relationships searches relationships instead of nodes, when the
	// database indexes them (#1065); Types then filters by relationship type.
	Relationships bool

	// Graph ranks nodes and relationships in one pool (searchGraph): Types
	// filters the nodes by label, RelationshipTypes the relationships by type.
	Graph             bool
	RelationshipTypes []string
	// contains filtered or unexported fields
}

SearchOptions configures the search behavior.

func DefaultSearchOptions

func DefaultSearchOptions() *SearchOptions

DefaultSearchOptions returns sensible defaults.

func GetAdaptiveRRFConfig

func GetAdaptiveRRFConfig(query string) *SearchOptions

GetAdaptiveRRFConfig returns the production RRF configuration for a query.

Equal lexical and vector weights are the recall-oriented default. The former word-count heuristic over-emphasized vectors for long queries, which reduced recall in controlled hybrid retrieval evaluation. The query argument remains part of the API for future policies that are validated across benchmarks.

func (*SearchOptions) GetMinSimilarity

func (o *SearchOptions) GetMinSimilarity(fallback float64) float64

GetMinSimilarity returns the MinSimilarity value, or the fallback if nil.

type SearchPassage added in v1.3.3

type SearchPassage = SearchResult

SearchPassage is one matching child retained within a grouped search result.

type SearchQueryFunc added in v1.3.3

type SearchQueryFunc func(ctx context.Context, query string, embedding []float32, opts *SearchOptions) (*SearchResponse, error)

SearchQueryFunc searches one query and optional vector.

type SearchResponse

type SearchResponse struct {
	// RetrievalExhausted is internal continuation evidence: every participating
	// retrieval branch is exhausted and no candidate prefix was truncated.
	// A short filtered or approximate result alone must never set this flag.
	RetrievalExhausted bool `json:"-"`
	// CandidateBudgetReached is internal continuation evidence: the selected
	// producer hit a configured candidate budget and cannot expose a deeper
	// ranked prefix without changing that budget.
	CandidateBudgetReached bool                 `json:"-"`
	Status                 string               `json:"status"`
	Query                  string               `json:"query"`
	Results                []SearchResult       `json:"results"`
	TotalCandidates        int                  `json:"total_candidates"`
	Returned               int                  `json:"returned"`
	SearchMethod           string               `json:"search_method"`
	FallbackTriggered      bool                 `json:"fallback_triggered"`
	FallbackReason         SearchFallbackReason `json:"fallback_reason,omitempty"`
	Message                string               `json:"message,omitempty"`
	Metrics                *SearchMetrics       `json:"metrics,omitempty"`
	// QueryChunksSearched / QueryChunksTotal: of a query split into several
	// chunks, how many were searched of how many. Zero for a one-chunk query.
	QueryChunksSearched int `json:"query_chunks_searched,omitempty"`
	QueryChunksTotal    int `json:"query_chunks_total,omitempty"`
	// contains filtered or unexported fields
}

SearchResponse is the response from a search operation.

func SearchTextChunks added in v1.3.3

func SearchTextChunks(
	ctx context.Context,
	query string,
	opts *SearchOptions,
	chunkQuery ChunkQueryFunc,
	embedQuery EmbedQueryFunc,
	searchQuery SearchQueryFunc,
) (*SearchResponse, error)

SearchTextChunks applies the canonical text-search semantics used by all transports. Multi-chunk queries are searched independently and fused with an outer RRF pass.

func SearchTextChunksWithErrorPolicy added in v1.3.3

func SearchTextChunksWithErrorPolicy(
	ctx context.Context,
	query string,
	opts *SearchOptions,
	chunkQuery ChunkQueryFunc,
	embedQuery EmbedQueryFunc,
	searchQuery SearchQueryFunc,
	errorPolicy ChunkedSearchErrorPolicy,
) (response *SearchResponse, retErr error)

SearchTextChunksWithErrorPolicy applies SearchTextChunks while allowing an adapter to designate errors that must be returned instead of triggering BM25 fallback.

func (*SearchResponse) ResponseHeaders

func (r *SearchResponse) ResponseHeaders() map[string]string

ResponseHeaders exposes the sanitized fallback reason to HTTP callers whose legacy response body is a bare result array.

func (*SearchResponse) ResponseTrailers

func (r *SearchResponse) ResponseTrailers() map[string]string

ResponseTrailers exposes the sanitized fallback reason to gRPC callers.

func (*SearchResponse) ResultMetadata

func (r *SearchResponse) ResultMetadata() map[string]any

ResultMetadata returns protocol-neutral search selection metadata.

type SearchResult

type SearchResult struct {
	ID             string          `json:"id"`
	NodeID         storage.NodeID  `json:"nodeId"`
	GroupKey       string          `json:"group_key,omitempty"`
	Phase          string          `json:"phase,omitempty"`
	Passages       []SearchPassage `json:"passages,omitempty"`
	Matches        []SearchMatch   `json:"matches,omitempty"`
	Type           string          `json:"type"`
	Labels         []string        `json:"labels"`
	Title          string          `json:"title,omitempty"`
	Description    string          `json:"description,omitempty"`
	ContentPreview string          `json:"content_preview,omitempty"`
	Properties     map[string]any  `json:"properties,omitempty"`

	// Scoring. Similarity is the vector similarity when VectorRank is
	// positive (for a chunked search, the best of the chunks that found it by
	// vector), else the keyword score; graph fusion and MCP rely on this.
	Score      float64 `json:"score"`
	Similarity float64 `json:"similarity,omitempty"`

	// RRF metadata (vector_rank/bm25_rank are always emitted so clients see original
	// ranks even when Stage-2 reranking is applied; 0 means not in that result set.
	// A chunked search reports each method's best rank across its chunks.)
	RRFScore   float64 `json:"rrf_score,omitempty"`
	VectorRank int     `json:"vector_rank"`
	BM25Rank   int     `json:"bm25_rank"`

	// Relationship is a relationship search's result: its ID (also in ID),
	// type, endpoints and returned properties; NodeID and Labels are empty.
	// A pointer, so a node result grows by one word (#1065).
	Relationship *storage.Edge `json:"relationship,omitempty"`
	// contains filtered or unexported fields
}

SearchResult represents a unified search result.

func (SearchResult) MaterializedNode

func (result SearchResult) MaterializedNode(database ...string) *storage.Node

MaterializedNode returns a detached logical node for a search hit. Preserve the source timestamps: later property-visibility checks must score the node that was read, rather than a reconstruction with a zero creation time. Managed vectors stay in storage; a user vector property remains a property. A database context supplies provenance only when the result has no source database, as with compact continuation results. Existing provenance wins.

type Service

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

Service provides unified hybrid search with automatic index management.

The Service maintains:

  • Vector index (HNSW for fast approximate nearest neighbor search)
  • Full-text index (BM25 with inverted index)
  • Connection to storage engine for node data enrichment

Thread-safe: Multiple goroutines can call Search() concurrently.

Example:

svc := search.NewService(engine, search.DefaultVectorDimensions, nil)
defer svc.Close()

// Index existing data
if err := svc.BuildIndexes(ctx); err != nil {
	log.Fatal(err)
}

// Index new nodes as they're created
node := &storage.Node{...}
if err := svc.IndexNode(node); err != nil {
	log.Printf("Failed to index: %v", err)
}

func NewService

func NewService(engine storage.Engine, dimensions int, options *ServiceOptions) *Service

NewService creates a search service for the specified embedding dimensions and resource policy. Nil options use the default service policy.

func (*Service) AdmitsVectorDimensions

func (s *Service) AdmitsVectorDimensions(dimensions int) bool

AdmitsVectorDimensions reports whether IndexNode indexes a vector of dimensions: the active store's dimension (activeVectorDimensions), or any dimension while the next vector may still set it (vectorDimensionsAdoptable). A service with vector search off accepts every dimension, since it indexes no vectors. Writers that store vectors before indexing them check it first, so a vector the index can't hold is rejected rather than stored and left unindexed.

func (*Service) AfterFunc

func (s *Service) AfterFunc(delay time.Duration, fn func()) *lifecycle.OwnedTimer

AfterFunc retains the real callback, including a callback already running when Stop returns false. Origin/provenance decisions remain with its caller.

func (*Service) AttachMetrics added in v1.1.0

func (s *Service) AttachMetrics(metrics *observability.SearchMetrics)

AttachMetrics injects the observability.SearchMetrics bag into the Service for per-stage observation (Plan 04-05-05). Pre-binds the stage-specific observers under tenant-OFF so the request hot path pays zero WithLabelValues overhead per stage.

nil is tolerated: the observation helpers no-op when metrics is nil (defensive for embedded-library callers + tests that don't wire observability).

Idempotent: subsequent calls overwrite the previous bag and re-bind observers.

func (*Service) AwaitVectorIndexOnline

func (s *Service) AwaitVectorIndexOnline(ctx context.Context, name string, timeout time.Duration) error

AwaitVectorIndexOnline waits, at most timeout, for the index named name to be ONLINE, as Neo4j's vector query procedures do before they read an index. A FAILED index is an ErrVectorIndexFailed error carrying its cause; an index still populating when the wait ends is ErrVectorIndexNotOnline. An index already ONLINE costs a lookup: the wait starts only for a population. An index this service holds no population record for waits on nothing: a failed build refuses it (vectorIndexBuildState) and an unfinished one leaves the read to storage.

func (*Service) BM25Enabled added in v1.1.2

func (s *Service) BM25Enabled() bool

BM25Enabled reports whether BM25 search is enabled for this service.

func (*Service) BeginShutdown

func (s *Service) BeginShutdown()

BeginShutdown closes service admission and signals accepted work. Close owns the join and disposal. DB owners signal every service before joining workers that may themselves be waiting for a service's cancellation.

func (*Service) BeginVectorIndexPopulation

func (s *Service) BeginVectorIndexPopulation(name string, target VectorIndexTarget) *VectorIndexPopulation

BeginVectorIndexPopulation records that the index named name, reading target, is POPULATING. Its publisher calls it before the index becomes visible to readers (before the commit that publishes it), then Populate after the commit, or Abort when the commit fails.

func (*Service) BuildInProgress

func (s *Service) BuildInProgress() bool

BuildInProgress reports whether BuildIndexes is currently running.

func (*Service) BuildIndexes

func (s *Service) BuildIndexes(ctx context.Context) (resultErr error)

BuildIndexes builds search indexes from all nodes in the engine. Call this after storage (and WAL recovery) so indexes reflect durable state. When both fulltext and vector index paths are set, tries to load both from disk; if both load with count > 0 (and semver format version matches), the full iteration is skipped. Otherwise iterates over storage and saves both indexes at the end when paths are set.

func (*Service) CatchUpPendingRefreshes

func (s *Service) CatchUpPendingRefreshes(ctx context.Context) error

CatchUpPendingRefreshes applies now a refresh of every node and relationship that has one reserved and not yet applied, such as a write whose refresh is still waiting in the debounced event queue; each queued refresh, superseded, does nothing when it runs. A refresh whose read fails is retried a bounded number of times; it returns those that still failed. An entry a refresh refused is not a failure: the refresh installed everything else.

func (*Service) ClearIndexes

func (s *Service) ClearIndexes() error

ClearIndexes retires all collection-owned search data and capacity accounting. Use after dropping a database when its provider may reuse this service. Example: after dropping storage, call svc.ClearIndexes() before recreation.

func (*Service) ClearVectorIndex

func (s *Service) ClearVectorIndex() error

ClearVectorIndex removes all embeddings from the vector index. This is used when regenerating all embeddings to reset the index count. It also removes persisted vector/ANN artifacts and returns any removal error. Live mutations and derived builds finish before the source is cleared.

Example:

if err := svc.ClearVectorIndex(); err != nil { return err }

func (*Service) Close added in v1.1.8

func (s *Service) Close() error

Close stops search-service background workers and releases file-backed vector resources. It is safe to call more than once. PersistIndexesToDisk should be called by owners before Close when shutdown persistence is desired.

func (*Service) Closed

func (s *Service) Closed() bool

Closed reports whether Close was called (its background workers stopped and its file-backed vector store released).

func (*Service) ClusterStats

func (s *Service) ClusterStats() *gpu.ClusterStats

ClusterStats returns k-means clustering statistics.

func (*Service) ClusteringInProgress

func (s *Service) ClusteringInProgress() bool

ClusteringInProgress returns true if k-means is currently running for this service. Used to debounce timer ticks and avoid starting a second run while one is in progress.

func (*Service) ConfigureHNSWQuantization

func (s *Service) ConfigureHNSWQuantization(ctx context.Context, cfg HNSWQuantizationConfig) error

ConfigureHNSWQuantization sets a database's graph compression policy, for example from its persisted Qdrant collection configuration. It preserves lexical hints and original-vector scoring, and does not change global env.

err := service.ConfigureHNSWQuantization(ctx, HNSWQuantizationConfig{Mode:HNSWQuantizationScalar})

The configured policy also applies after graph rebuilds and restarts when the owning collection reloads its durable configuration.

func (*Service) CountPropertyVectorEntries added in v1.1.2

func (s *Service) CountPropertyVectorEntries(propertyKey string) int

CountPropertyVectorEntries reports the number of nodes that currently have a tracked vector entry for the given property key. Exposed for teardown / observability tests that need to assert DROP INDEX really purged the per-property bookkeeping.

func (*Service) CrossEncoderAvailable

func (s *Service) CrossEncoderAvailable(ctx context.Context) bool

CrossEncoderAvailable returns true if a cross-encoder reranker is configured and available.

func (*Service) CurrentStrategy

func (s *Service) CurrentStrategy() string

CurrentStrategy returns the currently active vector search strategy label. Returns "unknown" until a vector pipeline has been initialized.

func (*Service) DiscardNodeMutation

func (s *Service) DiscardNodeMutation(mutation NodeMutation)

DiscardNodeMutation retires work that could not be prepared for application. It cannot erase a newer reservation for the same node.

func (*Service) EmbeddingCount

func (s *Service) EmbeddingCount() int

EmbeddingCount returns the total number of nodes with embeddings in the vector index.

func (*Service) EnableClustering

func (s *Service) EnableClustering(gpuManager *gpu.Manager, numClusters int)

EnableClustering enables GPU k-means clustering for accelerated vector search.

Performance Improvements (Real-World Benchmarks):

  • 2,000 embeddings: ~14% faster (61ms vs 65ms avg)
  • 4,500 embeddings: ~26% faster (35ms vs 47ms avg)
  • 10,000+ embeddings: 10-50x faster (scales with dataset size)

The speedup increases with dataset size as the cluster-based search avoids comparing against all vectors.

Parameters:

  • gpuManager: GPU manager for acceleration (can be nil for CPU-only)
  • numClusters: Number of k-means clusters (0 for auto based on dataset size)

Call this BEFORE BuildIndexes(), then call TriggerClustering() after indexing.

Example:

gpuManager, _ := gpu.NewManager(nil)
svc.EnableClustering(gpuManager, 100) // 100 clusters
svc.BuildIndexes(ctx)
svc.TriggerClustering(ctx) // Run k-means

func (*Service) EnableRelationshipSearch

func (s *Service) EnableRelationshipSearch(embed RelationshipEmbedFunc)

EnableRelationshipSearch turns relationship indexing on for this service, with embed (nil: keyword search only) for its vectors. Call it once, after SetFulltextProperties and SetFulltextIndexPath, then StartRelationshipIndex.

func (*Service) EnsureWarm added in v1.1.2

func (s *Service) EnsureWarm(ctx context.Context) error

EnsureWarm triggers the lazy build (exactly once) and waits for it to finish. Safe to call from every read path — it's a fast no-op once the service is warm.

Synchronization contract:

  • Trigger fires at most once per service lifetime, in the OWNER'S long-lived context (NOT the caller's). A caller whose ctx times out while waiting returns ctx.Err() but the build continues so the next reader finds the service warm.
  • Concurrent first-readers wait on the same channel; only one fires the trigger.
  • When warmingLazy=false (eager) or the service is already fully built, EnsureWarm returns immediately.

func (*Service) FixVectorDimensions

func (s *Service) FixVectorDimensions()

FixVectorDimensions keeps the vector index at the dimension the service was created with: the configured embedding dimension, which every managed embedding has. The first node indexed then can't change it (maybeAutoSetVectorDimensions), so an ordinary numeric list property (page_starts = [0, 30]) indexed before any embedding can't make the index 2-dimensional and reject every embedding after it; a property list is a vector only when its length is that dimension. Without it, the first vector-shaped value sets the dimension of an empty index (a database with no embedder storing its own vectors).

func (*Service) FulltextDocCount added in v1.1.2

func (s *Service) FulltextDocCount() int

FulltextDocCount returns the number of documents in the BM25 fulltext index. Used by tests and observability to confirm whether writes are actually landing in BM25 or being short-circuited by the disabled flag.

func (*Service) FulltextLabels

func (s *Service) FulltextLabels() []string

FulltextLabels returns the configured BM25 label allowlist.

func (*Service) FulltextProperties added in v1.3.1

func (s *Service) FulltextProperties() []string

FulltextProperties returns the configured ordered BM25 property allowlist.

func (*Service) FulltextRetention

func (s *Service) FulltextRetention() []FulltextRetentionStatus

FulltextRetention returns the current optional-copy state for the existing database search status owner. Reading status never initializes an index.

func (*Service) GetBuildProgress

func (s *Service) GetBuildProgress() BuildProgress

GetBuildProgress returns current search build progress for status APIs.

func (*Service) GetDefaultMinSimilarity

func (s *Service) GetDefaultMinSimilarity() float64

GetDefaultMinSimilarity returns the configured minimum similarity threshold.

func (*Service) GetMinEmbeddingsForClustering

func (s *Service) GetMinEmbeddingsForClustering() int

GetMinEmbeddingsForClustering returns the current minimum embeddings threshold.

func (*Service) HasRelationshipVectorEntries added in v1.1.7

func (s *Service) HasRelationshipVectorEntries(relType, propertyKey string) bool

HasRelationshipVectorEntries reports whether relationship vector metadata exists for a relationship type/property pair. Empty relationship type matches any type.

func (*Service) IndexCapacityPolicy added in v1.3.1

func (s *Service) IndexCapacityPolicy() (bm25Max, vectorMax, metadataMax int64, bm25Storage, vectorStorage string)

IndexCapacityPolicy returns this service's restart-bound index resource policy.

func (*Service) IndexEdge added in v1.1.7

func (s *Service) IndexEdge(edge *storage.Edge) error

IndexEdge adds vector-shaped relationship properties to in-memory search metadata.

Relationship vector queries use this metadata to avoid scanning and decoding every relationship from storage for each db.index.vector.queryRelationships call.

Live writers use RefreshEdge; this payload form is for rebuilds and offline sinks, like IndexNode.

func (*Service) IndexNode

func (s *Service) IndexNode(node *storage.Node) error

IndexNode adds a node to all search indexes. All embeddings are stored in ChunkEmbeddings (even single chunk = array of 1).

func (*Service) IndexRelationship

func (s *Service) IndexRelationship(edge *storage.Edge)

IndexRelationship indexes or re-indexes a relationship for relationship search; a no-op when it is off. During a build it is ordered with the build sequence (queueBuildWrite).

func (*Service) IndexRevision

func (s *Service) IndexRevision() uint64

IndexRevision is a number that advances whenever what a search can return changes: a node or relationship is indexed or removed, an index is cleared or rebuilt, or the embedding space or index flags change. A cache of search results reads it before computing a result and keys the result by it, so the result is never served once a later change has completed (#945).

func (*Service) IndexSizeBytes added in v1.1.0

func (s *Service) IndexSizeBytes(kind string) uint64

IndexSizeBytes satisfies observability.SearchProbe (Plan 04-05-04). It returns a best-effort byte estimate of the named index kind:

  • hnsw: HNSWIndex.Size() (vector count) × vector dimensions × sizeof(float32). Captures the dominant memory cost of HNSW; node graph metadata is comparatively small.
  • bm25: the optional maintained procedure corpora's estimated retained bytes. A native BM25 size accessor is still unavailable; this component drops to zero when pressure releases the reconstructible copies.

kind values outside AllowedSearchIndexKinds return 0 — defense in depth even though the closed enum at the call site means this branch is unreachable from the GaugeFunc collector.

func (*Service) Instance

func (s *Service) Instance() uint64

Instance identifies this service among every one created in the process. A database whose search is reset gets a new service whose IndexRevision starts over, so a cache of search results keys by Instance and IndexRevision together.

func (*Service) IsClusteringEnabled

func (s *Service) IsClusteringEnabled() bool

IsClusteringEnabled returns true if GPU clustering is enabled.

func (*Service) IsReady

func (s *Service) IsReady() bool

IsReady reports whether the search indexes are fully built and ready.

func (*Service) LifetimeContext

func (s *Service) LifetimeContext() context.Context

LifetimeContext is immutable and is canceled by BeginShutdown/Close.

func (*Service) MarkReadyDisabled added in v1.1.2

func (s *Service) MarkReadyDisabled()

func (*Service) PersistIndexesToDisk

func (s *Service) PersistIndexesToDisk()

PersistIndexesToDisk writes the current BM25, vector, HNSW, and IVF-HNSW (per-cluster) indexes to disk immediately. Call this on shutdown so the latest in-memory state is saved before exit, same as every other persisted index. Cancels any pending debounced persist so no write runs after shutdown.

func (*Service) ReadFulltextDocuments

func (s *Service) ReadFulltextDocuments(ctx context.Context, engine storage.Engine, scope FulltextDocumentScope, build FulltextDocumentBuilder, read func(context.Context, FulltextDocuments) error) error

ReadFulltextDocuments serves a named fulltext projection from this search service, maintaining it from storage changes independently of query text. Definition is the schema's identity, including ordered fields and scope; changing or recreating a named index replaces its old projection.

Only a committed view of the service's own database (storage.SameEventView: the same publisher, namespace and rows, reached only through forwarders) has a retained corpus, whichever view built the service. Every other view, and a scope with dynamic visibility, is request-scoped.

Documents come from the view's own readers, so a read serves what the release reader serves. A commit moves the graph revision only after its data is visible, so rows read after sampling a revision include every write that revision names, and an equal revision later reuses them. A write during the population moves the revision afterwards. A baseline sampled with the event queue settled, and a revision and event count that moved together since, refresh by ID from the journal; anything else populates again.

read receives the read context this service accepted for it, so cancellation and shutdown stay owned here and reach every follow-up read the consumer issues on these documents.

func (*Service) RefreshEdge

func (s *Service) RefreshEdge(ctx context.Context, edgeID storage.EdgeID) error

RefreshEdge makes the relationship's index entries match storage, as RefreshNode does for nodes; a deleted relationship leaves them.

func (*Service) RefreshEdgeWithMutation

func (s *Service) RefreshEdgeWithMutation(ctx context.Context, mutation EdgeMutation) error

RefreshEdgeWithMutation applies a relationship refresh reserved earlier; storage is read after the reservation, as in RefreshNodeWithMutation.

func (*Service) RefreshNode

func (s *Service) RefreshNode(ctx context.Context, nodeID storage.NodeID) error

RefreshNode makes the node's index entries match storage: indexed while it is stored and visible, removed otherwise. Live writers and readers that find a node missing use it rather than IndexNode or RemoveNode, so none of them decides from a read that a newer write may already have outdated.

func (*Service) RefreshNodeWithMutation

func (s *Service) RefreshNodeWithMutation(ctx context.Context, mutation NodeMutation) error

RefreshNodeWithMutation applies a refresh reserved earlier, such as one queued for a storage event. Storage is read after the reservation: a write this read misses commits later and reserves a newer refresh of its own, which makes this one a no-op.

The refresh installs the stored node entry by entry (installStored): an entry a budget or a dimension refuses is decided on its own, and the error reports the refusal. A read that fails keeps the reservation for the retry owner; the node's entries lag until it lands.

func (*Service) RelationshipEmbeddingCount

func (s *Service) RelationshipEmbeddingCount() int

RelationshipEmbeddingCount reports how many relationships have vectors.

func (*Service) RelationshipFulltextProperties

func (s *Service) RelationshipFulltextProperties() []string

RelationshipFulltextProperties is relationship search's keyword property allowlist: its own when set, otherwise the node list.

func (*Service) RelationshipSearchEnabled

func (s *Service) RelationshipSearchEnabled() bool

RelationshipSearchEnabled reports whether this service indexes relationships.

func (*Service) RemoveEdge added in v1.1.7

func (s *Service) RemoveEdge(edgeID storage.EdgeID) error

RemoveEdge removes a relationship from vector search metadata. Like node writes (see IndexEdge), a removal waits for the explicit build, so its relationship stream cannot re-add the edge.

func (*Service) RemoveNode

func (s *Service) RemoveNode(nodeID storage.NodeID) error

RemoveNode removes a node from all search indexes. Also removes all chunk embeddings (for nodes with multiple chunks).

A payload removal for rebuilds and offline sinks, like IndexNode; live writers use RefreshNode (TestLiveIndexWritersRefreshFromStorage).

func (*Service) RemovePropertyVectorIndex added in v1.1.2

func (s *Service) RemovePropertyVectorIndex(propertyKey string)

RemovePropertyVectorIndex tears down all in-memory vector entries that were indexed under the given property key (every node's property entry for it). Cypher DROP INDEX does not call it: those entries are projections of storage that every vector index on the property reads, so dropping one index keeps them (NOR-404).

Safe to call when the property was never indexed: it walks the nodePropVector map and is a no-op if no nodes recorded an entry for propertyKey. Callers are expected to also call DropIndex on the schema to remove the named-index entry that points at this property.

func (*Service) RemoveRelationship

func (s *Service) RemoveRelationship(id storage.EdgeID)

RemoveRelationship drops a relationship from relationship search; a no-op when it is off. During a build it is ordered with the build sequence (queueBuildWrite).

func (*Service) RerankCandidates

func (s *Service) RerankCandidates(ctx context.Context, query string, candidates []RerankCandidate, opts *SearchOptions) ([]RerankResult, error)

RerankCandidates applies the configured Stage-2 reranker to caller-provided candidates. This is a seam-friendly API for adapters that need rerank semantics without running retrieval.

func (*Service) RerankerAvailable

func (s *Service) RerankerAvailable(ctx context.Context) bool

RerankerAvailable returns true if Stage-2 reranking is configured and available.

func (*Service) RerankerName added in v1.3.1

func (s *Service) RerankerName() string

RerankerName returns the configured Stage-2 reranker name, or an empty string.

func (*Service) ReserveEdgeMutation

func (s *Service) ReserveEdgeMutation(edgeID storage.EdgeID) EdgeMutation

ReserveEdgeMutation supersedes older work for this relationship. Generations come from the same counter and registry as node reservations.

func (*Service) ReserveNodeMutation

func (s *Service) ReserveNodeMutation(nodeID storage.NodeID) NodeMutation

ReserveNodeMutation supersedes older work for this node. Reservation and application share one lock, so a newer reservation cannot slip between the generation check and the index write. No lock is retained by the caller.

func (*Service) RunBackgroundTask

func (s *Service) RunBackgroundTask(fn func()) bool

RunBackgroundTask enrolls before dispatch. A DB build trampoline uses the same service owner even when its caller already holds the DB state lock.

func (*Service) RuntimeStrategyTransitionsEnabled added in v1.1.8

func (s *Service) RuntimeStrategyTransitionsEnabled() bool

RuntimeStrategyTransitionsEnabled reports whether live write-triggered ANN strategy transitions are enabled.

func (*Service) Search

func (s *Service) Search(ctx context.Context, query string, embedding []float32, opts *SearchOptions) (resp *SearchResponse, err error)

Search performs hybrid search with automatic fallback.

Search strategy:

  1. Try RRF hybrid search (vector + BM25) if embedding provided
  2. Fall back to vector-only if RRF returns no results
  3. Fall back to BM25-only if vector search fails or no embedding

This ensures you always get results even if one index is empty or fails.

Parameters:

  • ctx: Context for cancellation
  • query: Text query for BM25 search
  • embedding: Vector embedding for similarity search (can be nil)
  • opts: Search options (use DefaultSearchOptions() if unsure)

Example:

svc := search.NewService(engine, search.DefaultVectorDimensions, nil)

// Hybrid search (best results)
query := "graph database memory"
embedding, _ := embedder.Embed(ctx, query)
opts := search.DefaultSearchOptions()
opts.Limit = 10

resp, err := svc.Search(ctx, query, embedding, opts)
if err != nil {
	return err
}

fmt.Printf("Found %d results using %s\n",
	resp.Returned, resp.SearchMethod)

for i, result := range resp.Results {
	fmt.Printf("%d. [RRF: %.4f] %s\n",
		i+1, result.RRFScore, result.Title)
	fmt.Printf("   Vector rank: #%d, BM25 rank: #%d\n",
		result.VectorRank, result.BM25Rank)
}

Returns a SearchResponse with ranked results and metadata about the search method used.

func (*Service) SearchRelationships

func (s *Service) SearchRelationships(ctx context.Context, query string, embedding []float32, opts *SearchOptions) (response *SearchResponse, err error)

SearchRelationships ranks relationships by keyword and, with an embedding, vector similarity, fused by reciprocal rank as node search is. Each result names the relationship, its type and both endpoints, with its properties. Types filters by relationship type.

func (*Service) SearchResultCachePolicy added in v1.3.1

func (s *Service) SearchResultCachePolicy() (maxEntries int, ttl time.Duration)

SearchResultCachePolicy returns the live result-cache capacity and TTL.

func (*Service) SearchTextContinuation added in v1.3.3

func (s *Service) SearchTextContinuation(
	ctx context.Context,
	query string,
	opts *SearchOptions,
	request SearchContinuationRequest,
	chunkQuery ChunkQueryFunc,
	embedQuery EmbedQueryFunc,
	searchQuery SearchQueryFunc,
	errorPolicy ChunkedSearchErrorPolicy,
) (out *SearchContinuationPage, err error)

SearchTextContinuation starts or resumes a progressively deepened canonical text search. Chunking and embedding execute only while starting the stream.

func (*Service) SetCompleteContinuationPolicy added in v1.3.3

func (s *Service) SetCompleteContinuationPolicy(policy CompleteContinuationPolicy)

SetCompleteContinuationPolicy replaces the limits used by future complete continuation builds. Zero fields retain their defaults.

func (*Service) SetContinuationRegistry added in v1.3.3

func (s *Service) SetContinuationRegistry(registry *resultstream.Registry)

SetContinuationRegistry shares one process registry across database-scoped search services. The registry remains owned by the caller.

func (*Service) SetDefaultMinSimilarity

func (s *Service) SetDefaultMinSimilarity(threshold float64)

SetDefaultMinSimilarity sets the default minimum cosine similarity threshold for vector search. Apple Intelligence embeddings produce scores in 0.2-0.8 range, bge-m3/mxbai produce 0.7-0.99. Default: 0.0 (let RRF ranking handle relevance filtering)

func (*Service) SetEmbedTextOptions

func (s *Service) SetEmbedTextOptions(opts *embeddingutil.EmbedTextOptions)

SetEmbedTextOptions tells the service how the embedding worker builds a node's embedding text (labels and the included properties), so the chunks of an embedding made before chunk places were recorded can be placed in the node's properties.

func (*Service) SetEmbeddingSpace

func (s *Service) SetEmbeddingSpace(space string)

SetEmbeddingSpace selects the managed vector space for this database search service. Configure it before building indexes. Named and property vectors retain their existing Neo4j-compatible behavior.

func (*Service) SetFulltextIndexPath

func (s *Service) SetFulltextIndexPath(path string)

SetFulltextIndexPath sets the path for persisting the BM25 fulltext index. When both fulltext and vector paths are set, BuildIndexes() will try to load both; reuse requires matching source/projection certificates and build settings.

func (*Service) SetFulltextLabels

func (s *Service) SetFulltextLabels(labels []string)

SetFulltextLabels limits BM25 indexing to nodes carrying at least one of the labels (NORNICDB_SEARCH_BM25_LABELS); any other node is indexed with no text, so it is never a keyword hit, as a node with none of the listed properties already is. An empty list indexes every node. Configure this before building indexes; a change invalidates persisted BM25 data.

func (*Service) SetFulltextProperties added in v1.3.1

func (s *Service) SetFulltextProperties(properties []string)

SetFulltextProperties limits BM25 indexing to the ordered property values. An empty list preserves the default behavior of indexing labels and all properties. Configure this before building indexes.

func (*Service) SetGPUManager

func (s *Service) SetGPUManager(manager *gpu.Manager)

SetGPUManager enables GPU acceleration for exact brute-force vector search.

This is independent from k-means clustering. When enabled, the vector pipeline may choose GPU brute-force search (exact) for datasets where it outperforms HNSW. The GPU copy of the vectors is built when that strategy is first chosen (ensureGPUIndexSynced), not here: outside NORNICDB_VECTOR_GPU_BRUTE_MIN_N..MAX_N it is never used, and it holds every vector in host and GPU memory.

func (*Service) SetHNSWIndexPath

func (s *Service) SetHNSWIndexPath(path string)

SetHNSWIndexPath sets the path for persisting the HNSW index. When set with persist search indexes, the HNSW index is saved after build/warmup and loaded on startup so the full graph does not need to be rebuilt from vectors.

func (*Service) SetIndexFlags added in v1.1.2

func (s *Service) SetIndexFlags(bm25Enabled, vectorEnabled bool) (changed bool)

SetIndexFlags configures whether BM25 and vector search are enabled for this service. Atomic flag swap only — does not tear down any in-memory or on-disk structures. Runtime teardown on a runtime flag flip lives in the admin API path (server_dbconfig.go) which calls ResetSearchService followed by getOrCreateSearchService, producing a freshly-configured service from scratch.

Returns true if either flag changed value, so callers (typically just the construction path in getOrCreateSearchService) can observe whether the swap was a no-op.

func (*Service) SetLazyWarming added in v1.1.2

func (s *Service) SetLazyWarming(lazy bool, fn WarmFunc)

SetLazyWarming marks this service as lazy-warmed and stores the WarmFunc callback that EnsureWarm uses to request the actual build. Call from the DB's getOrCreateSearchService when the resolved warming setting is "lazy" for the database. When called with lazy=false, the warm state is cleared (subsequent EnsureWarm calls become no-ops).

func (*Service) SetLocalizer added in v1.3.1

func (s *Service) SetLocalizer(manager *localization.Manager)

SetLocalizer injects the optional operator-log localizer.

func (*Service) SetLogger added in v1.3.1

func (s *Service) SetLogger(logger *slog.Logger)

SetLogger injects the optional structured operator logger. It may be called while the service runs; later log calls use it.

func (*Service) SetMinEmbeddingsForClustering

func (s *Service) SetMinEmbeddingsForClustering(threshold int)

SetMinEmbeddingsForClustering sets the minimum number of embeddings required before k-means clustering is triggered. Below this threshold, the default non-clustered vector strategy is used to avoid cluster overhead.

This should be called BEFORE TriggerClustering() to take effect.

Parameters:

  • threshold: Minimum embeddings (must be > 0, default: 1000)

Tuning Guidelines:

  • 1000 (default): Safe for most workloads
  • 500-1000: Latency-sensitive applications with moderate data
  • 100-500: Testing or small datasets
  • 2000+: Very large datasets, delay clustering until more data arrives

Example:

svc := search.NewService(engine, search.DefaultVectorDimensions, nil)
svc.SetMinEmbeddingsForClustering(500) // Lower threshold for faster clustering
svc.EnableClustering(gpuManager, 100)
svc.BuildIndexes(ctx)
svc.TriggerClustering(ctx) // Will cluster if >= 500 embeddings

func (*Service) SetNodeDecayFilter added in v1.1.0

func (s *Service) SetNodeDecayFilter(fn NodeDecayFilterFunc)

SetNodeDecayFilter installs a decay visibility filter for search results. Candidates that the filter reports as suppressed are removed from vector and BM25 candidate pools before RRF fusion.

func (*Service) SetPersistenceEnabled

func (s *Service) SetPersistenceEnabled(enabled bool)

SetPersistenceEnabled controls whether index persistence is allowed. When false, all persist paths (debounced writes, build checkpoints, and shutdown flush) are treated as no-ops even if index paths are configured.

func (*Service) SetRefreshRetry

func (s *Service) SetRefreshRetry(retry RefreshRetryFunc)

SetRefreshRetry preserves the notification API for callers that queue their own new work rather than retaining a failed reservation.

func (*Service) SetRefreshRetryOwner

func (s *Service) SetRefreshRetryOwner(owner RefreshRetryOwner)

func (*Service) SetRelationshipEmbedPolicy

func (s *Service) SetRelationshipEmbedPolicy(policy string)

relationshipSource hashes a relationship's type and properties, in key order, to tell when its embedding text may have changed. SetRelationshipEmbedPolicy records what selects a relationship's embedding text (its property lists, whether its type is included), as policy; a change of policy changes every relationship's source, so vectors saved under the earlier one are embedded again. Set it before the relationship index starts.

func (*Service) SetRelationshipFulltextProperties

func (s *Service) SetRelationshipFulltextProperties(properties []string)

SetRelationshipFulltextProperties limits relationship search's keyword index to the ordered property values; an empty list leaves it on the node list (SetFulltextProperties). Configure this before the relationship index is built.

func (*Service) SetReranker

func (s *Service) SetReranker(r Reranker)

SetReranker configures the Stage-2 reranker and invalidates cached search results when the provider changes. CrossEncoder implements Reranker:

svc.SetReranker(search.NewCrossEncoder(&search.CrossEncoderConfig{
    Enabled: true, APIURL: "http://localhost:8081/rerank",
    Model: "cross-encoder/ms-marco-MiniLM-L-6-v2",
}))

Uses a quick read-lock check to avoid write-lock contention when the value hasn't changed. This prevents deadlock when multiple goroutines call getOrCreateSearchService concurrently.

func (*Service) SetRuntimeStrategyTransitionsEnabled added in v1.1.8

func (s *Service) SetRuntimeStrategyTransitionsEnabled(enabled bool)

SetRuntimeStrategyTransitionsEnabled controls whether live writes may schedule background vector strategy rebuilds, such as brute-force -> HNSW transitions. Explicit BuildIndexes/warmup calls can still build ANN structures when this is false.

func (*Service) SetSearchResultCachePolicy added in v1.3.1

func (s *Service) SetSearchResultCachePolicy(maxEntries int, ttl time.Duration)

SetSearchResultCachePolicy applies a dynamic result-cache capacity and TTL.

func (*Service) SetVectorIndexPath

func (s *Service) SetVectorIndexPath(path string)

SetVectorIndexPath sets the path for persisting the vector index. When both fulltext and vector paths are set, BuildIndexes() will try to load both; reuse requires matching source/projection certificates and build settings.

func (*Service) StartRelationshipIndex

func (s *Service) StartRelationshipIndex()

StartRelationshipIndex builds the relationship keyword index from storage, keeping the persisted vectors of relationships that haven't changed, then embeds the others in the background until the service closes. It returns at once; searches wait for the build. An unreadable or unconverted snapshot is left untouched and reported by SearchRelationships and Close.

func (*Service) TriggerClustering

func (s *Service) TriggerClustering(ctx context.Context) error

TriggerClustering runs k-means clustering on all indexed embeddings. Stops promptly when ctx is cancelled (e.g. process shutdown). Only one run executes at a time per service; if clustering is already in progress, returns nil immediately (debounced).

Trigger Policies:

  • After bulk loads: Automatically called after BuildIndexes() completes
  • Periodic clustering: Background timer runs clustering at regular intervals
  • Manual trigger: Call this after bulk data loading to enable k-means routing

Once clustering completes, the vector search pipeline automatically uses KMeansCandidateGen for candidate generation, providing significant speedup for very large datasets (N > 100K).

Returns nil (not error) if there are too few embeddings - clustering will be skipped silently and the default non-clustered vector strategy is used. Returns error only if clustering is not enabled or fails unexpectedly.

func (*Service) VectorEnabled added in v1.1.2

func (s *Service) VectorEnabled() bool

VectorEnabled reports whether vector search is enabled for this service.

func (*Service) VectorIndexDimensions

func (s *Service) VectorIndexDimensions() int

VectorIndexDimensions returns the configured dimensions of the vector index.

func (*Service) VectorIndexPopulationOf

func (s *Service) VectorIndexPopulationOf(name string) *VectorIndexPopulation

VectorIndexPopulationOf is the population record of the index named name: nil for an index whose population this service did not serve, whose state is the service's build (vectorIndexBuildState).

func (*Service) VectorIndexState

func (s *Service) VectorIndexState(name string) (string, error)

VectorIndexState reports the population state of the index named name, and the cause of a FAILED population. The record of a population this service served is the index's state, whatever build the service runs later. An index this service holds no population record for takes the state of the service's own build (vectorIndexBuildState): a service that did not populate the index serves it through that build, so its outcome is the index's state.

func (*Service) VectorQueryNodes

func (s *Service) VectorQueryNodes(ctx context.Context, queryEmbedding []float32, spec VectorQuerySpec) ([]VectorQueryHit, error)

VectorQueryNodes executes a Cypher-style vector query.

This method preserves Cypher semantics for per-node embedding selection:

  1. Prefer NamedEmbeddings[Property] (or "default" when Property is empty)
  2. If Property is set, next try node.Properties[Property] as a vector array
  3. Fallback to ChunkEmbeddings[0..N] (best score across chunks)

For performance, cosine-similarity queries are executed against the in-memory vector index (unified pipeline) rather than scanning storage. This legacy entry point preserves live-indexed Cypher reads before full warmup; use VectorQueryNodesWithOptions for reads requiring warming/readiness.

Scores are on spec.ScoreScale; the zero value is Neo4j's scale for its vector indexes (#907): cosine max((1 + cos) / 2, 0) and euclidean 1 / (1 + d²), both in [0, 1] (vector.Neo4jCosineSimilarity, vector.Neo4jEuclideanSimilarity); dot, a NornicDB similarity, is the dot product.

func (*Service) VectorQueryNodesWithOptions

func (s *Service) VectorQueryNodesWithOptions(ctx context.Context, queryEmbedding []float32, spec VectorQuerySpec, opts *SearchOptions) ([]VectorQueryHit, error)

VectorQueryNodesWithOptions is VectorQueryNodes for a caller with its own search options. Of opts it reads HNSWEf, the query's own HNSW beam width, and Where, which admits candidate nodes before the top-K cut, as a Cypher WHERE on the node does; nil opts uses default options. It is the vector query the Qdrant API's Search runs, on the same index and strategy as Cypher's. Unlike the legacy scalar-vector API, this optioned entry point warms a lazy service and rejects an incomplete build before returning any results.

Example:

hits, err := svc.VectorQueryNodesWithOptions(ctx, query, search.VectorQuerySpec{
	Label: "QdrantPoint", Property: "default", Similarity: "cosine",
	Limit: 10, ScoreScale: search.VectorScoreSimilarity,
}, &search.SearchOptions{HNSWEf: 128, Where: func(_ context.Context, n *storage.Node) (bool, error) {
	return n.Properties["tag"] == "a", nil
}})

func (*Service) VectorQueryRelationships added in v1.1.7

func (s *Service) VectorQueryRelationships(ctx context.Context, queryEmbedding []float32, spec RelationshipVectorQuerySpec) (hits []RelationshipVectorQueryHit, err error)

VectorQueryRelationships executes a Cypher-style relationship vector query using in-memory relationship-vector metadata. This avoids scanning storage.AllEdges() on every fact-search call.

func (*Service) VectorSearchCandidates

func (s *Service) VectorSearchCandidates(ctx context.Context, embedding []float32, opts *SearchOptions) ([]SearchCandidate, error)

VectorSearchCandidates performs vector-only search and returns lightweight candidates without enrichment. It is optimized for throughput: it skips BM25, RRF fusion, and storage fetches.

This method uses the unified vector search pipeline (CandidateGen + ExactScore) with automatic strategy selection. HNSW is the default; CPU brute-force is only selected automatically when NORNICDB_VECTOR_CPU_BRUTE_MAX_N is set above zero.

func (*Service) VectorStorageStatus

func (s *Service) VectorStorageStatus() VectorStorageStatus

func (*Service) WakeRelationshipEmbedding

func (s *Service) WakeRelationshipEmbedding()

WakeRelationshipEmbedding has relationship search embed its pending relationships now, as when an embedder has just been loaded, instead of after a failed attempt's retry delay; a no-op when it is off.

type ServiceOptions added in v1.3.1

type ServiceOptions struct {
	// MemoryPolicy is the existing database admission owner, shared with storage
	// and transports. Nil leaves application admission disabled; retained copies
	// still obey the already-applied Go runtime memory limit.
	MemoryPolicy *memory.Policy
	// SearchCursorMaxPageSize bounds pages when this service owns its registry.
	SearchCursorMaxPageSize int

	DatabaseID               string
	SearchResultCacheEntries int
	SearchResultCacheTTL     time.Duration
	BM25MemoryMaxBytes       int64
	VectorMemoryMaxBytes     int64
	MetadataMemoryMaxBytes   int64
	BM25StorageMode          string
	VectorStorageMode        string
	BM25StemmerID            string
	BM25Stemmer              *stemmer.Registration
}

ServiceOptions configures database-specific search service resources.

func DefaultServiceOptions

func DefaultServiceOptions(databaseID string) ServiceOptions

DefaultServiceOptions returns the standard service resource policy bound to databaseID. Callers can override individual fields before constructing a database-scoped Service.

type VectorFileStore

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

VectorFileStore is an append-only vector store backed by a file. Only ID-to-ordinal metadata is kept in RAM; vector data lives on disk. All vectors are stored normalized (one copy per id).

func NewVectorFileStore

func NewVectorFileStore(vecBasePath string, dimensions int) (*VectorFileStore, error)

NewVectorFileStore creates a new file-backed store and opens the vector file for append. vecBasePath is the path prefix: .vec and .meta will be appended. If the .vec file exists it is opened for append; otherwise it is created with a header.

func (*VectorFileStore) Add

func (v *VectorFileStore) Add(id string, vec []float32) error

Add appends a normalized vector to the store. vec is normalized in place/copied; only one copy is stored.

func (*VectorFileStore) Close

func (v *VectorFileStore) Close() error

Close closes the underlying file. The store must not be used after Close.

func (*VectorFileStore) CompactIfNeeded

func (v *VectorFileStore) CompactIfNeeded() (bool, error)

CompactIfNeeded rewrites .vec with only live slots when stale entries accumulate. The rewrite is atomic: write temp file, fsync, rename. Returns true when compaction actually ran.

func (*VectorFileStore) Count

func (v *VectorFileStore) Count() int

Count returns the number of vectors in the store.

func (*VectorFileStore) GetBuildIndexedCount

func (v *VectorFileStore) GetBuildIndexedCount() int64

GetBuildIndexedCount returns the last persisted checkpoint count (0 if none). Used at start of BuildIndexes to skip the first N nodes when resuming.

func (*VectorFileStore) GetDimensions

func (v *VectorFileStore) GetDimensions() int

GetDimensions returns the vector dimension.

func (*VectorFileStore) GetVector

func (v *VectorFileStore) GetVector(id string) ([]float32, bool)

GetVector returns a copy of the stored (normalized) vector for id, or (nil, false) if not found.

func (*VectorFileStore) Has

func (v *VectorFileStore) Has(id string) bool

Has reports whether id is present in the id-to-ordinal map.

func (*VectorFileStore) IDs

func (v *VectorFileStore) IDs() []string

IDs returns the IDs of the vectors in the store, without reading them.

func (*VectorFileStore) IterateChunked

func (v *VectorFileStore) IterateChunked(chunkSize int, fn func(ids []string, vecs [][]float32) error) error

IterateChunked reads the vector file in chunks and calls fn(ids, vecs) for each chunk. Used to build HNSW without loading all vectors into memory. fn may be called with fewer than chunkSize vectors on the last chunk. Callbacks run without mu: HNSW construction looks vectors up through Service and this store. An owned read handle and copied ordinals keep this snapshot valid across close or compaction, which replaces the store's handle and file.

func (*VectorFileStore) Load

func (v *VectorFileStore) Load() error

Load is the sole vector tuple installer. It verifies metadata and the committed payload prefix before truncating any uncommitted append tail; an append tail is uncommitted because the .meta slot count is the commit point.

func (*VectorFileStore) NodeQueryMetadata added in v1.3.2

func (v *VectorFileStore) NodeQueryMetadata() (map[string][]string, map[string]map[string]string, map[string]map[string]string, map[string][]string, bool)

NodeQueryMetadata returns durable node-to-vector associations, if available.

func (*VectorFileStore) NodeQueryMetadataWithTypes

func (v *VectorFileStore) NodeQueryMetadataWithTypes() (map[string][]string, map[string]string, map[string]map[string]string, map[string]map[string]string, map[string][]string, bool)

NodeQueryMetadataWithTypes returns query metadata only when the sidecar has the complete type-property projection required for storage-free filtering.

func (*VectorFileStore) Remove

func (v *VectorFileStore) Remove(id string) bool

Remove deletes id from the live id-to-ordinal map. The old .vec slot is left in-place and reclaimed by compaction.

func (*VectorFileStore) Save

func (v *VectorFileStore) Save() error

Save commits the ID-to-ordinal map and its associations as one recoverable tuple after syncing vector payloads. Appends leave the committed payload prefix untouched, so this publication writes metadata only; compaction and relocation stage a complete replacement payload and use the same decision.

func (*VectorFileStore) SetBuildIndexedCount

func (v *VectorFileStore) SetBuildIndexedCount(n int64)

SetBuildIndexedCount sets the last checkpoint count from BuildIndexes (for resume). Call before Save() when persisting after a checkpoint so the next run can skip already-indexed nodes.

func (*VectorFileStore) SetNodeQueryMetadata added in v1.3.2

func (v *VectorFileStore) SetNodeQueryMetadata(labels map[string][]string, named, properties map[string]map[string]string, chunks map[string][]string)

SetNodeQueryMetadata stores node-to-vector associations in the sidecar.

func (*VectorFileStore) SetNodeQueryMetadataWithTypes

func (v *VectorFileStore) SetNodeQueryMetadataWithTypes(labels map[string][]string, types map[string]string, named, properties map[string]map[string]string, chunks map[string][]string)

SetNodeQueryMetadataWithTypes also persists the legacy string type-property projection used by metadata-only search candidate filtering.

func (*VectorFileStore) Sync

func (v *VectorFileStore) Sync() error

Sync flushes the .vec file to disk so progress is visible and durable.

type VectorFileStoreMeta

type VectorFileStoreMeta struct {
	Version               int                          `msgpack:"v"`
	Dimensions            int                          `msgpack:"dim"`
	IDToOrdinal           map[string]int64             `msgpack:"id2ord"`
	DataSlots             int64                        `msgpack:"slots"`
	BuildIndexedCount     int64                        `msgpack:"build_count,omitempty"` // last checkpoint count during BuildIndexes; used for resume
	NodeLabels            map[string][]string          `msgpack:"node_labels,omitempty"`
	NodeTypes             map[string]string            `msgpack:"node_types,omitempty"`
	NodeNamedVectors      map[string]map[string]string `msgpack:"node_named_vectors,omitempty"`
	NodePropertyVectors   map[string]map[string]string `msgpack:"node_property_vectors,omitempty"`
	NodeChunkVectors      map[string][]string          `msgpack:"node_chunk_vectors,omitempty"`
	NodeMetadataPersisted bool                         `msgpack:"node_metadata_persisted,omitempty"`
	NodeTypesPersisted    bool                         `msgpack:"node_types_persisted,omitempty"`
	// Integrity and derivative identity of this exact tuple. A .meta without
	// them cannot certify its payload/associations and is rebuilt.
	MetadataDigest string                     `msgpack:"metadata_digest,omitempty"`
	PayloadDigest  string                     `msgpack:"payload_digest,omitempty"`
	Generation     vectorCheckpointGeneration `msgpack:"generation,omitempty"`
}

VectorFileStoreMeta is persisted to the .meta file (msgpack).

type VectorGetter

type VectorGetter interface {
	GetVector(id string) ([]float32, bool)
}

VectorGetter is implemented by *VectorIndex and by adapters for VectorLookup (e.g. file-backed store).

type VectorIndex

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

VectorIndex provides exact vector similarity search using cosine similarity.

The index stores normalized vectors for efficient similarity computation and supports concurrent read/write operations. It uses brute-force search which provides exact results but has O(n) time complexity.

Key features:

  • Exact cosine similarity computation
  • Automatic vector normalization
  • Thread-safe concurrent operations
  • Context-aware search with cancellation
  • Configurable similarity thresholds

Example:

// Create index for 512-dimensional vectors
index := search.NewVectorIndex(512)

// Add vectors
for id, vector := range vectors {
	index.Add(id, vector)
}

// Search with minimum similarity threshold
results, _ := index.Search(ctx, queryVector, 5, 0.8)
for _, result := range results {
	fmt.Printf("%s: %.3f\n", result.ID, result.Score)
}

Performance:

  • Add: O(d) where d = dimensions
  • Search: O(n×d) where n = number of vectors
  • Memory: O(n×d) for normalized vectors

Thread Safety:

All methods are thread-safe using RWMutex for concurrent access.

func NewVectorIndex

func NewVectorIndex(dimensions int) *VectorIndex

NewVectorIndex creates a new vector similarity index for the given dimensions.

The index is initialized empty and ready to accept vectors of the specified dimensionality. All vectors added to the index must have exactly this number of dimensions.

Parameters:

  • dimensions: Number of dimensions for vectors (must be > 0)

Returns:

  • VectorIndex ready for use

Example:

// Create index for OpenAI embeddings (1536 dimensions)
index := search.NewVectorIndex(1536)

// Create index for sentence transformers (384 dimensions)
index = search.NewVectorIndex(384)

// Index is ready to accept vectors
index.Add("doc1", embedding1)

func (*VectorIndex) Add

func (v *VectorIndex) Add(id string, vec []float32) error

Add adds or updates a vector in the index with automatic normalization.

The vector is normalized to unit length for efficient cosine similarity computation. If a vector with the same ID already exists, it is replaced.

Parameters:

  • id: Unique identifier for the vector
  • vector: Vector to add (must match index dimensions)

Returns:

  • ErrDimensionMismatch if vector dimensions don't match index

Example:

// Add document embeddings
for docID, embedding := range documentEmbeddings {
	err := index.Add(docID, embedding)
	if err != nil {
		log.Printf("Failed to add %s: %v", docID, err)
	}
}

// Update existing vector
newEmbedding := getUpdatedEmbedding("doc1")
index.Add("doc1", newEmbedding) // Replaces previous

Performance:

  • Time: O(d) where d is vector dimensions
  • Space: O(d) additional storage per vector
  • Thread-safe: Uses write lock during update

Normalization:

Vectors are automatically normalized to unit length, so cosine
similarity becomes a simple dot product during search.

func (*VectorIndex) Clear

func (v *VectorIndex) Clear()

Clear removes all vectors from the index. This is useful when regenerating all embeddings to reset the index state.

func (*VectorIndex) Count

func (v *VectorIndex) Count() int

Count returns the number of vectors in the index.

func (*VectorIndex) GetDimensions

func (v *VectorIndex) GetDimensions() int

GetDimensions returns the vector dimensions.

func (*VectorIndex) GetVector

func (v *VectorIndex) GetVector(id string) ([]float32, bool)

GetVector returns a copy of the normalized vector for id, or (nil, false) if not found. Used when loading a graph-only HNSW index to populate vectors from the vector index.

func (*VectorIndex) HasVector

func (v *VectorIndex) HasVector(id string) bool

HasVector checks if a vector exists for the given ID.

func (*VectorIndex) Load

func (v *VectorIndex) Load(path string) error

Load replaces the vector index with the one stored at path (msgpack format). If the file does not exist or decode fails, the index is left empty (or unchanged on missing file) and no error is returned, so the caller can proceed with a full rebuild. Returns an error only for unexpected I/O (e.g. permission denied).

func (*VectorIndex) Remove

func (v *VectorIndex) Remove(id string)

Remove removes a vector from the index by its ID.

If the vector doesn't exist, this operation is a no-op.

Parameters:

  • id: Identifier of the vector to remove

Example:

// Remove a document that was deleted
index.Remove("doc-123")

// Remove multiple vectors
for _, docID := range deletedDocs {
	index.Remove(docID)
}

Performance:

  • Time: O(1) hash map deletion
  • Thread-safe: Uses write lock during removal

func (*VectorIndex) Save

func (v *VectorIndex) Save(path string) error

Save writes the vector index to path (msgpack format). Dir is created if needed. Copies index data under a short read lock so I/O does not block Search/IndexNode.

func (*VectorIndex) Search

func (v *VectorIndex) Search(ctx context.Context, query []float32, limit int, minSimilarity float64) ([]indexResult, error)

Search finds vectors similar to the query vector using cosine similarity.

The search computes cosine similarity between the query and all indexed vectors, filters by minimum similarity threshold, and returns the top results sorted by similarity score (highest first).

Parameters:

  • ctx: Context for cancellation and timeouts
  • query: Query vector (must match index dimensions)
  • limit: Maximum number of results to return
  • minSimilarity: Minimum similarity threshold (0.0 to 1.0)

Returns:

  • Slice of indexResult sorted by similarity (descending)
  • ErrDimensionMismatch if query dimensions don't match

Example:

// Search for top 10 most similar vectors
results, err := index.Search(ctx, queryVector, 10, 0.0)
if err != nil {
	log.Fatal(err)
}

// Search with high similarity threshold
results, err = index.Search(ctx, queryVector, 5, 0.8)
for _, result := range results {
	fmt.Printf("ID: %s, Similarity: %.3f\n", result.ID, result.Score)
}

// Search with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
results, err = index.Search(ctx, queryVector, 10, 0.7)

Performance:

  • Time: O(n×d) where n=vectors, d=dimensions
  • Space: O(k) where k=number of results
  • Cancellation: Respects context cancellation during search

Similarity Range:

  • 1.0: Identical vectors (same direction)
  • 0.0: Orthogonal vectors (perpendicular)
  • -1.0: Opposite vectors (opposite directions)

Thread Safety:

Uses read lock during search, allowing concurrent searches.

type VectorIndexPopulation

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

VectorIndexPopulation is the population of one schema vector index, from the commit that publishes the index to ONLINE or FAILED. The search service owns it. Populating an index means making it serve what storage holds: every stored node with the index's label (relationship of its type) whose property holds a vector the index can read is served with that vector.

The service holds the record of every index whose population it served: it is POPULATING from Begin, ONLINE once Populate served what storage holds, and FAILED, with the cause, when it could not. The committed drop of the index removes it (Retire) and a new population of the name replaces it, so an index keeps the outcome of its own population whatever the service's build does later. A name without one is an index this service did not populate, whose state is the service's own build state (vectorIndexBuildState): an index the service found published when it started (a restart, a restore, a replacement) is served by that build, so it is ONLINE once the build is ready, POPULATING while the build has not completed, and FAILED, with that build's error, when the build failed. Cypher answers such an index from storage until the build is ready.

func (*VectorIndexPopulation) Abort

func (p *VectorIndexPopulation) Abort()

Abort withdraws a population whose publishing commit failed: the name's previous record, if any, is current again.

func (*VectorIndexPopulation) Populate

func (p *VectorIndexPopulation) Populate(ctx context.Context, served bool) error

Populate makes the index serve what storage holds (populateVectorIndex) and records the outcome: ONLINE, or FAILED with what it could not serve as the cause. served is whether the index's queries read the service, decided by the queries' own source decision; an index they read from storage has nothing in the service to populate, so its record ends with it and its state stays the service's build.

func (*VectorIndexPopulation) Retire

func (p *VectorIndexPopulation) Retire()

Retire removes the record of an index whose drop has committed. A population of the name begun since then no longer restores it on Abort. A population still running is over, as an aborted one is: its waiters wake and find the name's current record, and its outcome is not recorded.

type VectorIndexTarget

type VectorIndexTarget struct {
	Label        string // the nodes' label, or the relationships' type
	Property     string
	Relationship bool
}

VectorIndexTarget is what a schema vector index reads: a vector property of the nodes with a label, or of the relationships of a type.

type VectorLookup

type VectorLookup func(id string) ([]float32, bool)

VectorLookup returns a vector by ID (e.g. from the vector index). Used when loading a graph-only HNSW file.

type VectorQueryHit

type VectorQueryHit struct {
	ID    string
	Score float64
}

VectorQueryHit is a lightweight result row for Cypher-compatible vector queries. ID is the node ID (not a chunk/named vector ID).

type VectorQuerySpec

type VectorQuerySpec struct {
	// IndexName is informational only (used for debugging/observability).
	IndexName string

	// Label optionally filters candidate nodes to those that have this label.
	Label string

	// Property is the Cypher vector index "property" name.
	//
	// Resolution semantics:
	//   1) Prefer NamedEmbeddings[Property] (or "default" when Property is empty)
	//   2) If Property is set, next try node.Properties[Property] as a vector array
	//   3) Fallback to ChunkEmbeddings[0..N] (best score across chunks)
	Property string

	// Similarity is the similarity function name. Supported values:
	// "cosine" (default), "dot", "euclidean".
	Similarity string

	// Limit is the maximum number of results to return (top-K).
	Limit int

	// ScoreScale is the scale of each hit's Score: Neo4j's (the zero value, for
	// Cypher) or the raw similarity (for the Qdrant API).
	ScoreScale VectorScoreScale

	// Exact evaluates every indexed node instead of an approximate candidate set.
	Exact bool
}

VectorQuerySpec describes how to resolve embeddings for a Cypher-style vector query.

This is intentionally a "core" representation of Cypher vector index metadata: the Cypher layer can remain syntax-compatible, while the search layer owns the implementation details and can choose the best execution strategy.

type VectorScoreScale

type VectorScoreScale int

VectorScoreScale is the scale a vector query reports its scores on. It never changes which nodes are returned or their order.

const (
	// VectorScoreNeo4j is Neo4j's scale for its vector indexes (#907): cosine
	// max((1 + cos) / 2, 0) and euclidean 1 / (1 + d²), both in [0, 1]; dot is
	// the dot product.
	VectorScoreNeo4j VectorScoreScale = iota
	// VectorScoreSimilarity is the raw similarity, as Qdrant reports it: the
	// cosine similarity in [-1, 1], the dot product, and for euclidean
	// 1 / (1 + d) (vector.EuclideanSimilarity).
	VectorScoreSimilarity
)

type VectorSearchPipeline

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

VectorSearchPipeline implements the unified vector search pipeline.

Pipeline stages:

  1. CandidateGen: Generate candidates (brute-force or HNSW)
  2. ExactScore: Re-score candidates exactly (CPU or GPU)
  3. Filter: Apply minSimilarity threshold
  4. TopK: Return top-k results

func NewVectorSearchPipeline

func NewVectorSearchPipeline(candidateGen CandidateGenerator, exactScorer ExactScorer) *VectorSearchPipeline

NewVectorSearchPipeline creates a new vector search pipeline.

func (*VectorSearchPipeline) Search

func (p *VectorSearchPipeline) Search(ctx context.Context, query []float32, k int, minSimilarity float64) ([]ScoredCandidate, error)

Search performs vector search using the pipeline.

Parameters:

  • ctx: Context for cancellation
  • query: Query vector (will be normalized)
  • k: Desired number of results
  • minSimilarity: Minimum similarity threshold

Returns:

  • candidates: Top-k candidates with exact scores
  • error: Context cancellation or other errors

type VectorSource

type VectorSource uint8

VectorSource is one kind of a node's vector sources that a Cypher vector query reads (VectorSourcePrecedence).

const (
	VectorSourceNamed    VectorSource = iota // the named embedding of the query's name
	VectorSourceAnyNamed                     // every named embedding (a query bound to no property)
	VectorSourceProperty                     // the vector-shaped value of the query's property
	VectorSourceChunks                       // the managed chunk embeddings
)

func VectorSourcePrecedence

func VectorSourcePrecedence(property string) []VectorSource

VectorSourcePrecedence is the one decision of which of a node's vector sources a Cypher vector query on property reads (Cypher precedence): its sources in order, of which the first that holds a vector the reader can read is the node's, and the later ones are not read. Every reader of the vector a query reads for a node follows it, each in its own representation: the candidate and exact queries over the service's entries, the scoring of stored nodes, the population that makes an index serve what storage holds (storedIndexVectors, indexVectorKeysLocked), and Cypher's scoring of a node it reads from storage. The returned order is shared and must not be changed.

type VectorStorageStatus

type VectorStorageStatus struct {
	Configured    string `json:"configured"`
	Active        string `json:"active"`
	Reason        string `json:"reason,omitempty"`
	ResidentBytes int64  `json:"resident_bytes"`
	LastRebuild   string `json:"last_rebuild_reason,omitempty"`
}

VectorStorageStatus is exposed through the existing database search status. RAM fallback is an operator-visible mode transition, not a successful disk admission. ResidentBytes is charged by the existing index accounting owner; actual RAM remains subject to the applied runtime/application memory limits.

type VulkanHNSWBuildAccelerator added in v1.1.11

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

VulkanHNSWBuildAccelerator uses Vulkan compute shaders for HNSW construction candidate search. The CPU still performs all graph mutation and reciprocal linking, so persisted artifacts remain compatible with CPU-built indexes.

func NewVulkanHNSWBuildAccelerator added in v1.1.11

func NewVulkanHNSWBuildAccelerator() (*VulkanHNSWBuildAccelerator, error)

NewVulkanHNSWBuildAccelerator creates a Vulkan-backed HNSW build accelerator.

func (*VulkanHNSWBuildAccelerator) AppendInserted

func (a *VulkanHNSWBuildAccelerator) AppendInserted(vecs [][]float32) error

AppendInserted uploads only the newly inserted normalized vectors.

func (*VulkanHNSWBuildAccelerator) CandidateSearch added in v1.1.11

func (a *VulkanHNSWBuildAccelerator) CandidateSearch(ctx context.Context, queries [][]float32, frontier [][]float32, topK int) ([][]int, [][]float32, error)

func (*VulkanHNSWBuildAccelerator) CandidateSearchGraph added in v1.1.11

func (a *VulkanHNSWBuildAccelerator) CandidateSearchGraph(ctx context.Context, queries [][]float32, graph *hnswBuildGraphSnapshot, topK int) ([][]uint32, [][]float32, error)

func (*VulkanHNSWBuildAccelerator) CandidateSearchInserted

func (a *VulkanHNSWBuildAccelerator) CandidateSearchInserted(ctx context.Context, queries [][]float32, topK int) ([][]uint32, [][]float32, error)

CandidateSearchInserted scores resident vectors without re-uploading the corpus.

func (*VulkanHNSWBuildAccelerator) Close added in v1.1.11

func (a *VulkanHNSWBuildAccelerator) Close() error

func (*VulkanHNSWBuildAccelerator) Prepare added in v1.1.11

func (a *VulkanHNSWBuildAccelerator) Prepare(dim int, _ int) error

func (*VulkanHNSWBuildAccelerator) ResidentReady

func (a *VulkanHNSWBuildAccelerator) ResidentReady() bool

ResidentReady reports whether device buffers can be retained for this build.

type WarmFunc added in v1.1.2

type WarmFunc func()

WarmFunc is the callback that EnsureWarm fires to request a synchronous build in the owner's long-lived context. The DB wires this at service creation time so the build is rooted in db.buildCtx (cancelled on DB close), independent of any caller's request context. Implementations MUST be idempotent — EnsureWarm uses its completion owner to fire it at most once per service lifetime, but the implementation is also free to be a no-op for already-warmed services as a defensive guard.

Source Files

Directories

Path Synopsis
Package stemmer defines NornicDB's dependency-free BM25 stemmer plugin ABI.
Package stemmer defines NornicDB's dependency-free BM25 stemmer plugin ABI.

Jump to

Keyboard shortcuts

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