Skip to main content

redis_tower_commands/
search_util.rs

1use crate::CommandArg;
2use bytes::Bytes;
3use redis_tower_core::{Command, Frame, RedisError};
4use redis_tower_protocol::helpers::{array, bulk};
5
6/// FT.SUGADD key string score \[INCR\] \[PAYLOAD payload\]
7///
8/// Adds a suggestion string to an auto-complete dictionary. Returns the
9/// current size of the dictionary.
10///
11/// Arguments are serialized byte-for-byte. Redis Search treats suggestion
12/// strings as text: an embedded NUL is a terminator and malformed UTF-8 can be
13/// normalized by the server. Dictionary keys and payloads are not subject to
14/// that suggestion-string limitation.
15#[derive(Clone)]
16pub struct FtSugAdd {
17    key: CommandArg,
18    string: CommandArg,
19    score: f64,
20    incr: bool,
21    payload: Option<CommandArg>,
22}
23
24impl FtSugAdd {
25    /// Create a new [`FtSugAdd`] command.
26    pub fn new(key: impl Into<CommandArg>, string: impl Into<CommandArg>, score: f64) -> Self {
27        Self {
28            key: key.into(),
29            string: string.into(),
30            score,
31            incr: false,
32            payload: None,
33        }
34    }
35
36    /// Increment the existing score instead of replacing it.
37    pub fn incr(mut self) -> Self {
38        self.incr = true;
39        self
40    }
41
42    /// Set an opaque payload to store with the suggestion.
43    pub fn payload(mut self, payload: impl Into<CommandArg>) -> Self {
44        self.payload = Some(payload.into());
45        self
46    }
47}
48
49impl Command for FtSugAdd {
50    type Response = i64;
51
52    fn to_frame(&self) -> Frame {
53        let mut args = vec![
54            bulk("FT.SUGADD"),
55            bulk(&self.key),
56            bulk(&self.string),
57            bulk(self.score.to_string()),
58        ];
59        if self.incr {
60            args.push(bulk("INCR"));
61        }
62        if let Some(payload) = &self.payload {
63            args.push(bulk("PAYLOAD"));
64            args.push(bulk(payload));
65        }
66        array(args)
67    }
68
69    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
70        match frame {
71            Frame::Integer(n) => Ok(n),
72            other => Err(RedisError::UnexpectedResponse {
73                expected: "integer",
74                actual: format!("{other:?}"),
75            }),
76        }
77    }
78
79    fn name(&self) -> &str {
80        "FT.SUGADD"
81    }
82}
83
84/// FT.SUGGET key prefix \[FUZZY\] \[WITHSCORES\] \[WITHPAYLOADS\] \[MAX num\]
85///
86/// Gets completion suggestions for a prefix from an auto-complete dictionary.
87/// The response structure varies based on options, so it returns a raw `Frame`.
88#[derive(Clone)]
89pub struct FtSugGet {
90    key: CommandArg,
91    prefix: CommandArg,
92    fuzzy: bool,
93    withscores: bool,
94    withpayloads: bool,
95    max: Option<u64>,
96}
97
98impl FtSugGet {
99    /// Create a new [`FtSugGet`] command.
100    pub fn new(key: impl Into<CommandArg>, prefix: impl Into<CommandArg>) -> Self {
101        Self {
102            key: key.into(),
103            prefix: prefix.into(),
104            fuzzy: false,
105            withscores: false,
106            withpayloads: false,
107            max: None,
108        }
109    }
110
111    /// Enable fuzzy matching.
112    pub fn fuzzy(mut self) -> Self {
113        self.fuzzy = true;
114        self
115    }
116
117    /// Include scores in the results.
118    pub fn withscores(mut self) -> Self {
119        self.withscores = true;
120        self
121    }
122
123    /// Include payloads in the results.
124    pub fn withpayloads(mut self) -> Self {
125        self.withpayloads = true;
126        self
127    }
128
129    /// Limit the number of results.
130    pub fn max(mut self, num: u64) -> Self {
131        self.max = Some(num);
132        self
133    }
134}
135
136impl Command for FtSugGet {
137    type Response = Frame;
138
139    fn to_frame(&self) -> Frame {
140        let mut args = vec![bulk("FT.SUGGET"), bulk(&self.key), bulk(&self.prefix)];
141        if self.fuzzy {
142            args.push(bulk("FUZZY"));
143        }
144        if self.withscores {
145            args.push(bulk("WITHSCORES"));
146        }
147        if self.withpayloads {
148            args.push(bulk("WITHPAYLOADS"));
149        }
150        if let Some(max) = self.max {
151            args.push(bulk("MAX"));
152            args.push(bulk(max.to_string()));
153        }
154        array(args)
155    }
156
157    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
158        Ok(frame)
159    }
160
161    fn name(&self) -> &str {
162        "FT.SUGGET"
163    }
164}
165
166/// FT.SUGDEL key string
167///
168/// Deletes a string from an auto-complete dictionary. Returns `true` if the
169/// string was found and deleted.
170#[derive(Clone)]
171pub struct FtSugDel {
172    key: CommandArg,
173    string: CommandArg,
174}
175
176impl FtSugDel {
177    /// Create a new [`FtSugDel`] command.
178    pub fn new(key: impl Into<CommandArg>, string: impl Into<CommandArg>) -> Self {
179        Self {
180            key: key.into(),
181            string: string.into(),
182        }
183    }
184}
185
186impl Command for FtSugDel {
187    type Response = bool;
188
189    fn to_frame(&self) -> Frame {
190        array(vec![bulk("FT.SUGDEL"), bulk(&self.key), bulk(&self.string)])
191    }
192
193    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
194        match frame {
195            Frame::Integer(1) => Ok(true),
196            Frame::Integer(0) => Ok(false),
197            other => Err(RedisError::UnexpectedResponse {
198                expected: "integer 0 or 1",
199                actual: format!("{other:?}"),
200            }),
201        }
202    }
203
204    fn name(&self) -> &str {
205        "FT.SUGDEL"
206    }
207}
208
209/// FT.SUGLEN key
210///
211/// Returns the number of entries in an auto-complete dictionary.
212#[derive(Clone)]
213pub struct FtSugLen {
214    key: CommandArg,
215}
216
217impl FtSugLen {
218    /// Create a new [`FtSugLen`] command.
219    pub fn new(key: impl Into<CommandArg>) -> Self {
220        Self { key: key.into() }
221    }
222}
223
224impl Command for FtSugLen {
225    type Response = i64;
226
227    fn to_frame(&self) -> Frame {
228        array(vec![bulk("FT.SUGLEN"), bulk(&self.key)])
229    }
230
231    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
232        match frame {
233            Frame::Integer(n) => Ok(n),
234            other => Err(RedisError::UnexpectedResponse {
235                expected: "integer",
236                actual: format!("{other:?}"),
237            }),
238        }
239    }
240
241    fn name(&self) -> &str {
242        "FT.SUGLEN"
243    }
244}
245
246/// FT.SYNUPDATE index group_id term \[term ...\]
247///
248/// Updates a synonym group with additional terms.
249#[derive(Clone)]
250pub struct FtSynUpdate {
251    index: String,
252    group_id: String,
253    terms: Vec<String>,
254}
255
256impl FtSynUpdate {
257    /// Create a new [`FtSynUpdate`] command.
258    pub fn new(
259        index: impl Into<String>,
260        group_id: impl Into<String>,
261        terms: impl IntoIterator<Item = impl Into<String>>,
262    ) -> Self {
263        Self {
264            index: index.into(),
265            group_id: group_id.into(),
266            terms: terms.into_iter().map(Into::into).collect(),
267        }
268    }
269}
270
271impl Command for FtSynUpdate {
272    type Response = ();
273
274    fn to_frame(&self) -> Frame {
275        let mut args = vec![
276            bulk("FT.SYNUPDATE"),
277            bulk(self.index.as_str()),
278            bulk(self.group_id.as_str()),
279        ];
280        for term in &self.terms {
281            args.push(bulk(term.as_str()));
282        }
283        array(args)
284    }
285
286    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
287        match frame {
288            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
289            other => Err(RedisError::UnexpectedResponse {
290                expected: "OK",
291                actual: format!("{other:?}"),
292            }),
293        }
294    }
295
296    fn name(&self) -> &str {
297        "FT.SYNUPDATE"
298    }
299}
300
301/// FT.SYNDUMP index
302///
303/// Dumps the contents of a synonym group. Returns a raw `Frame` containing
304/// alternating term and group ID pairs.
305#[derive(Clone)]
306pub struct FtSynDump {
307    index: String,
308}
309
310impl FtSynDump {
311    /// Create a new [`FtSynDump`] command.
312    pub fn new(index: impl Into<String>) -> Self {
313        Self {
314            index: index.into(),
315        }
316    }
317}
318
319impl Command for FtSynDump {
320    type Response = Frame;
321
322    fn to_frame(&self) -> Frame {
323        array(vec![bulk("FT.SYNDUMP"), bulk(self.index.as_str())])
324    }
325
326    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
327        Ok(frame)
328    }
329
330    fn name(&self) -> &str {
331        "FT.SYNDUMP"
332    }
333}
334
335/// FT.DICTADD dict term \[term ...\]
336///
337/// Adds terms to a dictionary. Returns the number of new terms added.
338#[derive(Clone)]
339pub struct FtDictAdd {
340    dict: String,
341    terms: Vec<String>,
342}
343
344impl FtDictAdd {
345    /// Create a new [`FtDictAdd`] command.
346    pub fn new(
347        dict: impl Into<String>,
348        terms: impl IntoIterator<Item = impl Into<String>>,
349    ) -> Self {
350        Self {
351            dict: dict.into(),
352            terms: terms.into_iter().map(Into::into).collect(),
353        }
354    }
355}
356
357impl Command for FtDictAdd {
358    type Response = i64;
359
360    fn to_frame(&self) -> Frame {
361        let mut args = vec![bulk("FT.DICTADD"), bulk(self.dict.as_str())];
362        for term in &self.terms {
363            args.push(bulk(term.as_str()));
364        }
365        array(args)
366    }
367
368    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
369        match frame {
370            Frame::Integer(n) => Ok(n),
371            other => Err(RedisError::UnexpectedResponse {
372                expected: "integer",
373                actual: format!("{other:?}"),
374            }),
375        }
376    }
377
378    fn name(&self) -> &str {
379        "FT.DICTADD"
380    }
381}
382
383/// FT.DICTDEL dict term \[term ...\]
384///
385/// Deletes terms from a dictionary. Returns the number of terms deleted.
386#[derive(Clone)]
387pub struct FtDictDel {
388    dict: String,
389    terms: Vec<String>,
390}
391
392impl FtDictDel {
393    /// Create a new [`FtDictDel`] command.
394    pub fn new(
395        dict: impl Into<String>,
396        terms: impl IntoIterator<Item = impl Into<String>>,
397    ) -> Self {
398        Self {
399            dict: dict.into(),
400            terms: terms.into_iter().map(Into::into).collect(),
401        }
402    }
403}
404
405impl Command for FtDictDel {
406    type Response = i64;
407
408    fn to_frame(&self) -> Frame {
409        let mut args = vec![bulk("FT.DICTDEL"), bulk(self.dict.as_str())];
410        for term in &self.terms {
411            args.push(bulk(term.as_str()));
412        }
413        array(args)
414    }
415
416    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
417        match frame {
418            Frame::Integer(n) => Ok(n),
419            other => Err(RedisError::UnexpectedResponse {
420                expected: "integer",
421                actual: format!("{other:?}"),
422            }),
423        }
424    }
425
426    fn name(&self) -> &str {
427        "FT.DICTDEL"
428    }
429}
430
431/// FT.DICTDUMP dict
432///
433/// Returns all terms in a dictionary.
434#[derive(Clone)]
435pub struct FtDictDump {
436    dict: String,
437}
438
439impl FtDictDump {
440    /// Create a new [`FtDictDump`] command.
441    pub fn new(dict: impl Into<String>) -> Self {
442        Self { dict: dict.into() }
443    }
444}
445
446impl Command for FtDictDump {
447    type Response = Vec<Bytes>;
448
449    fn to_frame(&self) -> Frame {
450        array(vec![bulk("FT.DICTDUMP"), bulk(self.dict.as_str())])
451    }
452
453    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
454        match frame {
455            Frame::Array(Some(frames)) => frames
456                .into_iter()
457                .map(|f| match f {
458                    Frame::BulkString(Some(data)) => Ok(data),
459                    other => Err(RedisError::UnexpectedResponse {
460                        expected: "bulk string",
461                        actual: format!("{other:?}"),
462                    }),
463                })
464                .collect(),
465            other => Err(RedisError::UnexpectedResponse {
466                expected: "array",
467                actual: format!("{other:?}"),
468            }),
469        }
470    }
471
472    fn name(&self) -> &str {
473        "FT.DICTDUMP"
474    }
475}
476
477/// Term inclusion mode for FT.SPELLCHECK.
478#[derive(Clone)]
479pub enum SpellCheckTerms {
480    /// Include terms from the specified dictionary.
481    Include(String),
482    /// Exclude terms from the specified dictionary.
483    Exclude(String),
484}
485
486/// FT.SPELLCHECK index query \[DISTANCE dist\] \[TERMS INCLUDE|EXCLUDE dict\]
487///
488/// Performs spelling correction on a query. Returns suggestions for
489/// misspelled terms as a raw `Frame`.
490#[derive(Clone)]
491pub struct FtSpellCheck {
492    index: String,
493    query: String,
494    distance: Option<u64>,
495    terms: Option<SpellCheckTerms>,
496}
497
498impl FtSpellCheck {
499    /// Create a new [`FtSpellCheck`] command.
500    pub fn new(index: impl Into<String>, query: impl Into<String>) -> Self {
501        Self {
502            index: index.into(),
503            query: query.into(),
504            distance: None,
505            terms: None,
506        }
507    }
508
509    /// Set the maximum Levenshtein distance for spelling suggestions (1-4).
510    pub fn distance(mut self, dist: u64) -> Self {
511        self.distance = Some(dist);
512        self
513    }
514
515    /// Include terms from the given dictionary in spell checking.
516    pub fn include_terms(mut self, dict: impl Into<String>) -> Self {
517        self.terms = Some(SpellCheckTerms::Include(dict.into()));
518        self
519    }
520
521    /// Exclude terms from the given dictionary in spell checking.
522    pub fn exclude_terms(mut self, dict: impl Into<String>) -> Self {
523        self.terms = Some(SpellCheckTerms::Exclude(dict.into()));
524        self
525    }
526}
527
528impl Command for FtSpellCheck {
529    type Response = Frame;
530
531    fn to_frame(&self) -> Frame {
532        let mut args = vec![
533            bulk("FT.SPELLCHECK"),
534            bulk(self.index.as_str()),
535            bulk(self.query.as_str()),
536        ];
537        if let Some(dist) = self.distance {
538            args.push(bulk("DISTANCE"));
539            args.push(bulk(dist.to_string()));
540        }
541        match &self.terms {
542            Some(SpellCheckTerms::Include(dict)) => {
543                args.push(bulk("TERMS"));
544                args.push(bulk("INCLUDE"));
545                args.push(bulk(dict.as_str()));
546            }
547            Some(SpellCheckTerms::Exclude(dict)) => {
548                args.push(bulk("TERMS"));
549                args.push(bulk("EXCLUDE"));
550                args.push(bulk(dict.as_str()));
551            }
552            None => {}
553        }
554        array(args)
555    }
556
557    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
558        Ok(frame)
559    }
560
561    fn name(&self) -> &str {
562        "FT.SPELLCHECK"
563    }
564}
565
566/// FT.CONFIG SET option value
567///
568/// Sets a RediSearch configuration option.
569#[derive(Clone)]
570pub struct FtConfigSet {
571    option: String,
572    value: String,
573}
574
575impl FtConfigSet {
576    /// Create a new [`FtConfigSet`] command.
577    pub fn new(option: impl Into<String>, value: impl Into<String>) -> Self {
578        Self {
579            option: option.into(),
580            value: value.into(),
581        }
582    }
583}
584
585impl Command for FtConfigSet {
586    type Response = ();
587
588    fn to_frame(&self) -> Frame {
589        array(vec![
590            bulk("FT.CONFIG"),
591            bulk("SET"),
592            bulk(self.option.as_str()),
593            bulk(self.value.as_str()),
594        ])
595    }
596
597    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
598        match frame {
599            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
600            other => Err(RedisError::UnexpectedResponse {
601                expected: "OK",
602                actual: format!("{other:?}"),
603            }),
604        }
605    }
606
607    fn name(&self) -> &str {
608        "FT.CONFIG SET"
609    }
610}
611
612/// FT.CONFIG GET option
613///
614/// Gets the value of a RediSearch configuration option. Returns a raw `Frame`.
615#[derive(Clone)]
616pub struct FtConfigGet {
617    option: String,
618}
619
620impl FtConfigGet {
621    /// Create a new [`FtConfigGet`] command.
622    pub fn new(option: impl Into<String>) -> Self {
623        Self {
624            option: option.into(),
625        }
626    }
627}
628
629impl Command for FtConfigGet {
630    type Response = Frame;
631
632    fn to_frame(&self) -> Frame {
633        array(vec![
634            bulk("FT.CONFIG"),
635            bulk("GET"),
636            bulk(self.option.as_str()),
637        ])
638    }
639
640    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
641        Ok(frame)
642    }
643
644    fn name(&self) -> &str {
645        "FT.CONFIG GET"
646    }
647}