Skip to main content

rig_core/vector_store/
request.rs

1//! Vector-search requests and composable metadata filters.
2//!
3//! ```
4//! use rig_core::vector_store::request::{VectorSearchRequest, Filter, SearchFilter};
5//!
6//! let request: VectorSearchRequest = VectorSearchRequest::builder()
7//!     .query("guide").samples(5)
8//!     .filter(Filter::eq("category", serde_json::json!("manual"))).build();
9//! assert_eq!(request.samples(), 5);
10//! ```
11
12use std::ops::Range;
13
14use serde::{Deserialize, Serialize};
15
16use crate::markers::{Missing, Provided};
17
18/// A vector search request for querying a [`super::VectorStoreIndex`].
19///
20/// The type parameter `F` specifies the filter type (defaults to [`Filter<serde_json::Value>`]).
21/// Use [`VectorSearchRequest::builder()`] to construct instances.
22#[derive(Clone, Serialize, Deserialize, Debug)]
23pub struct VectorSearchRequest<F = Filter<serde_json::Value>> {
24    /// The query text to embed and search with.
25    query: String,
26    /// Maximum number of results to return.
27    samples: u64,
28    /// Minimum similarity score for results.
29    #[serde(default, deserialize_with = "crate::json_utils::floats")]
30    threshold: Option<f64>,
31    /// Filter expression to narrow results by metadata.
32    filter: Option<F>,
33}
34
35impl<Filter> VectorSearchRequest<Filter> {
36    /// Creates a [`VectorSearchRequestBuilder`] which you can use to instantiate this struct.
37    pub fn builder() -> VectorSearchRequestBuilder<Filter> {
38        VectorSearchRequestBuilder::<Filter>::default()
39    }
40
41    /// The query to be embedded and used in similarity search.
42    pub fn query(&self) -> &str {
43        &self.query
44    }
45
46    /// Returns the maximum number of results to return.
47    pub fn samples(&self) -> u64 {
48        self.samples
49    }
50
51    /// Returns the optional similarity threshold.
52    pub fn threshold(&self) -> Option<f64> {
53        self.threshold
54    }
55
56    /// Returns a reference to the optional filter expression.
57    pub fn filter(&self) -> Option<&Filter> {
58        self.filter.as_ref()
59    }
60
61    /// Transforms the filter type using the provided function.
62    ///
63    /// This is useful for converting between filter representations, such as
64    /// translating the canonical [`super::request::Filter`] to a backend-specific filter type.
65    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    /// Transforms the filter type using a provided function which can additionally return a result.
78    ///
79    /// Useful for converting between filter representations where the conversion can potentially fail (eg, unrepresentable or invalid values).
80    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/// Errors from constructing or converting filter expressions.
96#[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    // NOTE: Uses String because `serde_json::Error` is not `Clone`.
111    #[error("Filter serialization failed: {0}")]
112    Serialization(String),
113}
114
115/// Trait for constructing filter expressions in vector search queries.
116///
117/// Uses [tagless final](https://nrinaudo.github.io/articles/tagless_final.html) encoding
118/// for backend-agnostic filters. Use `SearchFilter::eq(...)` etc. directly and let
119/// type inference resolve the concrete filter type.
120pub 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/// A rendered SQL-style condition together with its positional bind parameters.
131///
132/// Parameters retain left-to-right placeholder order. Keys, operators, and
133/// placeholders are interpolated verbatim; callers must validate or quote them
134/// for the target backend. Only values are separated as bind parameters. The
135/// condition records where each placeholder token sits, so
136/// [`SqlCondition::render_placeholders`] rewrites placeholders without touching
137/// spliced text that happens to contain the same characters.
138#[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
146/// Hand-written so that `P` needs no [`Default`] of its own: a parameterless
147/// empty condition is meaningful for every parameter type.
148impl<P> Default for SqlCondition<P> {
149    fn default() -> Self {
150        Self::raw(String::new())
151    }
152}
153
154impl<P> SqlCondition<P> {
155    /// Renders `<key> <op> <placeholder>` bound to a single parameter, e.g.
156    /// `price >= $`.
157    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    /// Renders `<key> <op> (<placeholder>, ...)` with one placeholder per value,
165    /// e.g. `id IN (?, ?)`.
166    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    /// Renders `<key> >= <placeholder> AND <key> <= <placeholder>` bound to
180    /// `lo` then `hi`, e.g. `price >= ? AND price <= ?`.
181    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    /// Renders `<key> between <placeholder> and <placeholder>` bound to `lo`
192    /// then `hi`, e.g. `price between ? and ?`.
193    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    /// Wraps an already-rendered, parameterless condition such as `id is null`.
203    /// The text holds no placeholders, whatever characters it contains.
204    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    /// Conjoins two conditions as `(lhs) AND (rhs)`, concatenating their parameters.
213    pub fn and(self, rhs: Self) -> Self {
214        self.combine("AND", rhs)
215    }
216
217    /// Disjoins two conditions as `(lhs) OR (rhs)`, concatenating their parameters.
218    pub fn or(self, rhs: Self) -> Self {
219        self.combine("OR", rhs)
220    }
221
222    /// Negates the condition as `NOT (condition)`, keeping its parameters.
223    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    /// The rendered condition, with placeholders as the caller supplied them.
258    pub fn condition(&self) -> &str {
259        &self.condition
260    }
261
262    /// The bind parameters, in placeholder order.
263    pub fn params(&self) -> &[P] {
264        &self.params
265    }
266
267    /// Returns the condition with the placeholder for parameter `i` (zero-based,
268    /// in [`SqlCondition::params`] order) replaced by `placeholder(i)`, e.g.
269    /// `|i| format!("${}", i + 1)` for Postgres. Only tokens emitted by the
270    /// constructors are replaced; keys and [`SqlCondition::raw`] text are
271    /// copied verbatim.
272    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            // Ranges only come from the constructors or deserialization; skip
282            // any that do not fit the text rather than panic.
283            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    /// Consumes the condition, returning the rendered text and its parameters.
298    pub fn into_parts(self) -> (String, Vec<P>) {
299        (self.condition, self.params)
300    }
301}
302
303/// Converts the canonical JSON-valued [`Filter`] used by type-erased vector
304/// searches into a backend's native filter representation.
305///
306/// JSON-valued [`SearchFilter`] implementations receive this automatically.
307/// Backends with native value types implement the conversion once here rather
308/// than hand-writing both the `RetrieveAdapter`
309/// methods.
310pub trait DynamicSearchFilter: SearchFilter + Sized {
311    /// Converts a canonical dynamic filter into this backend's filter type.
312    fn from_dynamic_filter(filter: Filter<serde_json::Value>) -> Result<Self, FilterError>;
313
314    /// Normalizes a document returned through the type-erased search surface.
315    ///
316    /// The default retains documents unchanged. The JSON-valued blanket
317    /// implementation recursively removes arrays longer than 400 elements;
318    /// a removed root array becomes null.
319    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/// Canonical, serializable filter representation.
358///
359/// Use for serialization, runtime inspection, or translating between backends via
360/// [`Filter::interpret`]. Prefer [`SearchFilter`] trait methods for writing queries.
361#[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    /// Select values where the entry at `key` is equal to `value`
381    fn eq(key: impl AsRef<str>, value: Self::Value) -> Self {
382        Self::Eq(key.as_ref().to_owned(), value)
383    }
384
385    /// Select values where the entry at `key` is greater than `value`
386    fn gt(key: impl AsRef<str>, value: Self::Value) -> Self {
387        Self::Gt(key.as_ref().to_owned(), value)
388    }
389
390    /// Select values where the entry at `key` is less than `value`
391    fn lt(key: impl AsRef<str>, value: Self::Value) -> Self {
392        Self::Lt(key.as_ref().to_owned(), value)
393    }
394
395    /// Select values where the entry satisfies `self` *and* `rhs`
396    fn and(self, rhs: Self) -> Self {
397        Self::And(self.into(), rhs.into())
398    }
399
400    /// Select values where the entry satisfies `self` *or* `rhs`
401    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    /// Converts this filter into a backend-specific filter type.
411    pub fn interpret<F>(self) -> F
412    where
413        F: SearchFilter<Value = V>,
414    {
415        self.interpret_with(|v| v)
416    }
417
418    /// Converts this filter into a backend-specific filter type, converting
419    /// each leaf value with `conv`.
420    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    /// Converts this filter into a backend-specific filter type, converting
431    /// each leaf value with `conv`. Fails on the first value that fails to convert.
432    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    /// Tests whether a JSON document satisfies this filter.
448    ///
449    /// Looks up top-level object fields. Missing fields fail all leaves.
450    /// Equality accepts numeric comparison or structural JSON equality; ordering
451    /// compares only number, string, boolean, or null pairs of the same kind.
452    /// `And` and `Or` short-circuit.
453    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            // Numbers compare numerically so `5` matches `5.0`, consistent with
470            // `Gt`/`Lt`; other JSON types fall back to structural equality so
471            // strings/bools/arrays/objects still match exactly.
472            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/// Builder for [`VectorSearchRequest`]. Requires `query` and `samples`.
490#[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    /// Sets the query text. Required.
514    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    /// Sets the maximum number of results. Required.
527    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    /// Sets the minimum similarity threshold.
537    pub fn threshold(mut self, threshold: f64) -> Self {
538        self.threshold = Some(threshold);
539        self
540    }
541
542    /// Sets a filter expression.
543    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    /// Builds without validating query emptiness, sample count, or threshold.
551    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;