1use std::ops::Range;
13
14use serde::{Deserialize, Serialize};
15
16use crate::markers::{Missing, Provided};
17
18#[derive(Clone, Serialize, Deserialize, Debug)]
23pub struct VectorSearchRequest<F = Filter<serde_json::Value>> {
24 query: String,
26 samples: u64,
28 #[serde(default, deserialize_with = "crate::json_utils::floats")]
30 threshold: Option<f64>,
31 filter: Option<F>,
33}
34
35impl<Filter> VectorSearchRequest<Filter> {
36 pub fn builder() -> VectorSearchRequestBuilder<Filter> {
38 VectorSearchRequestBuilder::<Filter>::default()
39 }
40
41 pub fn query(&self) -> &str {
43 &self.query
44 }
45
46 pub fn samples(&self) -> u64 {
48 self.samples
49 }
50
51 pub fn threshold(&self) -> Option<f64> {
53 self.threshold
54 }
55
56 pub fn filter(&self) -> Option<&Filter> {
58 self.filter.as_ref()
59 }
60
61 pub fn map_filter<T, F>(self, f: F) -> VectorSearchRequest<T>
66 where
67 F: Fn(Filter) -> T,
68 {
69 VectorSearchRequest {
70 query: self.query,
71 samples: self.samples,
72 threshold: self.threshold,
73 filter: self.filter.map(f),
74 }
75 }
76
77 pub fn try_map_filter<T, F>(self, f: F) -> Result<VectorSearchRequest<T>, FilterError>
81 where
82 F: Fn(Filter) -> Result<T, FilterError>,
83 {
84 let filter = self.filter.map(f).transpose()?;
85
86 Ok(VectorSearchRequest {
87 query: self.query,
88 samples: self.samples,
89 threshold: self.threshold,
90 filter,
91 })
92 }
93}
94
95#[derive(Debug, Clone, thiserror::Error)]
97pub enum FilterError {
98 #[error("Expected: {expected}, got: {got}")]
99 Expected { expected: String, got: String },
100
101 #[error("Cannot compile '{0}' to the backend's filter type")]
102 TypeError(String),
103
104 #[error("Missing field '{0}'")]
105 MissingField(String),
106
107 #[error("'{0}' must {1}")]
108 Must(String, String),
109
110 #[error("Filter serialization failed: {0}")]
112 Serialization(String),
113}
114
115pub trait SearchFilter {
121 type Value;
122
123 fn eq(key: impl AsRef<str>, value: Self::Value) -> Self;
124 fn gt(key: impl AsRef<str>, value: Self::Value) -> Self;
125 fn lt(key: impl AsRef<str>, value: Self::Value) -> Self;
126 fn and(self, rhs: Self) -> Self;
127 fn or(self, rhs: Self) -> Self;
128}
129
130#[derive(Clone, Debug, Serialize, Deserialize)]
139pub struct SqlCondition<P> {
140 condition: String,
141 params: Vec<P>,
142 #[serde(default)]
143 placeholders: Vec<Range<usize>>,
144}
145
146impl<P> Default for SqlCondition<P> {
149 fn default() -> Self {
150 Self::raw(String::new())
151 }
152}
153
154impl<P> SqlCondition<P> {
155 pub fn binary(key: impl AsRef<str>, op: &str, placeholder: &str, value: P) -> Self {
158 let mut this = Self::raw(format!("{} {op} ", key.as_ref()));
159 this.push_placeholder(placeholder);
160 this.params.push(value);
161 this
162 }
163
164 pub fn list(key: impl AsRef<str>, op: &str, placeholder: &str, values: Vec<P>) -> Self {
167 let mut this = Self::raw(format!("{} {op} (", key.as_ref()));
168 for i in 0..values.len() {
169 if i > 0 {
170 this.condition.push_str(", ");
171 }
172 this.push_placeholder(placeholder);
173 }
174 this.condition.push(')');
175 this.params = values;
176 this
177 }
178
179 pub fn range(key: impl AsRef<str>, placeholder: &str, lo: P, hi: P) -> Self {
182 let key = key.as_ref();
183 let mut this = Self::raw(format!("{key} >= "));
184 this.push_placeholder(placeholder);
185 this.condition.push_str(&format!(" AND {key} <= "));
186 this.push_placeholder(placeholder);
187 this.params = vec![lo, hi];
188 this
189 }
190
191 pub fn between(key: impl AsRef<str>, placeholder: &str, lo: P, hi: P) -> Self {
194 let mut this = Self::raw(format!("{} between ", key.as_ref()));
195 this.push_placeholder(placeholder);
196 this.condition.push_str(" and ");
197 this.push_placeholder(placeholder);
198 this.params = vec![lo, hi];
199 this
200 }
201
202 pub fn raw(condition: impl Into<String>) -> Self {
205 Self {
206 condition: condition.into(),
207 params: Vec::new(),
208 placeholders: Vec::new(),
209 }
210 }
211
212 pub fn and(self, rhs: Self) -> Self {
214 self.combine("AND", rhs)
215 }
216
217 pub fn or(self, rhs: Self) -> Self {
219 self.combine("OR", rhs)
220 }
221
222 pub fn not(self) -> Self {
224 let mut this = Self::raw("NOT (");
225 this.append(self);
226 this.condition.push(')');
227 this
228 }
229
230 fn combine(self, joiner: &str, rhs: Self) -> Self {
231 let mut this = Self::raw("(");
232 this.append(self);
233 this.condition.push_str(&format!(") {joiner} ("));
234 this.append(rhs);
235 this.condition.push(')');
236 this
237 }
238
239 fn push_placeholder(&mut self, placeholder: &str) {
240 let start = self.condition.len();
241 self.condition.push_str(placeholder);
242 self.placeholders.push(start..self.condition.len());
243 }
244
245 fn append(&mut self, other: Self) {
246 let offset = self.condition.len();
247 self.condition.push_str(&other.condition);
248 self.params.extend(other.params);
249 self.placeholders.extend(
250 other
251 .placeholders
252 .into_iter()
253 .map(|range| range.start + offset..range.end + offset),
254 );
255 }
256
257 pub fn condition(&self) -> &str {
259 &self.condition
260 }
261
262 pub fn params(&self) -> &[P] {
264 &self.params
265 }
266
267 pub fn render_placeholders<D: std::fmt::Display>(
273 &self,
274 mut placeholder: impl FnMut(usize) -> D,
275 ) -> String {
276 use std::fmt::Write as _;
277
278 let mut out = String::with_capacity(self.condition.len() + 2 * self.placeholders.len());
279 let mut copied = 0;
280 for (i, range) in self.placeholders.iter().enumerate() {
281 let (Some(before), Some(_)) = (
284 self.condition.get(copied..range.start),
285 self.condition.get(range.clone()),
286 ) else {
287 continue;
288 };
289 out.push_str(before);
290 let _ = write!(out, "{}", placeholder(i));
291 copied = range.end;
292 }
293 out.push_str(self.condition.get(copied..).unwrap_or_default());
294 out
295 }
296
297 pub fn into_parts(self) -> (String, Vec<P>) {
299 (self.condition, self.params)
300 }
301}
302
303pub trait DynamicSearchFilter: SearchFilter + Sized {
311 fn from_dynamic_filter(filter: Filter<serde_json::Value>) -> Result<Self, FilterError>;
313
314 fn normalize_dynamic_document(document: serde_json::Value) -> serde_json::Value {
320 document
321 }
322}
323
324impl<F> DynamicSearchFilter for F
325where
326 F: SearchFilter<Value = serde_json::Value>,
327{
328 fn from_dynamic_filter(filter: Filter<serde_json::Value>) -> Result<Self, FilterError> {
329 Ok(filter.interpret())
330 }
331
332 fn normalize_dynamic_document(document: serde_json::Value) -> serde_json::Value {
333 prune_document(document).unwrap_or_default()
334 }
335}
336
337fn prune_document(document: serde_json::Value) -> Option<serde_json::Value> {
338 match document {
339 serde_json::Value::Object(mut map) => {
340 let new_map = map
341 .iter_mut()
342 .filter_map(|(key, value)| {
343 prune_document(value.take()).map(|value| (key.clone(), value))
344 })
345 .collect::<serde_json::Map<_, _>>();
346
347 Some(serde_json::Value::Object(new_map))
348 }
349 serde_json::Value::Array(vec) if vec.len() > 400 => None,
350 serde_json::Value::Array(vec) => Some(serde_json::Value::Array(
351 vec.into_iter().filter_map(prune_document).collect(),
352 )),
353 value => Some(value),
354 }
355}
356
357#[derive(Debug, Clone, Serialize, Deserialize)]
362#[serde(rename_all = "lowercase")]
363pub enum Filter<V>
364where
365 V: std::fmt::Debug + Clone,
366{
367 Eq(String, V),
368 Gt(String, V),
369 Lt(String, V),
370 And(Box<Self>, Box<Self>),
371 Or(Box<Self>, Box<Self>),
372}
373
374impl<V> SearchFilter for Filter<V>
375where
376 V: std::fmt::Debug + Clone + Serialize + serde::de::DeserializeOwned,
377{
378 type Value = V;
379
380 fn eq(key: impl AsRef<str>, value: Self::Value) -> Self {
382 Self::Eq(key.as_ref().to_owned(), value)
383 }
384
385 fn gt(key: impl AsRef<str>, value: Self::Value) -> Self {
387 Self::Gt(key.as_ref().to_owned(), value)
388 }
389
390 fn lt(key: impl AsRef<str>, value: Self::Value) -> Self {
392 Self::Lt(key.as_ref().to_owned(), value)
393 }
394
395 fn and(self, rhs: Self) -> Self {
397 Self::And(self.into(), rhs.into())
398 }
399
400 fn or(self, rhs: Self) -> Self {
402 Self::Or(self.into(), rhs.into())
403 }
404}
405
406impl<V> Filter<V>
407where
408 V: std::fmt::Debug + Clone,
409{
410 pub fn interpret<F>(self) -> F
412 where
413 F: SearchFilter<Value = V>,
414 {
415 self.interpret_with(|v| v)
416 }
417
418 pub fn interpret_with<F, W>(self, conv: impl Fn(V) -> W + Copy) -> F
421 where
422 F: SearchFilter<Value = W>,
423 {
424 match self.try_interpret(|v| Ok::<W, std::convert::Infallible>(conv(v))) {
425 Ok(filter) => filter,
426 Err(never) => match never {},
427 }
428 }
429
430 pub fn try_interpret<F, W, E>(self, conv: impl Fn(V) -> Result<W, E> + Copy) -> Result<F, E>
433 where
434 F: SearchFilter<Value = W>,
435 {
436 Ok(match self {
437 Self::Eq(key, val) => F::eq(key, conv(val)?),
438 Self::Gt(key, val) => F::gt(key, conv(val)?),
439 Self::Lt(key, val) => F::lt(key, conv(val)?),
440 Self::And(lhs, rhs) => F::and(lhs.try_interpret(conv)?, rhs.try_interpret(conv)?),
441 Self::Or(lhs, rhs) => F::or(lhs.try_interpret(conv)?, rhs.try_interpret(conv)?),
442 })
443 }
444}
445
446impl Filter<serde_json::Value> {
447 pub fn satisfies(&self, value: &serde_json::Value) -> bool {
454 use Filter::*;
455 use serde_json::{Value, Value::*};
456 use std::cmp::Ordering;
457
458 fn compare_pair(l: &Value, r: &Value) -> Option<Ordering> {
459 match (l, r) {
460 (Number(l), Number(r)) => crate::json_utils::compare_numbers(l, r),
461 (String(l), String(r)) => Some(l.cmp(r)),
462 (Null, Null) => Some(Ordering::Equal),
463 (Bool(l), Bool(r)) => Some(l.cmp(r)),
464 _ => None,
465 }
466 }
467
468 match self {
469 Eq(k, v) => value
473 .get(k)
474 .is_some_and(|field| compare_pair(field, v) == Some(Ordering::Equal) || field == v),
475 Gt(k, v) => value
476 .get(k)
477 .and_then(|field| compare_pair(field, v))
478 .is_some_and(|ord| ord == Ordering::Greater),
479 Lt(k, v) => value
480 .get(k)
481 .and_then(|field| compare_pair(field, v))
482 .is_some_and(|ord| ord == Ordering::Less),
483 And(l, r) => l.satisfies(value) && r.satisfies(value),
484 Or(l, r) => l.satisfies(value) || r.satisfies(value),
485 }
486 }
487}
488
489#[derive(Clone, Serialize, Deserialize, Debug)]
491pub struct VectorSearchRequestBuilder<F = Filter<serde_json::Value>, Q = Missing, S = Missing> {
492 query: Q,
493 samples: S,
494 threshold: Option<f64>,
495 filter: Option<F>,
496}
497
498impl<F> Default for VectorSearchRequestBuilder<F, Missing, Missing> {
499 fn default() -> Self {
500 Self {
501 query: Missing,
502 samples: Missing,
503 threshold: None,
504 filter: None,
505 }
506 }
507}
508
509impl<F, Q, S> VectorSearchRequestBuilder<F, Q, S>
510where
511 F: SearchFilter,
512{
513 pub fn query<T>(self, query: T) -> VectorSearchRequestBuilder<F, Provided<String>, S>
515 where
516 T: Into<String>,
517 {
518 VectorSearchRequestBuilder {
519 query: Provided(query.into()),
520 samples: self.samples,
521 threshold: self.threshold,
522 filter: self.filter,
523 }
524 }
525
526 pub fn samples(self, samples: u64) -> VectorSearchRequestBuilder<F, Q, Provided<u64>> {
528 VectorSearchRequestBuilder {
529 query: self.query,
530 samples: Provided(samples),
531 threshold: self.threshold,
532 filter: self.filter,
533 }
534 }
535
536 pub fn threshold(mut self, threshold: f64) -> Self {
538 self.threshold = Some(threshold);
539 self
540 }
541
542 pub fn filter(mut self, filter: F) -> Self {
544 self.filter = Some(filter);
545 self
546 }
547}
548
549impl<F> VectorSearchRequestBuilder<F, Provided<String>, Provided<u64>> {
550 pub fn build(self) -> VectorSearchRequest<F> {
552 VectorSearchRequest {
553 query: self.query.0,
554 samples: self.samples.0,
555 threshold: self.threshold,
556 filter: self.filter,
557 }
558 }
559}
560
561#[cfg(test)]
562mod tests;