1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
//! Hierarchical Navigable Small World (HNSW) approximate nearest neighbor search.
//!
//! The industry-standard graph-based ANN algorithm. Pure Rust with SIMD acceleration.
//!
//! # Quick Start
//!
//! ```rust,no_run
//! use jin::hnsw::HNSWIndex;
//!
//! fn main() -> Result<(), jin::RetrieveError> {
//! // dimension=128, M=16, ef_construction=200
//! let mut index = HNSWIndex::new(128, 16, 200)?;
//!
//! let v0 = vec![0.1; 128];
//! let v1 = vec![0.2; 128];
//! index.add_slice(0, &v0)?;
//! index.add_slice(1, &v1)?;
//! index.build()?;
//!
//! // k=10, ef_search=50
//! let q = vec![0.15; 128];
//! let results = index.search(&q, 10, 50)?;
//! Ok(())
//! }
//! ```
//!
//! # Parameter Recommendations
//!
//! | Dataset Size | M | ef_construction | ef_search | Memory/vector |
//! |--------------|---|-----------------|-----------|---------------|
//! | < 100K | 16 | 100 | 50 | ~1.2 KB |
//! | 100K - 1M | 16 | 200 | 100 | ~1.2 KB |
//! | 1M - 10M | 32 | 200 | 100-200 | ~2.4 KB |
//! | > 10M | 48 | 400 | 200+ | ~3.6 KB |
//!
//! **Memory formula**: `n × (d × 4 + M × 8 + overhead)` bytes
//! - For 1M vectors at d=768, M=16: ~3.5 GB
//!
//! # The Small-World Insight
//!
//! HNSW exploits the **small-world network property**: in well-constructed graphs,
//! any two nodes can be reached in O(log n) hops via greedy routing.
//!
//! ```text
//! Layer 3: [sparse] o───────────────o (long jumps, few nodes)
//! Layer 2: o───o───o───o───o───o (medium connections)
//! Layer 1: o─o─o─o─o─o─o─o─o─o─o─o─o (local connections)
//! Layer 0: ooooooooooooooooooooooooooo (all nodes, dense)
//! ```
//!
//! Search starts at sparse top layer, descends using each layer as a better starting point.
//!
//! # Parameter Effects
//!
//! | Parameter | Effect when increased |
//! |-----------|----------------------|
//! | **M** | Better recall, more memory, slower build |
//! | **ef_construction** | Better graph quality, slower build |
//! | **ef_search** | Better recall, slower search |
//!
//! # When NOT to Use HNSW
//!
//! - **< 10K vectors**: Brute force is faster (no graph overhead)
//! - **> 99.9% recall required**: Graph methods have a recall ceiling
//! - **Memory constrained + > 10M vectors**: Use IVF-PQ instead
//!
//! # Hierarchy in High Dimensions
//!
//! Research (2025-2026) shows hierarchy provides **minimal benefit for d > 32**.
//! In high dimensions, "hubs" emerge naturally and serve the same routing function.
//!
//! **Practical advice**: HNSW is still the safe default. The hierarchy overhead
//! is small, and the algorithm is battle-tested. Consider flat NSW only if you
//! specifically need to minimize memory.
//!
//! # Advanced Features
//!
//! - [`filtered`]: ACORN-style attribute filtering
//! - [`dual_branch`]: LID-based insertion with skip bridges (2025-2026)
//! - [`fused`]: Attribute-vector fusion for filtered search
//! - [`merge`]: Index merging algorithms (NGM, IGTM, CGTM)
//! - [`tombstones`]: Soft deletion for streaming workloads (FreshDiskANN-style)
//!
//! # Historical Lineage
//!
//! HNSW builds on a rich history of small-world network theory:
//!
//! | Year | Work | Contribution |
//! |------|------|--------------|
//! | 1967 | Milgram | "Six degrees of separation" experiment |
//! | 2000 | Kleinberg | Proved O(log²n) greedy routing possible on augmented grids |
//! | 2011 | Malkov et al. | NSW: flat navigable small-world graph for ANN |
//! | 2014 | Malkov et al. | Improved NSW with better neighbor selection |
//! | 2016 | Malkov & Yashunin | HNSW: hierarchical NSW with skip-list-like layers |
//!
//! **Kleinberg's insight** (2000): Random long-range edges enable efficient routing
//! if their probability decays as `P(distance) ∝ d^(-r)` with `r = dim` (dimension).
//! This explains why HNSW works: the hierarchical structure implicitly creates
//! this distance-dependent edge distribution.
//!
//! # References
//!
//! - Milgram (1967). "The Small World Problem." Psychology Today.
//! - Kleinberg (2000). "The Small-World Phenomenon: An Algorithmic Perspective."
//! - Malkov et al. (2014). "Approximate nearest neighbor algorithm based on
//! navigable small world graphs." Information Systems.
//! - Malkov & Yashunin (2016). "Efficient and robust approximate nearest neighbor
//! search using Hierarchical Navigable Small World graphs." IEEE TPAMI.
//! - [NSW hierarchy analysis](https://arxiv.org/abs/2412.01940) (2024)
//! - [Hub Highway Hypothesis](https://arxiv.org/abs/2502.00450) (2025)
// Compression fields are placeholders
pub
pub
pub
pub use ;
// Filtered search (ACORN-style)
pub use ;
// Graph repair (MN-RU algorithm for deletions)
pub use ;
// Vamana graph construction (DiskANN-style alpha-pruning)
pub use ;
// FusedANN: Attribute-vector fusion for filtered search
pub use ;
// Random Walk-based graph repair (alternative to MN-RU)
pub use ;
// Dynamic Edge Navigation Graph (DEG) for bimodal data
pub use ;
// In-place updates (IP-DiskANN style)
pub use ;
// Incremental learning patterns (edge refinement, temporal locality)
pub use ;
// Probabilistic edge routing (PEOs) for QPS improvement
pub use ;
// HNSW index merging algorithms (NGM, IGTM, CGTM)
pub use ;
// Dual-Branch HNSW with LID-based insertion and skip bridges (arXiv 2501.13992)
pub use ;
// Tombstone-based deletions for streaming updates (FreshDiskANN/IP-DiskANN inspired)
pub use ;
// =============================================================================
// Note on Streaming Updates
// =============================================================================
//
// For streaming workloads, combine HNSWIndex with TombstoneSet:
//
// ```rust,ignore
// let mut index = HNSWIndex::new(dim, m, ef)?;
// let mut tombstones = TombstoneSet::new(0.1); // 10% compaction threshold
//
// // Soft delete
// tombstones.delete(internal_id);
//
// // Filter search results
// let results = index.search(&query, k, ef)?;
// let filtered: Vec<_> = tombstones
// .filter_results(results.into_iter().map(|(id, d)| (id as usize, d)))
// .collect();
//
// // Periodic compaction when threshold reached
// if tombstones.should_compact(index.len()) {
// // Rebuild index without tombstoned nodes
// }
// ```