rig-redis-vectorstore 0.1.1

Redis (RediSearch) vector store integration for the Rig LLM framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Redis-specific filter types for RediSearch `FT.SEARCH` queries.
//!
//! Provides [`Filter`] which implements [`SearchFilter`] and translates
//! Rig's generic filter expressions into RediSearch query syntax.
//!
//! # Field Type Expectations
//!
//! - **Numeric fields**: `eq`, `gt`, `lt`, `gte`, `lte`, and `range` produce range syntax (`@field:[min max]`)
//! - **Tag fields**: String equality uses tag syntax (`@field:{value}`)
//! - **Bool fields**: Equality uses numeric TAG values (`1` or `0`) with tag syntax
//! - **Range filters**: Redis-specific range constructors reject non-numeric values instead of converting them into tag matches
//!
//! The generic [`SearchFilter`] implementation is numeric-only because Rig's
//! shared trait is infallible. Use the inherent [`Filter`] constructors when
//! building Redis filters directly, especially for tag values and fallible
//! numeric range filters. Ensure your RediSearch schema matches the filter
//! types you use.
//!
//! # Dynamic API Subset
//!
//! The [`VectorStoreIndexDyn`](rig_core::vector_store::VectorStoreIndexDyn) path
//! only supports the five [`CoreFilter`](rig_core::vector_store::request::Filter)
//! variants: `Eq`, `Gt`, `Lt`, `And`, `Or`. Redis-specific methods such as
//! [`Filter::gte`], [`Filter::lte`], [`Filter::range`], [`Filter::tag_in`],
//! [`Filter::text_contains`], and [`Filter::text_phrase`] are only reachable
//! through the typed [`VectorStoreIndex`](rig_core::vector_store::VectorStoreIndex) API.
//!
//! # Escaping
//!
//! Field names and tag/text values are escaped for RediSearch special characters
//! by the typed constructors. The [`escape_tag_value`] and [`escape_text_value`]
//! helpers are exported for callers building raw queries via [`Filter::raw`].

use rig_core::vector_store::request::{Filter as CoreFilter, FilterError, SearchFilter};
use serde::{Deserialize, Serialize};

/// Typed value for Redis-specific filter expressions.
///
/// Determines how the value is formatted in the RediSearch query syntax.
#[derive(Debug, Clone, PartialEq)]
pub enum RedisValue {
    /// Numeric value. Equality produces range syntax; range constructors use
    /// this as the only supported value kind.
    Number(f64),
    /// String/tag value. Equality and tag filters produce tag syntax.
    String(String),
    /// Boolean value. Equality treats this as a TAG value (`1` or `0`).
    Bool(bool),
}

/// Finite numeric value for Redis range-syntax filters.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RedisNumber(f64);

impl RedisNumber {
    /// Creates a finite Redis numeric filter value.
    ///
    /// Returns a [`FilterError`] if `value` is not finite (`NaN`, `+inf`, `-inf`).
    pub fn new(value: f64) -> Result<Self, FilterError> {
        if value.is_finite() {
            Ok(Self(value))
        } else {
            Err(FilterError::Expected {
                expected: "finite numeric value for Redis numeric filter".into(),
                got: value.to_string(),
            })
        }
    }

    fn get(self) -> f64 {
        self.0
    }
}

impl TryFrom<f64> for RedisNumber {
    type Error = FilterError;

