Add a vector to the index. Returns the assigned ID.
(&mut self, vector: &[f32])
| 100 | |
| 101 | /// Add a vector to the index. Returns the assigned ID. |
| 102 | pub fn add(&mut self, vector: &[f32]) -> u32 { |
| 103 | assert_eq!(vector.len(), self.dim); |
| 104 | let pq = self |
| 105 | .pq |
| 106 | .as_ref() |
| 107 | .expect("index must be trained before add()"); |
| 108 | |
| 109 | let cell = self.nearest_centroid(vector); |
| 110 | let residual: Vec<f32> = vector |
| 111 | .iter() |
| 112 | .zip(&self.centroids[cell]) |
| 113 | .map(|(a, b)| a - b) |
| 114 | .collect(); |
| 115 | let code = pq.encode(&residual); |
| 116 | let id = self.count; |
| 117 | self.cells[cell].push((id, code)); |
| 118 | self.count += 1; |
| 119 | id |
| 120 | } |
| 121 | |
| 122 | /// Batch add vectors. |
| 123 | pub fn add_batch(&mut self, vectors: &[&[f32]]) { |