Brute-force k-NN search. Exact results — no approximation.
(&self, query: &[f32], top_k: usize)
| 115 | |
| 116 | /// Brute-force k-NN search. Exact results — no approximation. |
| 117 | pub fn search(&self, query: &[f32], top_k: usize) -> Vec<SearchResult> { |
| 118 | assert_eq!(query.len(), self.dim); |
| 119 | let n = self.len(); |
| 120 | if n == 0 || top_k == 0 { |
| 121 | return Vec::new(); |
| 122 | } |
| 123 | |
| 124 | let mut candidates: Vec<SearchResult> = Vec::with_capacity(n.min(top_k * 2)); |
| 125 | for i in 0..n { |
| 126 | if self.deleted[i] { |
| 127 | continue; |
| 128 | } |
| 129 | let start = i * self.dim; |
| 130 | let vec_slice = &self.data[start..start + self.dim]; |
| 131 | let dist = distance(query, vec_slice, self.metric); |
| 132 | candidates.push(SearchResult { |
| 133 | id: i as u32, |
| 134 | distance: dist, |
| 135 | }); |
| 136 | } |
| 137 | |
| 138 | if candidates.len() > top_k { |
| 139 | candidates.select_nth_unstable_by(top_k, |a, b| { |
| 140 | a.distance |
| 141 | .partial_cmp(&b.distance) |
| 142 | .unwrap_or(std::cmp::Ordering::Equal) |
| 143 | }); |
| 144 | candidates.truncate(top_k); |
| 145 | } |
| 146 | candidates.sort_by(|a, b| { |
| 147 | a.distance |
| 148 | .partial_cmp(&b.distance) |
| 149 | .unwrap_or(std::cmp::Ordering::Equal) |
| 150 | }); |
| 151 | candidates |
| 152 | } |
| 153 | |
| 154 | /// Search with a pre-filter bitmap (byte-array format). |
| 155 | pub fn search_filtered(&self, query: &[f32], top_k: usize, bitmap: &[u8]) -> Vec<SearchResult> { |