    fn try_from(value: f64) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// Note: `i64` values with magnitude above 2^53 lose precision in the `f64`
/// representation used by RediSearch numeric fields.
impl From<i64> for RedisNumber {
    fn from(value: i64) -> Self {
        Self(value as f64)
    }
}

/// Note: `u64` values above 2^53 (9,007,199,254,740,992) lose precision in the
/// `f64` representation used by RediSearch numeric fields.
impl From<u64> for RedisNumber {
    fn from(value: u64) -> Self {
        Self(value as f64)
    }
}

fn numeric_bound(value: RedisValue, operation: &'static str) -> Result<RedisNumber, FilterError> {
    match value {
        RedisValue::Number(n) if n.is_finite() => Ok(RedisNumber(n)),
        RedisValue::Number(n) => Err(FilterError::Expected {
            expected: format!("finite numeric value for Redis {operation} filter"),
            got: n.to_string(),
        }),
        other => Err(FilterError::Expected {
            expected: format!("numeric value for Redis {operation} filter"),
            got: format!("{other:?}"),
        }),
    }
}

fn numeric_eq_filter(key: impl AsRef<str>, value: RedisNumber) -> Filter {
    let value = value.get();
    Filter(format!("@{}:[{value} {value}]", field_name(key)))
}

fn gt_number_filter(key: impl AsRef<str>, value: RedisNumber) -> Filter {
    let value = value.get();
    Filter(format!("@{}:[({value} +inf]", field_name(key)))
}

fn lt_number_filter(key: impl AsRef<str>, value: RedisNumber) -> Filter {
    let value = value.get();
    Filter(format!("@{}:[-inf ({value}]", field_name(key)))
}

fn gte_number_filter(key: impl AsRef<str>, value: RedisNumber) -> Filter {
    let value = value.get();
    Filter(format!("@{}:[{value} +inf]", field_name(key)))
}

fn lte_number_filter(key: impl AsRef<str>, value: RedisNumber) -> Filter {
    let value = value.get();
    Filter(format!("@{}:[-inf {value}]", field_name(key)))
}

fn field_name(key: impl AsRef<str>) -> String {
    key.as_ref()
        .split('.')
        .map(escape_field_segment)
        .collect::<Vec<_>>()
        .join(".")
}

fn escape_field_segment(segment: &str) -> String {
    let mut escaped = String::with_capacity(segment.len());
    for ch in segment.chars() {
        if ch.is_ascii_alphanumeric() || ch == '_' {
            escaped.push(ch);
        } else {
            escaped.push('\\');
            escaped.push(ch);
        }
    }
    escaped
}

/// Escapes RediSearch tag special characters in `value` by backslash-prefixing them.
///
/// Useful when constructing raw queries with [`Filter::raw`]. The typed
/// constructors apply this automatically.
pub fn escape_tag_value(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for ch in value.chars() {
        if matches!(
            ch,
            '\\' | ' '
                | ','
                | '.'
                | '<'
                | '>'
                | '{'
                | '}'
                | '['
                | ']'
                | '"'
                | '\''
                | ':'
                | ';'
                | '!'
                | '@'
                | '#'
                | '$'
                | '%'
                | '^'
                | '&'
                | '*'
                | '('
                | ')'
                | '-'
                | '+'
                | '='
                | '~'
                | '|'
                | '/'
        ) {
            escaped.push('\\');
        }
        escaped.push(ch);
    }
    escaped
}

/// Escapes RediSearch TEXT query special characters in `value` by backslash-prefixing them.
///
/// Useful when constructing raw queries with [`Filter::raw`]. The typed
/// text constructors ([`Filter::text_contains`], [`Filter::text_phrase`]) apply
/// this automatically.
pub fn escape_text_value(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for ch in value.chars() {
        if matches!(
            ch,
            '\\' | '<'
                | '>'
                | '{'
                | '}'
                | '['
                | ']'
                | '"'
                | '\''
                | ':'
                | ';'
                | '!'
                | '@'
                | '#'
                | '$'
                | '%'
                | '^'
                | '&'
                | '*'
                | '('
                | ')'
                | '-'
                | '+'
                | '='
                | '~'
                | '|'
                | '/'
        ) {
            escaped.push('\\');
        }
        escaped.push(ch);
    }
    escaped
}

impl From<i64> for RedisValue {
    fn from(value: i64) -> Self {
        Self::Number(value as f64)
    }
}

impl From<u64> for RedisValue {
    fn from(value: u64) -> Self {
        Self::Number(value as f64)
    }
}

impl From<f64> for RedisValue {
    fn from(value: f64) -> Self {
        Self::Number(value)
    }
}

impl From<bool> for RedisValue {
    fn from(value: bool) -> Self {
        Self::Bool(value)
    }
}

impl From<String> for RedisValue {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

impl From<&str> for RedisValue {
    fn from(value: &str) -> Self {
        Self::String(value.to_owned())
    }
}

impl TryFrom<serde_json::Value> for RedisValue {
    type Error = FilterError;

    fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
        match value {
            serde_json::Value::Bool(b) => Ok(RedisValue::Bool(b)),
            serde_json::Value::Number(n) => {
                let num = n.as_f64().ok_or_else(|| FilterError::Expected {
                    expected: "Valid 64-bit float".into(),
                    got: "Invalid 64-bit float".into(),
                })?;
                Ok(RedisValue::Number(num))
            }
            serde_json::Value::String(s) => Ok(RedisValue::String(s)),
            serde_json::Value::Null
            | serde_json::Value::Array(_)
            | serde_json::Value::Object(_) => Err(FilterError::TypeError(
                "Redis filter does not currently support null values, arrays or objects".into(),
            )),
        }
    }
}

/// Redis filter for FT.SEARCH queries.
///
/// Wraps a raw RediSearch query string. Use the inherent constructors on this
/// type for Redis-specific filters, including fallible numeric range filters
/// and tag filters.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Filter(String);

impl SearchFilter for Filter {
    type Value = RedisNumber;

    /// Numeric equality filter.
    ///
    /// Redis-specific string and boolean equality are available through the
    /// inherent [`Filter::eq`] constructor.
    fn eq(key: impl AsRef<str>, value: Self::Value) -> Self {
        numeric_eq_filter(key, value)
    }

    fn gt(key: impl AsRef<str>, value: Self::Value) -> Self {
        gt_number_filter(key, value)
    }

    fn lt(key: impl AsRef<str>, value: Self::Value) -> Self {
        lt_number_filter(key, value)
    }

    fn and(self, rhs: Self) -> Self {
        self.and(rhs)
    }

    fn or(self, rhs: Self) -> Self {
        self.or(rhs)
    }
}

impl Filter {
    /// Equality filter.
    ///
    /// - Numeric: `@field:[val val]` (exact range match)
    /// - String: `@field:{value}` (tag match, value escaped)
    /// - Bool: `@field:{1}` or `@field:{0}` (tag match)
    pub fn eq(key: impl AsRef<str>, value: impl Into<RedisValue>) -> Result<Self, FilterError> {
        let key = field_name(key);
        let filter = match value.into() {
            RedisValue::Number(n) => numeric_eq_filter(key, RedisNumber::new(n)?),
            RedisValue::String(ref s) => Self(format!("@{key}:{{{}}}", escape_tag_value(s))),
            RedisValue::Bool(b) => {
                let v = if b { "1" } else { "0" };
                Self(format!("@{key}:{{{v}}}"))
            }
        };
        Ok(filter)
    }

    /// Greater-than filter (exclusive).
    ///
    /// Produces `@field:[(val +inf]` for numeric values and returns an error
    /// for strings or booleans. Use [`Filter::eq`] or [`Filter::tag_in`] for
    /// tag comparisons.
    pub fn gt(key: impl AsRef<str>, value: impl Into<RedisValue>) -> Result<Self, FilterError> {
        let value = numeric_bound(value.into(), "greater-than")?;
        Ok(gt_number_filter(key, value))
    }

    /// Less-than filter (exclusive).
    ///
    /// Produces `@field:[-inf (val]` for numeric values and returns an error
    /// for strings or booleans. Use [`Filter::eq`] or [`Filter::tag_in`] for
    /// tag comparisons.
    pub fn lt(key: impl AsRef<str>, value: impl Into<RedisValue>) -> Result<Self, FilterError> {
        let value = numeric_bound(value.into(), "less-than")?;
        Ok(lt_number_filter(key, value))
    }

    /// Negates this filter expression.
    #[allow(clippy::should_implement_trait)]
    pub fn not(self) -> Self {
        Self(format!("-{}", self.0))
    }

    /// Greater than or equal (inclusive).
    ///
    /// Produces `@field:[val +inf]` for numeric values and returns an error
    /// for strings or booleans. Use [`Filter::eq`] or [`Filter::tag_in`] for
    /// tag comparisons.
    pub fn gte(key: impl AsRef<str>, value: impl Into<RedisValue>) -> Result<Self, FilterError> {
        let value = numeric_bound(value.into(), "greater-than-or-equal")?;
        Ok(gte_number_filter(key, value))
    }

    /// Less than or equal (inclusive).
    ///
    /// Produces `@field:[-inf val]` for numeric values and returns an error
    /// for strings or booleans. Use [`Filter::eq`] or [`Filter::tag_in`] for
    /// tag comparisons.
    pub fn lte(key: impl AsRef<str>, value: impl Into<RedisValue>) -> Result<Self, FilterError> {
        let value = numeric_bound(value.into(), "less-than-or-equal")?;
        Ok(lte_number_filter(key, value))
    }

