HNSW 26.9.5494

dotnet add package HNSW --version 26.9.5494
                    
NuGet\Install-Package HNSW -Version 26.9.5494
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="HNSW" Version="26.9.5494" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="HNSW" Version="26.9.5494" />
                    
Directory.Packages.props
<PackageReference Include="HNSW" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add HNSW --version 26.9.5494
                    
#r "nuget: HNSW, 26.9.5494"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package HNSW@26.9.5494
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=HNSW&version=26.9.5494
                    
Install as a Cake Addin
#tool nuget:?package=HNSW&version=26.9.5494
                    
Install as a Cake Tool

Build Status

<a href="https://curiosity.ai"><img src="https://curiosity.ai/media/cat.color.square.svg" width="100" height="100" align="right" /></a>

HNSW.Net

.Net library for fast approximate nearest neighbours search.

Exact k nearest neighbours search algorithms tend to perform poorly in high-dimensional spaces. To overcome curse of dimensionality the ANN algorithms come in place. This library implements one of such algorithms described in the "Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs" article. It provides simple API for building nearest neighbours graphs, (de)serializing them and running k-NN search queries.

Usage

Check out the following code snippets once you've added the library reference to your project.

How to build a graph?
var parameters = new SmallWorld<float[], float>.Parameters()
{
  M = 15,
  LevelLambda = 1 / Math.Log(15),
  EfSearch = 50,
};

float[] vectors = GetFloatVectors();
var graph = new SmallWorld<float[], float>(CosineDistance.NonOptimized);
graph.BuildGraph(vectors, new Random(42), parameters);
SmallWorld<float[], float> graph = GetGraph();

float[] query = Enumerable.Repeat(1f, 100).ToArray();
var best20 = graph.KNNSearch(query, 20);
var best1 = best20.OrderBy(r => r.Distance).First();
How to speed up search with early termination?

KNN search can stop traversing the graph once the result set has stopped improving, trading a little recall for fewer distance computations (see the Manticore write-up and "Patience in Proximity", Teofili & Lin, ECIR 2025). The savings grow with k and EfSearch. It is disabled by default.

var parameters = new SmallWorld<float[], float>.Parameters()
{
  EfSearch = 100,
  EnableEarlyTermination = true,             // turn the optimization on
  EarlyTerminationSaturationThreshold = 0.95, // optional: fraction of top-k left unchanged to count a hop as "non-improving"
  EarlyTerminationPatience = 0,               // optional: consecutive non-improving hops before stopping (0 = adaptive, scales with EfSearch)
};
How to (de)serialize the graph?

The graph is written without its items - the caller keeps those and hands them back on load, in the same order. Items the persisted graph does not cover come back as ItemsNotInGraph, so a crash between "items persisted" and "graph persisted" is recovered by re-adding them.

SmallWorld<float[], float> graph = GetGraph();
graph.OptimizeIfNeeded();          // flattens the connections; optional, but makes the write a span copy
graph.SerializeGraph(stream);      // parameters + edges, nothing else

// distance function must be the same as the one which was used for building the original graph
var (copy, itemsNotInGraph) = SmallWorld<float[], float>.DeserializeGraph(vectors, CosineDistance.NonOptimized, DefaultRandomGenerator.Instance, stream);
copy.AddItems(itemsNotInGraph);

There is also an IBufferWriter<byte> overload, for a caller that already has a pooled writer and a destination that takes a contiguous span (a key-value store's put, an encryption call):

var writer = new ArrayBufferWriter<byte>();
graph.SerializeGraph(writer);
db.Put(key, writer.WrittenSpan);

Format. Graphs are written in the flat HNSW2 format: a msgpack header and parameters, then each node's connections as one run of little-endian ints - the per-layer start offsets, the total, then the neighbour ids. That is byte for byte how the connections are already held in memory once the graph is flattened, so a save is a span copy per node and a load is a span fill per node, through a buffer rented from ArrayPool<byte>.Shared. Nothing is staged in memory at graph size and no per-node list is allocated in either direction. The older HNSW (MessagePack) format is still read, so existing files keep loading.

Distance functions

The only one distance function supplied by the library is the cosine distance. But there are 4 versions to address universality/performance tradeoff.

CosineDistance.NonOptimized // most generic version works for all cases
CosineDistance.ForUnits     // gives correct result only when arguments are "unit" vectors
CosineDistance.SIMD         // uses SIMD instructions to optimize calculations
CosineDistance.SIMDForUnits // uses SIMD and requires arguments to be "units"

But the API allows to inject any custom distance function tailored specifically for your needs.

Contributing

Your contributions and suggestions are very welcome! Please note that this project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

The contributions to this project are released to the public under the project's open source license. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

How to contribute

If you've found a bug or have a feature request then please open an issue with detailed description. We will be glad to see your pull requests as well.

  1. Prepare workspace.
git clone https://github.com/Microsoft/HNSW.Net.git
cd HNSW.Net
git checkout -b [username]/[feature]
  1. Update the library and add tests if needed.
  2. Build and test the changes.
cd Src
dotnet build
dotnet test
  1. Send the pull request from [username]/[feature] to master branch.
  2. Get approve and merge the changes.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA.

Releasing

The library is distributed as a bundle of sources. We are working on enabling CI and creating Nuget package for the project.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (5)

Showing the top 5 NuGet packages that depend on HNSW:

Package Downloads
mostlylucid.botdetection

Enterprise bot detection and anonymous entity resolution for ASP.NET Core — the detection engine behind StyloBot. Probabilistic and behavioural, not just User-Agent matching: UA/header/IP analysis, JA3/JA4/HTTP2/QUIC/TCP-IP fingerprinting, Leiden cluster discovery, 129-dim Markov session vectors, metastable fingerprint identity, and optional LLM classification. Zero-PII (HMAC-SHA256), SQLite-backed, single-call UseStyloBot() setup.

LLM.Guard

Easily implement guardrails around LLM prompts.

IndxSearchLib

A new type of search system with pattern recognition. Enterprise-grade search in a class library.

Iciclecreek.Lucene.Net.Vector

Adds support for vector embeddings to Lucene.Net 4.8, supporting similarity search and RAG patterns.

ToolUp.VectorStores.Hnsw

HNSW approximate-nearest-neighbour IVectorStore for ToolUp.RAG. Lifts the ~50,000-chunk ceiling of InMemoryVectorStore.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
26.9.5494 473 9/19/2026
26.9.5484 100 9/18/2026
26.6.1848 14,897 6/13/2026
26.6.1827 217 6/12/2026
26.6.1714 255 6/9/2026
26.6.1655 259 6/8/2026
26.4.177 15,368 4/1/2026
26.3.129 351 3/30/2026
26.3.126 200 3/30/2026
26.1.63669 6,973 1/22/2026
26.1.63655 204 1/22/2026
25.12.63133 2,237 12/9/2025
25.12.63132 625 12/9/2025
25.7.60036 5,485 7/30/2025
25.7.59928 705 7/24/2025
25.3.56901 10,124 3/20/2025
24.9.52330 49,840 9/24/2024
1.0.52302 1,062 9/23/2024
1.0.52255 320 9/23/2024
1.0.52254 328 9/23/2024
Loading failed