1use futures::StreamExt;
2use mongodb::bson::{self, Bson, Document, doc};
3
4use rig::{
5 Embed, OneOrMany,
6 embeddings::embedding::{Embedding, EmbeddingModel},
7 vector_store::{
8 InsertDocuments, VectorStoreError, VectorStoreIndex,
9 request::{SearchFilter, VectorSearchRequest},
10 },
11};
12use serde::{Deserialize, Serialize};
13
14#[derive(Debug, Serialize, Deserialize)]
15#[serde(rename_all = "camelCase")]
16struct SearchIndex {
17 id: String,
18 name: String,
19 #[serde(rename = "type")]
20 index_type: String,
21 status: String,
22 queryable: bool,
23 latest_definition: LatestDefinition,
24}
25
26impl SearchIndex {
27 async fn get_search_index<C: Send + Sync>(
28 collection: mongodb::Collection<C>,
29 index_name: &str,
30 ) -> Result<SearchIndex, VectorStoreError> {
31 collection
32 .list_search_indexes()
33 .name(index_name)
34 .await
35 .map_err(mongodb_to_rig_error)?
36 .with_type::<SearchIndex>()
37 .next()
38 .await
39 .transpose()
40 .map_err(mongodb_to_rig_error)?
41 .ok_or(VectorStoreError::DatastoreError("Index not found".into()))
42 }
43}
44
45#[derive(Debug, Serialize, Deserialize)]
46struct LatestDefinition {
47 fields: Vec<Field>,
48}
49
50#[derive(Debug, Serialize, Deserialize)]
51#[serde(rename_all = "camelCase")]
52struct Field {
53 #[serde(rename = "type")]
54 field_type: String,
55 path: String,
56 num_dimensions: i32,
57 similarity: String,
58}
59
60fn mongodb_to_rig_error(e: mongodb::error::Error) -> VectorStoreError {
61 VectorStoreError::DatastoreError(Box::new(e))
62}
63
64pub struct MongoDbVectorIndex<C, M>
107where
108 C: Send + Sync,
109 M: EmbeddingModel,
110{
111 collection: mongodb::Collection<C>,
112 model: M,
113 index_name: String,
114 embedded_field: String,
115 search_params: SearchParams,
116}
117
118impl<C, M> MongoDbVectorIndex<C, M>
119where
120 C: Send + Sync,
121 M: EmbeddingModel,
122{
123 fn pipeline_search_stage(
126 &self,
127 prompt_embedding: &Embedding,
128 req: &VectorSearchRequest<MongoDbSearchFilter>,
129 ) -> bson::Document {
130 let SearchParams {
131 exact,
132 num_candidates,
133 } = &self.search_params;
134
135 let samples = req.samples() as usize;
136
137 let thresh = req
138 .threshold()
139 .map(|thresh| MongoDbSearchFilter::gte("score".into(), thresh.into()));
140
141 let filter = match (thresh, req.filter()) {
142 (Some(thresh), Some(filt)) => thresh.and(filt.clone()).into_inner(),
143 (Some(thresh), _) => thresh.into_inner(),
144 (_, Some(filt)) => filt.clone().into_inner(),
145 _ => Default::default(),
146 };
147
148 doc! {
149 "$vectorSearch": {
150 "index": &self.index_name,
151 "path": self.embedded_field.clone(),
152 "queryVector": &prompt_embedding.vec,
153 "numCandidates": num_candidates.unwrap_or((samples * 10) as u32),
154 "limit": samples as u32,
155 "filter": filter,
156 "exact": exact.unwrap_or(false)
157 }
158 }
159 }
160
161 fn pipeline_score_stage(&self) -> bson::Document {
164 doc! {
165 "$addFields": {
166 "score": { "$meta": "vectorSearchScore" }
167 }
168 }
169 }
170}
171
172impl<C, M> MongoDbVectorIndex<C, M>
173where
174 M: EmbeddingModel,
175 C: Send + Sync,
176{
177 pub async fn new(
182 collection: mongodb::Collection<C>,
183 model: M,
184 index_name: &str,
185 search_params: SearchParams,
186 ) -> Result<Self, VectorStoreError> {
187 let search_index = SearchIndex::get_search_index(collection.clone(), index_name).await?;
188
189 if !search_index.queryable {
190 return Err(VectorStoreError::DatastoreError(
191 "Index is not queryable".into(),
192 ));
193 }
194
195 let embedded_field = search_index
196 .latest_definition
197 .fields
198 .into_iter()
199 .map(|field| field.path)
200 .next()
201 .ok_or(VectorStoreError::DatastoreError(
203 "No embedded fields found".into(),
204 ))?;
205
206 Ok(Self {
207 collection,
208 model,
209 index_name: index_name.to_string(),
210 embedded_field,
211 search_params,
212 })
213 }
214}
215
216#[derive(Default)]
219pub struct SearchParams {
220 exact: Option<bool>,
221 num_candidates: Option<u32>,
222}
223
224impl SearchParams {
225 pub fn new() -> Self {
227 Self {
228 exact: None,
229 num_candidates: None,
230 }
231 }
232
233 pub fn exact(mut self, exact: bool) -> Self {
238 self.exact = Some(exact);
239 self
240 }
241
242 pub fn num_candidates(mut self, num_candidates: u32) -> Self {
247 self.num_candidates = Some(num_candidates);
248 self
249 }
250}
251
252#[derive(Clone, Debug)]
253pub struct MongoDbSearchFilter(Document);
254
255impl SearchFilter for MongoDbSearchFilter {
256 type Value = Bson;
257
258 fn eq(key: String, value: Self::Value) -> Self {
259 Self(doc! { key: value })
260 }
261
262 fn gt(key: String, value: Self::Value) -> Self {
263 Self(doc! { key: { "$gt": value } })
264 }
265
266 fn lt(key: String, value: Self::Value) -> Self {
267 Self(doc! { key: { "$lt": value } })
268 }
269
270 fn and(self, rhs: Self) -> Self {
271 Self(doc! { "$and": [ self.0, rhs.0 ]})
272 }
273
274 fn or(self, rhs: Self) -> Self {
275 Self(doc! { "$or": [ self.0, rhs.0 ]})
276 }
277}
278
279impl MongoDbSearchFilter {
280 fn into_inner(self) -> Document {
281 self.0
282 }
283
284 pub fn gte(key: String, value: <Self as SearchFilter>::Value) -> Self {
285 Self(doc! { key: { "$gte": value } })
286 }
287
288 pub fn lte(key: String, value: <Self as SearchFilter>::Value) -> Self {
289 Self(doc! { key: { "$lte": value } })
290 }
291
292 #[allow(clippy::should_implement_trait)]
293 pub fn not(self) -> Self {
294 Self(doc! { "$nor": [self.0] })
295 }
296
297 pub fn is_type(key: String, typ: &'static str) -> Self {
299 Self(doc! { key: { "$type": typ } })
300 }
301
302 pub fn size(key: String, size: i32) -> Self {
303 Self(doc! { key: { "$size": size } })
304 }
305
306 pub fn all(key: String, values: Vec<Bson>) -> Self {
308 Self(doc! { key: { "$all": values } })
309 }
310
311 pub fn any(key: String, condition: Document) -> Self {
312 Self(doc! { key: { "$elemMatch": condition } })
313 }
314}
315
316impl<C, M> VectorStoreIndex for MongoDbVectorIndex<C, M>
317where
318 C: Sync + Send,
319 M: EmbeddingModel + Sync + Send,
320{
321 type Filter = MongoDbSearchFilter;
322
323 async fn top_n<T: for<'a> Deserialize<'a> + Send>(
327 &self,
328 req: VectorSearchRequest<MongoDbSearchFilter>,
329 ) -> Result<Vec<(f64, String, T)>, VectorStoreError> {
330 let prompt_embedding = self.model.embed_text(req.query()).await?;
331
332 let pipeline = vec![
333 self.pipeline_search_stage(&prompt_embedding, &req),
334 self.pipeline_score_stage(),
335 doc! {
336 "$project": {
337 self.embedded_field.clone(): 0
338 }
339 },
340 ];
341
342 let mut cursor = self
343 .collection
344 .aggregate(pipeline)
345 .await
346 .map_err(mongodb_to_rig_error)?
347 .with_type::<serde_json::Value>();
348
349 let mut results = Vec::new();
350 while let Some(doc) = cursor.next().await {
351 let doc = doc.map_err(mongodb_to_rig_error)?;
352 let score = doc.get("score").expect("score").as_f64().expect("f64");
353 let id = doc.get("_id").expect("_id").to_string();
354 let doc_t: T = serde_json::from_value(doc).map_err(VectorStoreError::JsonError)?;
355 results.push((score, id, doc_t));
356 }
357
358 tracing::info!(target: "rig",
359 "Selected documents: {}",
360 results.iter()
361 .map(|(distance, id, _)| format!("{id} ({distance})"))
362 .collect::<Vec<String>>()
363 .join(", ")
364 );
365
366 Ok(results)
367 }
368
369 async fn top_n_ids(
371 &self,
372 req: VectorSearchRequest<MongoDbSearchFilter>,
373 ) -> Result<Vec<(f64, String)>, VectorStoreError> {
374 let prompt_embedding = self.model.embed_text(req.query()).await?;
375
376 let pipeline = vec![
377 self.pipeline_search_stage(&prompt_embedding, &req),
378 self.pipeline_score_stage(),
379 doc! {
380 "$project": {
381 "_id": 1,
382 "score": 1
383 },
384 },
385 ];
386
387 let mut cursor = self
388 .collection
389 .aggregate(pipeline)
390 .await
391 .map_err(mongodb_to_rig_error)?
392 .with_type::<serde_json::Value>();
393
394 let mut results = Vec::new();
395 while let Some(doc) = cursor.next().await {
396 let doc = doc.map_err(mongodb_to_rig_error)?;
397 let score = doc.get("score").expect("score").as_f64().expect("f64");
398 let id = doc.get("_id").expect("_id").to_string();
399 results.push((score, id));
400 }
401
402 tracing::info!(target: "rig",
403 "Selected documents: {}",
404 results.iter()
405 .map(|(distance, id)| format!("{id} ({distance})"))
406 .collect::<Vec<String>>()
407 .join(", ")
408 );
409
410 Ok(results)
411 }
412}
413
414impl<C, M> InsertDocuments for MongoDbVectorIndex<C, M>
415where
416 C: Send + Sync,
417 M: EmbeddingModel + Send + Sync,
418{
419 async fn insert_documents<Doc: Serialize + Embed + Send>(
420 &self,
421 documents: Vec<(Doc, OneOrMany<Embedding>)>,
422 ) -> Result<(), VectorStoreError> {
423 let mongo_documents = documents
424 .into_iter()
425 .map(|(document, embeddings)| -> Result<Vec<mongodb::bson::Document>, VectorStoreError> {
426 let json_doc = serde_json::to_value(&document)?;
427
428 embeddings.into_iter().map(|embedding| -> Result<mongodb::bson::Document, VectorStoreError> {
429 Ok(doc! {
430 "document": mongodb::bson::to_bson(&json_doc).map_err(|e| VectorStoreError::DatastoreError(Box::new(e)))?,
431 "embedding": embedding.vec,
432 "embedded_text": embedding.document,
433 })
434 }).collect::<Result<Vec<_>, _>>()
435 })
436 .collect::<Result<Vec<Vec<_>>, _>>()?
437 .into_iter()
438 .flatten()
439 .collect::<Vec<_>>();
440
441 let collection = self.collection.clone_with_type::<mongodb::bson::Document>();
442
443 collection
444 .insert_many(mongo_documents)
445 .await
446 .map_err(mongodb_to_rig_error)?;
447
448 Ok(())
449 }
450}