    /// Combines this filter with another using RediSearch AND semantics.
    pub fn and(self, rhs: Self) -> Self {
        Self(format!("({} {})", self.0, rhs.0))
    }

    /// Combines this filter with another using RediSearch OR semantics.
    pub fn or(self, rhs: Self) -> Self {
        Self(format!("({} | {})", self.0, rhs.0))
    }

    /// Numeric range filter (inclusive on both ends).
    pub fn range(key: impl AsRef<str>, min: f64, max: f64) -> Result<Self, FilterError> {
        let min = RedisNumber::new(min)?.get();
        let max = RedisNumber::new(max)?.get();
        Ok(Self(format!("@{}:[{} {}]", field_name(key), min, max)))
    }

    /// Numeric range filter (exclusive on both ends).
    pub fn range_exclusive(key: impl AsRef<str>, min: f64, max: f64) -> Result<Self, FilterError> {
        let min = RedisNumber::new(min)?.get();
        let max = RedisNumber::new(max)?.get();
        Ok(Self(format!("@{}:[({} ({}]", field_name(key), min, max)))
    }

    /// Tag filter for multiple values (OR).
    ///
    /// Produces `@field:{val1 | val2 | val3}` with each value escaped.
    ///
    /// If `values` is empty, returns a match-all filter (`*`) to avoid emitting
    /// invalid `@field:{}` syntax.
    pub fn tag_in(key: impl AsRef<str>, values: Vec<String>) -> Self {
        if values.is_empty() {
            return Self::raw("*");
        }
        let tags = values
            .iter()
            .map(|value| escape_tag_value(value))
            .collect::<Vec<_>>()
            .join(" | ");
        Self(format!("@{}:{{{}}}", field_name(key), tags))
    }

    /// Full-text token search within a TEXT field.
    ///
    /// Performs a token-AND search: all words in `text` must appear in the field,
    /// in any order or position. This is **not** a phrase search; use
    /// [`Filter::text_phrase`] for exact ordered matching.
    pub fn text_contains(key: impl AsRef<str>, text: impl AsRef<str>) -> Self {
        Self(format!(
            "@{}:({})",
            field_name(key),
            escape_text_value(text.as_ref())
        ))
    }

    /// Exact phrase search within a TEXT field.
    ///
    /// Matches the exact ordered sequence of words in `phrase`. Produces
    /// `@field:"phrase"` syntax with the phrase contents escaped (the wrapping
    /// quotes are not escaped).
    pub fn text_phrase(key: impl AsRef<str>, phrase: impl AsRef<str>) -> Self {
        Self(format!(
            "@{}:\"{}\"",
            field_name(key),
            escape_text_value(phrase.as_ref())
        ))
    }

    /// Creates a filter from a raw RediSearch query string.
    ///
    /// No escaping is applied; the caller is responsible for valid syntax.
    ///
    /// # Security Warning
    ///
    /// Do **not** pass unsanitized user input to this method. Arbitrary
    /// RediSearch clauses can be injected, returning unintended results or
    /// causing parse errors. Use the typed constructors (e.g. [`Filter::eq`],
    /// [`Filter::tag_in`]) for user-supplied values, or escape values yourself
    /// with [`escape_tag_value`] / [`escape_text_value`].
    pub fn raw(query: impl Into<String>) -> Self {
        Self(query.into())
    }

    /// Consumes the filter and returns the raw RediSearch query string.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl TryFrom<CoreFilter<serde_json::Value>> for Filter {
    type Error = FilterError;

    fn try_from(value: CoreFilter<serde_json::Value>) -> Result<Self, Self::Error> {
        let filter = match value {
            CoreFilter::Eq(k, val) => Filter::eq(k, RedisValue::try_from(val)?)?,
            CoreFilter::Gt(k, val) => Filter::gt(k, RedisValue::try_from(val)?)?,
            CoreFilter::Lt(k, val) => Filter::lt(k, RedisValue::try_from(val)?)?,
            CoreFilter::And(l, r) => Self::try_from(*l)?.and(Self::try_from(*r)?),
            CoreFilter::Or(l, r) => Self::try_from(*l)?.or(Self::try_from(*r)?),
        };

        Ok(filter)
    }
}