HnswIndex class
Approximate nearest-neighbor index using an HNSW graph. Same public shape as FlatIndex — you can swap it in wherever brute-force gets too slow. Search cost is O(log N · efSearch · d) instead of O(N · d), at the price of small recall loss controlled by efSearch.
Parameters mirror FAISS IndexHNSWFlat:
M— max neighbors per node above layer 0 (layer 0 gets2*M). Larger = better recall / more memory. Typical: 8–48.- efConstruction — build-time beam width. Larger = better graph, slower add. Typical: 40–200.
- efSearch — query-time beam width. Larger = better recall,
slower search. Tunable per-search via search's
efargument.
Metric semantics: VectorMetric.l2 and VectorMetric.l2sq both use
squared L2 internally for ranking; the visible distance is sqrt'd
for l2 at the end. VectorMetric.innerProduct flips comparisons
(larger = closer); VectorMetric.cosine is normalized-ip distance.
Constructors
Properties
- defaultMetric → VectorMetric
-
final
- dim → int
-
final
- efConstruction ↔ int
-
getter/setter pair
- efSearch ↔ int
-
getter/setter pair
- hashCode → int
-
The hash code for this object.
no setterinherited
- length → int
-
no setter
- liveCount → int
-
no setter
-
liveIds
→ Iterable<
Object?> -
V50: snapshot of live (non-tombstoned) ids, insertion order.
no setter
- m → int
-
final
- mMax0 → int
-
final
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- tombstoneCount → int
-
no setter
- tombstoneRatio → double
-
no setter
Methods
-
add(
Object? id, Vector v) → void -
Add
vunder keyid. Runs one graph-insertion step; not thread safe. Ids need not be unique, but removeId removes only the first match. -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
removeId(
Object? id) → bool -
Remove the first entry whose id equals
id. Returns true if removed. This is a soft-delete (the node stays in the graph as a tombstone) — the vector is zeroed and the id set to a sentinel so search skips it. HNSW does not support cheap true deletion. -
search(
Vector query, int k, {VectorMetric? metric, int? ef}) → List< VectorSearchHit> -
Search for
knearest neighbors ofqueryundermetric(or defaultMetric). Optional per-callefoverrides efSearch. Result is sorted best-first. -
toJson(
) → Map< String, Object?> -
Serialize the built graph. Excludes the RNG state — subsequent
add()calls on a reloaded index will follow a fresh sequence, which is harmless because level assignments are heuristic. -
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited