Skip to main content

redis_tower_commands/
search.rs

1//! Redis Search index, query, aggregation, and utility commands.
2//!
3//! Available with the `search` feature (included by `stack`) and requiring
4//! Redis Search on the server. Query strings and schema grammar are textual;
5//! result rows are returned in the documented typed/raw shape for each command
6//! so applications can normalize RESP2/RESP3 differences deliberately.
7//!
8//! ```
9//! use redis_tower_commands::FtSearch;
10//! use redis_tower_core::Command;
11//!
12//! let command = FtSearch::new("idx:users", "@name:Ada").limit(0, 10);
13//! assert_eq!(command.name(), "FT.SEARCH");
14//! ```
15//!
16//! Search suggestions, dictionaries, spelling, synonyms, and configuration
17//! builders are re-exported through this module and the crate root. See the
18//! [command cookbook] for module reply normalization.
19//!
20//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#raw-custom-and-module-replies
21
22use bytes::Bytes;
23use redis_tower_core::{Command, Frame, RedisError};
24use redis_tower_protocol::helpers::{array, bulk};
25
26use crate::SortOrder;
27
28pub use crate::search_util::*;
29
30/// Field type for RediSearch schema definitions.
31#[derive(Clone)]
32pub enum FieldType {
33    /// Full-text searchable field.
34    Text,
35    /// Numeric range-queryable field.
36    Numeric,
37    /// Tag field for exact-match filtering.
38    Tag,
39    /// Geo-spatial field (longitude, latitude).
40    Geo,
41    /// Vector similarity field.
42    Vector,
43}
44
45impl FieldType {
46    fn as_str(&self) -> &str {
47        match self {
48            FieldType::Text => "TEXT",
49            FieldType::Numeric => "NUMERIC",
50            FieldType::Tag => "TAG",
51            FieldType::Geo => "GEO",
52            FieldType::Vector => "VECTOR",
53        }
54    }
55}
56
57/// A field definition for a RediSearch schema.
58#[derive(Clone)]
59pub struct SchemaField {
60    /// Field name.
61    pub name: String,
62    /// Field type.
63    pub field_type: FieldType,
64    /// Whether the field is sortable.
65    pub sortable: bool,
66    /// Whether to skip indexing this field.
67    pub noindex: bool,
68}
69
70/// Data structure type for FT.CREATE.
71#[derive(Clone)]
72pub enum OnType {
73    /// Index HASH keys.
74    Hash,
75    /// Index JSON keys.
76    Json,
77}
78
79/// FT.CREATE index \[ON HASH|JSON\] \[PREFIX count prefix ...\] SCHEMA field type ...
80///
81/// Creates a new search index with the given schema. Uses a builder pattern
82/// for constructing the index definition.
83#[derive(Clone)]
84pub struct FtCreate {
85    index: String,
86    on_type: Option<OnType>,
87    prefixes: Vec<String>,
88    fields: Vec<SchemaField>,
89}
90
91impl FtCreate {
92    /// Create a new [`FtCreate`] command.
93    pub fn new(index: impl Into<String>) -> Self {
94        Self {
95            index: index.into(),
96            on_type: None,
97            prefixes: Vec::new(),
98            fields: Vec::new(),
99        }
100    }
101
102    /// Index HASH keys.
103    pub fn on_hash(mut self) -> Self {
104        self.on_type = Some(OnType::Hash);
105        self
106    }
107
108    /// Index JSON keys.
109    pub fn on_json(mut self) -> Self {
110        self.on_type = Some(OnType::Json);
111        self
112    }
113
114    /// Add a key prefix filter.
115    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
116        self.prefixes.push(prefix.into());
117        self
118    }
119
120    /// Add a field to the schema.
121    pub fn field(mut self, name: impl Into<String>, field_type: FieldType) -> Self {
122        self.fields.push(SchemaField {
123            name: name.into(),
124            field_type,
125            sortable: false,
126            noindex: false,
127        });
128        self
129    }
130
131    /// Add a sortable field to the schema.
132    pub fn sortable_field(mut self, name: impl Into<String>, field_type: FieldType) -> Self {
133        self.fields.push(SchemaField {
134            name: name.into(),
135            field_type,
136            sortable: true,
137            noindex: false,
138        });
139        self
140    }
141
142    /// Add a field with full options.
143    pub fn schema_field(mut self, field: SchemaField) -> Self {
144        self.fields.push(field);
145        self
146    }
147}
148
149impl Command for FtCreate {
150    type Response = ();
151
152    fn to_frame(&self) -> Frame {
153        let mut args = vec![bulk("FT.CREATE"), bulk(self.index.as_str())];
154
155        if let Some(on_type) = &self.on_type {
156            args.push(bulk("ON"));
157            match on_type {
158                OnType::Hash => args.push(bulk("HASH")),
159                OnType::Json => args.push(bulk("JSON")),
160            }
161        }
162
163        if !self.prefixes.is_empty() {
164            args.push(bulk("PREFIX"));
165            args.push(bulk(self.prefixes.len().to_string()));
166            for prefix in &self.prefixes {
167                args.push(bulk(prefix.as_str()));
168            }
169        }
170
171        args.push(bulk("SCHEMA"));
172        for field in &self.fields {
173            args.push(bulk(field.name.as_str()));
174            args.push(bulk(field.field_type.as_str()));
175            if field.sortable {
176                args.push(bulk("SORTABLE"));
177            }
178            if field.noindex {
179                args.push(bulk("NOINDEX"));
180            }
181        }
182
183        array(args)
184    }
185
186    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
187        match frame {
188            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
189            other => Err(RedisError::UnexpectedResponse {
190                expected: "OK",
191                actual: format!("{other:?}"),
192            }),
193        }
194    }
195
196    fn name(&self) -> &str {
197        "FT.CREATE"
198    }
199}
200
201/// FT.DROPINDEX index \[DD\]
202///
203/// Deletes a search index. With `DD`, also deletes the indexed documents.
204#[derive(Clone)]
205pub struct FtDropIndex {
206    index: String,
207    dd: bool,
208}
209
210impl FtDropIndex {
211    /// Create a new [`FtDropIndex`] command.
212    pub fn new(index: impl Into<String>) -> Self {
213        Self {
214            index: index.into(),
215            dd: false,
216        }
217    }
218
219    /// Also delete the indexed documents.
220    pub fn dd(mut self) -> Self {
221        self.dd = true;
222        self
223    }
224}
225
226impl Command for FtDropIndex {
227    type Response = ();
228
229    fn to_frame(&self) -> Frame {
230        let mut args = vec![bulk("FT.DROPINDEX"), bulk(self.index.as_str())];
231        if self.dd {
232            args.push(bulk("DD"));
233        }
234        array(args)
235    }
236
237    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
238        match frame {
239            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
240            other => Err(RedisError::UnexpectedResponse {
241                expected: "OK",
242                actual: format!("{other:?}"),
243            }),
244        }
245    }
246
247    fn name(&self) -> &str {
248        "FT.DROPINDEX"
249    }
250}
251
252/// FT.ALTER index SCHEMA ADD field type ...
253///
254/// Adds new fields to an existing index schema.
255#[derive(Clone)]
256pub struct FtAlter {
257    index: String,
258    fields: Vec<SchemaField>,
259}
260
261impl FtAlter {
262    /// Create a new [`FtAlter`] command.
263    pub fn new(index: impl Into<String>) -> Self {
264        Self {
265            index: index.into(),
266            fields: Vec::new(),
267        }
268    }
269
270    /// Add a field to the schema.
271    pub fn field(mut self, name: impl Into<String>, field_type: FieldType) -> Self {
272        self.fields.push(SchemaField {
273            name: name.into(),
274            field_type,
275            sortable: false,
276            noindex: false,
277        });
278        self
279    }
280
281    /// Add a field with full options.
282    pub fn schema_field(mut self, field: SchemaField) -> Self {
283        self.fields.push(field);
284        self
285    }
286}
287
288impl Command for FtAlter {
289    type Response = ();
290
291    fn to_frame(&self) -> Frame {
292        let mut args = vec![
293            bulk("FT.ALTER"),
294            bulk(self.index.as_str()),
295            bulk("SCHEMA"),
296            bulk("ADD"),
297        ];
298        for field in &self.fields {
299            args.push(bulk(field.name.as_str()));
300            args.push(bulk(field.field_type.as_str()));
301            if field.sortable {
302                args.push(bulk("SORTABLE"));
303            }
304            if field.noindex {
305                args.push(bulk("NOINDEX"));
306            }
307        }
308        array(args)
309    }
310
311    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
312        match frame {
313            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
314            other => Err(RedisError::UnexpectedResponse {
315                expected: "OK",
316                actual: format!("{other:?}"),
317            }),
318        }
319    }
320
321    fn name(&self) -> &str {
322        "FT.ALTER"
323    }
324}
325
326/// FT.INFO index
327///
328/// Returns information and statistics about a search index. The response is
329/// a complex nested structure returned as a raw `Frame`.
330#[derive(Clone)]
331pub struct FtInfo {
332    index: String,
333}
334
335impl FtInfo {
336    /// Create a new [`FtInfo`] command.
337    pub fn new(index: impl Into<String>) -> Self {
338        Self {
339            index: index.into(),
340        }
341    }
342}
343
344impl Command for FtInfo {
345    type Response = Frame;
346
347    fn to_frame(&self) -> Frame {
348        array(vec![bulk("FT.INFO"), bulk(self.index.as_str())])
349    }
350
351    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
352        Ok(frame)
353    }
354
355    fn name(&self) -> &str {
356        "FT.INFO"
357    }
358
359    fn idempotent(&self) -> bool {
360        true
361    }
362}
363
364/// FT._LIST
365///
366/// Returns a list of all existing search index names.
367#[derive(Clone)]
368pub struct FtList;
369
370impl FtList {
371    /// Create a new [`FtList`] command.
372    pub fn new() -> Self {
373        Self
374    }
375}
376
377impl Default for FtList {
378    fn default() -> Self {
379        Self::new()
380    }
381}
382
383impl Command for FtList {
384    type Response = Vec<Bytes>;
385
386    fn to_frame(&self) -> Frame {
387        array(vec![bulk("FT._LIST")])
388    }
389
390    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
391        match frame {
392            Frame::Array(Some(frames)) | Frame::Set(frames) | Frame::StreamedSet(frames) => frames
393                .into_iter()
394                .map(|f| match f {
395                    Frame::BulkString(Some(data)) | Frame::SimpleString(data) => Ok(data),
396                    other => Err(RedisError::UnexpectedResponse {
397                        expected: "bulk or simple string",
398                        actual: format!("{other:?}"),
399                    }),
400                })
401                .collect(),
402            other => Err(RedisError::UnexpectedResponse {
403                expected: "array or set",
404                actual: format!("{other:?}"),
405            }),
406        }
407    }
408
409    fn name(&self) -> &str {
410        "FT._LIST"
411    }
412}
413
414/// FT.SEARCH index query \[LIMIT offset num\] \[RETURN count field ...\]
415/// \[SORTBY field ASC|DESC\] \[NOCONTENT\] \[VERBATIM\] \[WITHSCORES\]
416///
417/// Searches the index with the given query. Uses a builder pattern for
418/// optional parameters. Returns a raw `Frame` containing the result count
419/// and document array.
420#[derive(Clone)]
421pub struct FtSearch {
422    index: String,
423    query: String,
424    limit_offset: Option<u64>,
425    limit_num: Option<u64>,
426    return_fields: Vec<String>,
427    sortby: Option<(String, SortOrder)>,
428    nocontent: bool,
429    verbatim: bool,
430    withscores: bool,
431}
432
433impl FtSearch {
434    /// Create a new [`FtSearch`] command.
435    pub fn new(index: impl Into<String>, query: impl Into<String>) -> Self {
436        Self {
437            index: index.into(),
438            query: query.into(),
439            limit_offset: None,
440            limit_num: None,
441            return_fields: Vec::new(),
442            sortby: None,
443            nocontent: false,
444            verbatim: false,
445            withscores: false,
446        }
447    }
448
449    /// Set the LIMIT clause with offset and number of results.
450    pub fn limit(mut self, offset: u64, num: u64) -> Self {
451        self.limit_offset = Some(offset);
452        self.limit_num = Some(num);
453        self
454    }
455
456    /// Set the fields to return.
457    pub fn return_fields(mut self, fields: &[impl AsRef<str>]) -> Self {
458        self.return_fields = fields.iter().map(|f| f.as_ref().to_string()).collect();
459        self
460    }
461
462    /// Sort results by a field.
463    pub fn sortby(mut self, field: impl Into<String>, order: SortOrder) -> Self {
464        self.sortby = Some((field.into(), order));
465        self
466    }
467
468    /// Return only document IDs, not content.
469    pub fn nocontent(mut self) -> Self {
470        self.nocontent = true;
471        self
472    }
473
474    /// Do not try to use stemming for query expansion.
475    pub fn verbatim(mut self) -> Self {
476        self.verbatim = true;
477        self
478    }
479
480    /// Include scores in the results.
481    pub fn withscores(mut self) -> Self {
482        self.withscores = true;
483        self
484    }
485}
486
487impl Command for FtSearch {
488    type Response = Frame;
489
490    fn to_frame(&self) -> Frame {
491        let mut args = vec![
492            bulk("FT.SEARCH"),
493            bulk(self.index.as_str()),
494            bulk(self.query.as_str()),
495        ];
496
497        if self.nocontent {
498            args.push(bulk("NOCONTENT"));
499        }
500        if self.verbatim {
501            args.push(bulk("VERBATIM"));
502        }
503        if self.withscores {
504            args.push(bulk("WITHSCORES"));
505        }
506
507        if let Some(offset) = self.limit_offset {
508            args.push(bulk("LIMIT"));
509            args.push(bulk(offset.to_string()));
510            if let Some(num) = self.limit_num {
511                args.push(bulk(num.to_string()));
512            }
513        }
514
515        if !self.return_fields.is_empty() {
516            args.push(bulk("RETURN"));
517            args.push(bulk(self.return_fields.len().to_string()));
518            for field in &self.return_fields {
519                args.push(bulk(field.as_str()));
520            }
521        }
522
523        if let Some((field, order)) = &self.sortby {
524            args.push(bulk("SORTBY"));
525            args.push(bulk(field.as_str()));
526            match order {
527                SortOrder::Asc => args.push(bulk("ASC")),
528                SortOrder::Desc => args.push(bulk("DESC")),
529            }
530        }
531
532        array(args)
533    }
534
535    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
536        Ok(frame)
537    }
538
539    fn name(&self) -> &str {
540        "FT.SEARCH"
541    }
542
543    fn idempotent(&self) -> bool {
544        true
545    }
546}
547
548/// FT.AGGREGATE index query \[GROUPBY nargs property ...\]
549/// \[REDUCE func nargs arg ...\] \[SORTBY nargs property ASC|DESC ...\]
550/// \[LIMIT offset num\] \[APPLY expr AS alias\]
551///
552/// Runs an aggregation query against the index. Returns a raw `Frame`.
553#[derive(Clone)]
554pub struct FtAggregate {
555    index: String,
556    query: String,
557    groupby: Vec<String>,
558    reduce: Vec<(String, Vec<String>, Option<String>)>,
559    sortby: Vec<(String, SortOrder)>,
560    limit_offset: Option<u64>,
561    limit_num: Option<u64>,
562    apply: Vec<(String, String)>,
563    with_cursor: bool,
564    cursor_count: Option<u64>,
565    cursor_maxidle: Option<u64>,
566}
567
568impl FtAggregate {
569    /// Create a new [`FtAggregate`] command.
570    pub fn new(index: impl Into<String>, query: impl Into<String>) -> Self {
571        Self {
572            index: index.into(),
573            query: query.into(),
574            groupby: Vec::new(),
575            reduce: Vec::new(),
576            sortby: Vec::new(),
577            limit_offset: None,
578            limit_num: None,
579            apply: Vec::new(),
580            with_cursor: false,
581            cursor_count: None,
582            cursor_maxidle: None,
583        }
584    }
585
586    /// Add a GROUPBY property.
587    pub fn groupby(mut self, properties: &[impl AsRef<str>]) -> Self {
588        self.groupby = properties.iter().map(|p| p.as_ref().to_string()).collect();
589        self
590    }
591
592    /// Add a REDUCE function with arguments and optional alias.
593    pub fn reduce(
594        mut self,
595        func: impl Into<String>,
596        args: &[impl AsRef<str>],
597        alias: Option<impl Into<String>>,
598    ) -> Self {
599        self.reduce.push((
600            func.into(),
601            args.iter().map(|a| a.as_ref().to_string()).collect(),
602            alias.map(Into::into),
603        ));
604        self
605    }
606
607    /// Add a SORTBY field with order.
608    pub fn sortby(mut self, field: impl Into<String>, order: SortOrder) -> Self {
609        self.sortby.push((field.into(), order));
610        self
611    }
612
613    /// Set the LIMIT clause.
614    pub fn limit(mut self, offset: u64, num: u64) -> Self {
615        self.limit_offset = Some(offset);
616        self.limit_num = Some(num);
617        self
618    }
619
620    /// Add an APPLY expression with an alias.
621    pub fn apply(mut self, expr: impl Into<String>, alias: impl Into<String>) -> Self {
622        self.apply.push((expr.into(), alias.into()));
623        self
624    }
625
626    /// Request a cursor for incremental result retrieval (`WITHCURSOR`).
627    ///
628    /// Read subsequent batches with [`FtCursorRead`] and release the cursor
629    /// with [`FtCursorDel`].
630    pub fn with_cursor(mut self) -> Self {
631        self.with_cursor = true;
632        self
633    }
634
635    /// Request a cursor and set its batch size (`WITHCURSOR COUNT n`).
636    pub fn with_cursor_count(mut self, count: u64) -> Self {
637        self.with_cursor = true;
638        self.cursor_count = Some(count);
639        self
640    }
641
642    /// Set the cursor's idle timeout in milliseconds (`MAXIDLE ms`).
643    ///
644    /// Implies `WITHCURSOR`.
645    pub fn cursor_maxidle(mut self, maxidle: u64) -> Self {
646        self.with_cursor = true;
647        self.cursor_maxidle = Some(maxidle);
648        self
649    }
650}
651
652impl Command for FtAggregate {
653    type Response = Frame;
654
655    fn to_frame(&self) -> Frame {
656        let mut args = vec![
657            bulk("FT.AGGREGATE"),
658            bulk(self.index.as_str()),
659            bulk(self.query.as_str()),
660        ];
661
662        if !self.groupby.is_empty() {
663            args.push(bulk("GROUPBY"));
664            args.push(bulk(self.groupby.len().to_string()));
665            for prop in &self.groupby {
666                args.push(bulk(prop.as_str()));
667            }
668
669            for (func, func_args, alias) in &self.reduce {
670                args.push(bulk("REDUCE"));
671                args.push(bulk(func.as_str()));
672                args.push(bulk(func_args.len().to_string()));
673                for arg in func_args {
674                    args.push(bulk(arg.as_str()));
675                }
676                if let Some(alias) = alias {
677                    args.push(bulk("AS"));
678                    args.push(bulk(alias.as_str()));
679                }
680            }
681        }
682
683        if !self.sortby.is_empty() {
684            args.push(bulk("SORTBY"));
685            // nargs = 2 * number of fields (field + order)
686            args.push(bulk((self.sortby.len() * 2).to_string()));
687            for (field, order) in &self.sortby {
688                args.push(bulk(field.as_str()));
689                match order {
690                    SortOrder::Asc => args.push(bulk("ASC")),
691                    SortOrder::Desc => args.push(bulk("DESC")),
692                }
693            }
694        }
695
696        for (expr, alias) in &self.apply {
697            args.push(bulk("APPLY"));
698            args.push(bulk(expr.as_str()));
699            args.push(bulk("AS"));
700            args.push(bulk(alias.as_str()));
701        }
702
703        if let Some(offset) = self.limit_offset {
704            args.push(bulk("LIMIT"));
705            args.push(bulk(offset.to_string()));
706            if let Some(num) = self.limit_num {
707                args.push(bulk(num.to_string()));
708            }
709        }
710
711        if self.with_cursor {
712            args.push(bulk("WITHCURSOR"));
713            if let Some(count) = self.cursor_count {
714                args.push(bulk("COUNT"));
715                args.push(bulk(count.to_string()));
716            }
717            if let Some(maxidle) = self.cursor_maxidle {
718                args.push(bulk("MAXIDLE"));
719                args.push(bulk(maxidle.to_string()));
720            }
721        }
722
723        array(args)
724    }
725
726    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
727        Ok(frame)
728    }
729
730    fn name(&self) -> &str {
731        "FT.AGGREGATE"
732    }
733}
734
735/// FT.CURSOR READ index cursor_id \[COUNT n\]
736///
737/// Reads the next batch of results from a cursor created by an
738/// [`FtAggregate`] with `WITHCURSOR`. Returns the same raw `Frame` shape as
739/// `FT.AGGREGATE`: an array of `[results, next_cursor_id]`. A `next_cursor_id`
740/// of `0` indicates the cursor is exhausted.
741///
742/// # Example
743///
744/// ```no_run
745/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
746/// use redis_tower_commands::FtCursorRead;
747/// use redis_tower_core::RedisConnection;
748///
749/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
750///
751/// let batch = conn.execute(FtCursorRead::new("idx", 42).count(100)).await?;
752/// # let _ = batch;
753/// # Ok(())
754/// # }
755/// ```
756#[derive(Clone)]
757pub struct FtCursorRead {
758    index: String,
759    cursor_id: u64,
760    count: Option<u64>,
761}
762
763impl FtCursorRead {
764    /// Create a new [`FtCursorRead`] command.
765    pub fn new(index: impl Into<String>, cursor_id: u64) -> Self {
766        Self {
767            index: index.into(),
768            cursor_id,
769            count: None,
770        }
771    }
772
773    /// Set the number of results to read in this batch (`COUNT n`).
774    pub fn count(mut self, count: u64) -> Self {
775        self.count = Some(count);
776        self
777    }
778}
779
780impl Command for FtCursorRead {
781    type Response = Frame;
782
783    fn to_frame(&self) -> Frame {
784        let mut args = vec![
785            bulk("FT.CURSOR"),
786            bulk("READ"),
787            bulk(self.index.as_str()),
788            bulk(self.cursor_id.to_string()),
789        ];
790        if let Some(count) = self.count {
791            args.push(bulk("COUNT"));
792            args.push(bulk(count.to_string()));
793        }
794        array(args)
795    }
796
797    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
798        Ok(frame)
799    }
800
801    fn name(&self) -> &str {
802        "FT.CURSOR"
803    }
804}
805
806/// FT.CURSOR DEL index cursor_id
807///
808/// Releases a cursor created by an [`FtAggregate`] with `WITHCURSOR`. Returns
809/// `Ok(())` on success.
810///
811/// # Example
812///
813/// ```no_run
814/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
815/// use redis_tower_commands::FtCursorDel;
816/// use redis_tower_core::RedisConnection;
817///
818/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
819///
820/// conn.execute(FtCursorDel::new("idx", 42)).await?;
821/// # Ok(())
822/// # }
823/// ```
824#[derive(Clone)]
825pub struct FtCursorDel {
826    index: String,
827    cursor_id: u64,
828}
829
830impl FtCursorDel {
831    /// Create a new [`FtCursorDel`] command.
832    pub fn new(index: impl Into<String>, cursor_id: u64) -> Self {
833        Self {
834            index: index.into(),
835            cursor_id,
836        }
837    }
838}
839
840impl Command for FtCursorDel {
841    type Response = ();
842
843    fn to_frame(&self) -> Frame {
844        array(vec![
845            bulk("FT.CURSOR"),
846            bulk("DEL"),
847            bulk(self.index.as_str()),
848            bulk(self.cursor_id.to_string()),
849        ])
850    }
851
852    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
853        match frame {
854            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
855            other => Err(RedisError::UnexpectedResponse {
856                expected: "OK",
857                actual: format!("{other:?}"),
858            }),
859        }
860    }
861
862    fn name(&self) -> &str {
863        "FT.CURSOR"
864    }
865}
866
867/// FT.ALIASADD alias index
868///
869/// Adds an alias to a search index.
870#[derive(Clone)]
871pub struct FtAliasAdd {
872    alias: String,
873    index: String,
874}
875
876impl FtAliasAdd {
877    /// Create a new [`FtAliasAdd`] command.
878    pub fn new(alias: impl Into<String>, index: impl Into<String>) -> Self {
879        Self {
880            alias: alias.into(),
881            index: index.into(),
882        }
883    }
884}
885
886impl Command for FtAliasAdd {
887    type Response = ();
888
889    fn to_frame(&self) -> Frame {
890        array(vec![
891            bulk("FT.ALIASADD"),
892            bulk(self.alias.as_str()),
893            bulk(self.index.as_str()),
894        ])
895    }
896
897    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
898        match frame {
899            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
900            other => Err(RedisError::UnexpectedResponse {
901                expected: "OK",
902                actual: format!("{other:?}"),
903            }),
904        }
905    }
906
907    fn name(&self) -> &str {
908        "FT.ALIASADD"
909    }
910}
911
912/// FT.ALIASDEL alias
913///
914/// Removes an alias from a search index.
915#[derive(Clone)]
916pub struct FtAliasDel {
917    alias: String,
918}
919
920impl FtAliasDel {
921    /// Create a new [`FtAliasDel`] command.
922    pub fn new(alias: impl Into<String>) -> Self {
923        Self {
924            alias: alias.into(),
925        }
926    }
927}
928
929impl Command for FtAliasDel {
930    type Response = ();
931
932    fn to_frame(&self) -> Frame {
933        array(vec![bulk("FT.ALIASDEL"), bulk(self.alias.as_str())])
934    }
935
936    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
937        match frame {
938            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
939            other => Err(RedisError::UnexpectedResponse {
940                expected: "OK",
941                actual: format!("{other:?}"),
942            }),
943        }
944    }
945
946    fn name(&self) -> &str {
947        "FT.ALIASDEL"
948    }
949}
950
951/// FT.ALIASUPDATE alias index
952///
953/// Updates an alias to point to a different search index.
954#[derive(Clone)]
955pub struct FtAliasUpdate {
956    alias: String,
957    index: String,
958}
959
960impl FtAliasUpdate {
961    /// Create a new [`FtAliasUpdate`] command.
962    pub fn new(alias: impl Into<String>, index: impl Into<String>) -> Self {
963        Self {
964            alias: alias.into(),
965            index: index.into(),
966        }
967    }
968}
969
970impl Command for FtAliasUpdate {
971    type Response = ();
972
973    fn to_frame(&self) -> Frame {
974        array(vec![
975            bulk("FT.ALIASUPDATE"),
976            bulk(self.alias.as_str()),
977            bulk(self.index.as_str()),
978        ])
979    }
980
981    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
982        match frame {
983            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
984            other => Err(RedisError::UnexpectedResponse {
985                expected: "OK",
986                actual: format!("{other:?}"),
987            }),
988        }
989    }
990
991    fn name(&self) -> &str {
992        "FT.ALIASUPDATE"
993    }
994}
995
996/// FT.EXPLAIN index query \[DIALECT dialect\]
997///
998/// Returns the textual execution plan for a search query.
999#[derive(Clone)]
1000pub struct FtExplain {
1001    index: String,
1002    query: String,
1003    dialect: Option<u64>,
1004}
1005
1006impl FtExplain {
1007    /// Create an `FT.EXPLAIN` command for `query`.
1008    pub fn new(index: impl Into<String>, query: impl Into<String>) -> Self {
1009        Self {
1010            index: index.into(),
1011            query: query.into(),
1012            dialect: None,
1013        }
1014    }
1015
1016    /// Select the query dialect used to parse the query.
1017    pub fn dialect(mut self, dialect: u64) -> Self {
1018        self.dialect = Some(dialect);
1019        self
1020    }
1021}
1022
1023impl Command for FtExplain {
1024    type Response = String;
1025
1026    fn to_frame(&self) -> Frame {
1027        let mut args = vec![
1028            bulk("FT.EXPLAIN"),
1029            bulk(self.index.as_str()),
1030            bulk(self.query.as_str()),
1031        ];
1032        if let Some(dialect) = self.dialect {
1033            args.push(bulk("DIALECT"));
1034            args.push(bulk(dialect.to_string()));
1035        }
1036        array(args)
1037    }
1038
1039    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1040        parse_text(frame, "bulk string containing a query execution plan")
1041    }
1042
1043    fn name(&self) -> &str {
1044        "FT.EXPLAIN"
1045    }
1046
1047    fn idempotent(&self) -> bool {
1048        true
1049    }
1050}
1051
1052/// FT.EXPLAINCLI index query \[DIALECT dialect\]
1053///
1054/// Returns the execution plan as separate, CLI-friendly lines.
1055#[derive(Clone)]
1056pub struct FtExplainCli {
1057    index: String,
1058    query: String,
1059    dialect: Option<u64>,
1060}
1061
1062impl FtExplainCli {
1063    /// Create an `FT.EXPLAINCLI` command for `query`.
1064    pub fn new(index: impl Into<String>, query: impl Into<String>) -> Self {
1065        Self {
1066            index: index.into(),
1067            query: query.into(),
1068            dialect: None,
1069        }
1070    }
1071
1072    /// Select the query dialect used to parse the query.
1073    pub fn dialect(mut self, dialect: u64) -> Self {
1074        self.dialect = Some(dialect);
1075        self
1076    }
1077}
1078
1079impl Command for FtExplainCli {
1080    type Response = Vec<String>;
1081
1082    fn to_frame(&self) -> Frame {
1083        let mut args = vec![
1084            bulk("FT.EXPLAINCLI"),
1085            bulk(self.index.as_str()),
1086            bulk(self.query.as_str()),
1087        ];
1088        if let Some(dialect) = self.dialect {
1089            args.push(bulk("DIALECT"));
1090            args.push(bulk(dialect.to_string()));
1091        }
1092        array(args)
1093    }
1094
1095    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1096        match frame {
1097            Frame::Array(Some(frames)) => frames
1098                .into_iter()
1099                .map(|frame| parse_text(frame, "bulk string containing an execution-plan line"))
1100                .collect(),
1101            Frame::Array(None) => Ok(Vec::new()),
1102            other => Err(RedisError::UnexpectedResponse {
1103                expected: "array of execution-plan lines",
1104                actual: format!("{other:?}"),
1105            }),
1106        }
1107    }
1108
1109    fn name(&self) -> &str {
1110        "FT.EXPLAINCLI"
1111    }
1112
1113    fn idempotent(&self) -> bool {
1114        true
1115    }
1116}
1117
1118fn parse_text(frame: Frame, expected: &'static str) -> Result<String, RedisError> {
1119    match frame {
1120        Frame::BulkString(Some(data))
1121        | Frame::SimpleString(data)
1122        | Frame::VerbatimString(_, data) => Ok(String::from_utf8_lossy(&data).into_owned()),
1123        other => Err(RedisError::UnexpectedResponse {
1124            expected,
1125            actual: format!("{other:?}"),
1126        }),
1127    }
1128}
1129
1130/// K-nearest-neighbor options for [`FtHybrid`].
1131#[derive(Clone)]
1132pub struct FtHybridKnn {
1133    k: u64,
1134    ef_runtime: Option<u64>,
1135    shard_k_ratio: Option<f64>,
1136}
1137
1138impl FtHybridKnn {
1139    /// Create a KNN query returning the nearest `k` vector candidates.
1140    pub fn new(k: u64) -> Self {
1141        Self {
1142            k,
1143            ef_runtime: None,
1144            shard_k_ratio: None,
1145        }
1146    }
1147
1148    /// Set the runtime search breadth.
1149    pub fn ef_runtime(mut self, ef_runtime: u64) -> Self {
1150        self.ef_runtime = Some(ef_runtime);
1151        self
1152    }
1153
1154    /// Set the per-shard candidate ratio used by clustered search.
1155    ///
1156    /// This option requires Redis 8.6.1 or later.
1157    pub fn shard_k_ratio(mut self, shard_k_ratio: f64) -> Self {
1158        self.shard_k_ratio = Some(shard_k_ratio);
1159        self
1160    }
1161
1162    fn append_args(&self, args: &mut Vec<Frame>) {
1163        let count = 2
1164            + usize::from(self.ef_runtime.is_some()) * 2
1165            + usize::from(self.shard_k_ratio.is_some()) * 2;
1166        args.push(bulk("KNN"));
1167        args.push(bulk(count.to_string()));
1168        args.push(bulk("K"));
1169        args.push(bulk(self.k.to_string()));
1170        if let Some(ef_runtime) = self.ef_runtime {
1171            args.push(bulk("EF_RUNTIME"));
1172            args.push(bulk(ef_runtime.to_string()));
1173        }
1174        if let Some(shard_k_ratio) = self.shard_k_ratio {
1175            args.push(bulk("SHARD_K_RATIO"));
1176            args.push(bulk(shard_k_ratio.to_string()));
1177        }
1178    }
1179}
1180
1181/// Vector-range options for [`FtHybrid`].
1182#[derive(Clone)]
1183pub struct FtHybridRange {
1184    radius: f64,
1185    epsilon: Option<f64>,
1186}
1187
1188impl FtHybridRange {
1189    /// Create a vector-range query with the maximum distance `radius`.
1190    pub fn new(radius: f64) -> Self {
1191        Self {
1192            radius,
1193            epsilon: None,
1194        }
1195    }
1196
1197    /// Set the range-query approximation factor.
1198    pub fn epsilon(mut self, epsilon: f64) -> Self {
1199        self.epsilon = Some(epsilon);
1200        self
1201    }
1202
1203    fn append_args(&self, args: &mut Vec<Frame>) {
1204        let count = 2 + usize::from(self.epsilon.is_some()) * 2;
1205        args.push(bulk("RANGE"));
1206        args.push(bulk(count.to_string()));
1207        args.push(bulk("RADIUS"));
1208        args.push(bulk(self.radius.to_string()));
1209        if let Some(epsilon) = self.epsilon {
1210            args.push(bulk("EPSILON"));
1211            args.push(bulk(epsilon.to_string()));
1212        }
1213    }
1214}
1215
1216#[derive(Clone)]
1217enum FtHybridVectorQuery {
1218    Default,
1219    Knn(FtHybridKnn),
1220    Range(FtHybridRange),
1221}
1222
1223/// Reciprocal-rank-fusion options for [`FtHybrid`].
1224#[derive(Clone, Default)]
1225pub struct FtHybridRrf {
1226    constant: Option<f64>,
1227    window: Option<u64>,
1228    score_alias: Option<String>,
1229}
1230
1231impl FtHybridRrf {
1232    /// Create an RRF configuration using Redis defaults.
1233    pub fn new() -> Self {
1234        Self::default()
1235    }
1236
1237    /// Set the RRF rank constant.
1238    pub fn constant(mut self, constant: f64) -> Self {
1239        self.constant = Some(constant);
1240        self
1241    }
1242
1243    /// Set the number of candidates considered from each sub-query.
1244    pub fn window(mut self, window: u64) -> Self {
1245        self.window = Some(window);
1246        self
1247    }
1248
1249    /// Alias the combined score for later pipeline operations.
1250    pub fn yield_score_as(mut self, alias: impl Into<String>) -> Self {
1251        self.score_alias = Some(alias.into());
1252        self
1253    }
1254
1255    fn append_args(&self, args: &mut Vec<Frame>) {
1256        let count = usize::from(self.constant.is_some()) * 2
1257            + usize::from(self.window.is_some()) * 2
1258            + usize::from(self.score_alias.is_some()) * 2;
1259        if count == 0 {
1260            // RRF with all defaults is FT.HYBRID's implicit combine mode.
1261            return;
1262        }
1263        args.push(bulk("COMBINE"));
1264        args.push(bulk("RRF"));
1265        args.push(bulk(count.to_string()));
1266        if let Some(constant) = self.constant {
1267            args.push(bulk("CONSTANT"));
1268            args.push(bulk(constant.to_string()));
1269        }
1270        if let Some(window) = self.window {
1271            args.push(bulk("WINDOW"));
1272            args.push(bulk(window.to_string()));
1273        }
1274        if let Some(alias) = &self.score_alias {
1275            args.push(bulk("YIELD_SCORE_AS"));
1276            args.push(bulk(alias.as_str()));
1277        }
1278    }
1279}
1280
1281/// Linear score-fusion options for [`FtHybrid`].
1282#[derive(Clone)]
1283pub struct FtHybridLinear {
1284    alpha: f64,
1285    beta: f64,
1286    window: Option<u64>,
1287    score_alias: Option<String>,
1288}
1289
1290impl FtHybridLinear {
1291    /// Create a linear fusion with text weight `alpha` and vector weight `beta`.
1292    pub fn new(alpha: f64, beta: f64) -> Self {
1293        Self {
1294            alpha,
1295            beta,
1296            window: None,
1297            score_alias: None,
1298        }
1299    }
1300
1301    /// Set the number of candidates considered from each sub-query.
1302    pub fn window(mut self, window: u64) -> Self {
1303        self.window = Some(window);
1304        self
1305    }
1306
1307    /// Alias the combined score for later pipeline operations.
1308    pub fn yield_score_as(mut self, alias: impl Into<String>) -> Self {
1309        self.score_alias = Some(alias.into());
1310        self
1311    }
1312
1313    fn append_args(&self, args: &mut Vec<Frame>) {
1314        let count = 4
1315            + usize::from(self.window.is_some()) * 2
1316            + usize::from(self.score_alias.is_some()) * 2;
1317        args.push(bulk("COMBINE"));
1318        args.push(bulk("LINEAR"));
1319        args.push(bulk(count.to_string()));
1320        args.push(bulk("ALPHA"));
1321        args.push(bulk(self.alpha.to_string()));
1322        args.push(bulk("BETA"));
1323        args.push(bulk(self.beta.to_string()));
1324        if let Some(window) = self.window {
1325            args.push(bulk("WINDOW"));
1326            args.push(bulk(window.to_string()));
1327        }
1328        if let Some(alias) = &self.score_alias {
1329            args.push(bulk("YIELD_SCORE_AS"));
1330            args.push(bulk(alias.as_str()));
1331        }
1332    }
1333}
1334
1335#[derive(Clone)]
1336enum FtHybridCombine {
1337    Default,
1338    Rrf(FtHybridRrf),
1339    Linear(FtHybridLinear),
1340}
1341
1342#[derive(Clone)]
1343enum FtHybridLoad {
1344    None,
1345    All,
1346    Fields(Vec<(String, Option<String>)>),
1347}
1348
1349/// FT.HYBRID index SEARCH query VSIM @vector_field $vector_param ...
1350///
1351/// Combines text and vector similarity search. The constructor binds the
1352/// required vector parameter to a binary-safe value; additional parameters and
1353/// pipeline operations can be added with the builder methods.
1354///
1355/// The serialized command intentionally uses the released Redis 8.4.4 grammar
1356/// without the later optional sub-query count, so it works across Redis 8.4.4
1357/// and newer.
1358///
1359/// Pipeline field expressions are serialized exactly as supplied. When a
1360/// method expects a field or previously yielded score alias, include Redis's
1361/// required `@` (or JSONPath `$`) sigil.
1362///
1363/// Returns the protocol-native response as a raw [`Frame`]: RESP2 uses an array
1364/// while RESP3 uses a map.
1365///
1366/// # Example
1367///
1368/// ```no_run
1369/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1370/// use bytes::Bytes;
1371/// use redis_tower_commands::{FtHybrid, FtHybridKnn};
1372/// use redis_tower_core::RedisConnection;
1373///
1374/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
1375/// let query_vector = Bytes::from_static(&[0, 0, 0, 0, 0, 0, 0, 0]);
1376/// let results = conn
1377///     .execute(
1378///         FtHybrid::new("products", "laptop", "embedding", "query_vec", query_vector)
1379///             .knn(FtHybridKnn::new(10))
1380///             .limit(0, 10),
1381///     )
1382///     .await?;
1383/// # let _ = results;
1384/// # Ok(())
1385/// # }
1386/// ```
1387#[derive(Clone)]
1388pub struct FtHybrid {
1389    index: String,
1390    search_query: String,
1391    vector_field: String,
1392    vector_param: String,
1393    vector: Bytes,
1394    scorer: Option<String>,
1395    search_score_alias: Option<String>,
1396    vector_query: FtHybridVectorQuery,
1397    vector_filter: Option<String>,
1398    vector_score_alias: Option<String>,
1399    combine: FtHybridCombine,
1400    limit: Option<(u64, u64)>,
1401    sortby: Option<(String, SortOrder)>,
1402    nosort: bool,
1403    load: FtHybridLoad,
1404    filter: Option<String>,
1405    params: Vec<(String, Bytes)>,
1406    timeout: Option<u64>,
1407}
1408
1409impl FtHybrid {
1410    /// Create a hybrid query and bind its required vector parameter.
1411    pub fn new(
1412        index: impl Into<String>,
1413        search_query: impl Into<String>,
1414        vector_field: impl Into<String>,
1415        vector_param: impl Into<String>,
1416        vector: impl Into<Bytes>,
1417    ) -> Self {
1418        Self {
1419            index: index.into(),
1420            search_query: search_query.into(),
1421            vector_field: strip_sigil(vector_field.into(), '@'),
1422            vector_param: strip_sigil(vector_param.into(), '$'),
1423            vector: vector.into(),
1424            scorer: None,
1425            search_score_alias: None,
1426            vector_query: FtHybridVectorQuery::Default,
1427            vector_filter: None,
1428            vector_score_alias: None,
1429            combine: FtHybridCombine::Default,
1430            limit: None,
1431            sortby: None,
1432            nosort: false,
1433            load: FtHybridLoad::None,
1434            filter: None,
1435            params: Vec::new(),
1436            timeout: None,
1437        }
1438    }
1439
1440    /// Select the text-search scorer.
1441    pub fn scorer(mut self, scorer: impl Into<String>) -> Self {
1442        self.scorer = Some(scorer.into());
1443        self
1444    }
1445
1446    /// Alias the text-search score.
1447    pub fn search_score_as(mut self, alias: impl Into<String>) -> Self {
1448        self.search_score_alias = Some(alias.into());
1449        self
1450    }
1451
1452    /// Configure K-nearest-neighbor vector search.
1453    pub fn knn(mut self, knn: FtHybridKnn) -> Self {
1454        self.vector_query = FtHybridVectorQuery::Knn(knn);
1455        self
1456    }
1457
1458    /// Configure vector-range search.
1459    pub fn range(mut self, range: FtHybridRange) -> Self {
1460        self.vector_query = FtHybridVectorQuery::Range(range);
1461        self
1462    }
1463
1464    /// Apply a pre-filter to the vector sub-query.
1465    pub fn vector_filter(mut self, filter: impl Into<String>) -> Self {
1466        self.vector_filter = Some(filter.into());
1467        self
1468    }
1469
1470    /// Alias the vector distance score.
1471    ///
1472    /// This uses the standalone alias position supported by Redis 8.4.4 and
1473    /// newer.
1474    pub fn vector_score_as(mut self, alias: impl Into<String>) -> Self {
1475        self.vector_score_alias = Some(alias.into());
1476        self
1477    }
1478
1479    /// Configure reciprocal-rank fusion.
1480    pub fn rrf(mut self, rrf: FtHybridRrf) -> Self {
1481        self.combine = FtHybridCombine::Rrf(rrf);
1482        self
1483    }
1484
1485    /// Configure linear score fusion.
1486    pub fn linear(mut self, linear: FtHybridLinear) -> Self {
1487        self.combine = FtHybridCombine::Linear(linear);
1488        self
1489    }
1490
1491    /// Limit the returned result window.
1492    pub fn limit(mut self, offset: u64, num: u64) -> Self {
1493        self.limit = Some((offset, num));
1494        self
1495    }
1496
1497    /// Sort results by a pipeline field or yielded score alias.
1498    ///
1499    /// The field is serialized verbatim; include Redis's required `@` (or
1500    /// JSONPath `$`) sigil, for example `@combined_score`.
1501    pub fn sortby(mut self, field: impl Into<String>, order: SortOrder) -> Self {
1502        self.sortby = Some((field.into(), order));
1503        self.nosort = false;
1504        self
1505    }
1506
1507    /// Preserve pipeline order rather than sorting the final results.
1508    pub fn nosort(mut self) -> Self {
1509        self.sortby = None;
1510        self.nosort = true;
1511        self
1512    }
1513
1514    /// Load a field into each result.
1515    ///
1516    /// The field is serialized verbatim; include Redis's required `@` (or
1517    /// JSONPath `$`) sigil.
1518    pub fn load_field(mut self, field: impl Into<String>) -> Self {
1519        self.load_fields_mut().push((field.into(), None));
1520        self
1521    }
1522
1523    /// Load a field under an alias.
1524    ///
1525    /// The field is serialized verbatim; include Redis's required `@` (or
1526    /// JSONPath `$`) sigil.
1527    pub fn load_field_as(mut self, field: impl Into<String>, alias: impl Into<String>) -> Self {
1528        self.load_fields_mut()
1529            .push((field.into(), Some(alias.into())));
1530        self
1531    }
1532
1533    /// Load all document fields.
1534    pub fn load_all(mut self) -> Self {
1535        self.load = FtHybridLoad::All;
1536        self
1537    }
1538
1539    /// Apply a post-combination pipeline filter.
1540    pub fn filter(mut self, filter: impl Into<String>) -> Self {
1541        self.filter = Some(filter.into());
1542        self
1543    }
1544
1545    /// Bind an additional binary-safe query parameter.
1546    ///
1547    /// A name matching the required vector parameter replaces its value.
1548    pub fn param(mut self, name: impl Into<String>, value: impl Into<Bytes>) -> Self {
1549        let name = strip_sigil(name.into(), '$');
1550        let value = value.into();
1551        if name == self.vector_param {
1552            self.vector = value;
1553        } else if let Some((_, existing)) = self
1554            .params
1555            .iter_mut()
1556            .find(|(existing, _)| existing == &name)
1557        {
1558            *existing = value;
1559        } else {
1560            self.params.push((name, value));
1561        }
1562        self
1563    }
1564
1565    /// Set the query timeout in milliseconds.
1566    pub fn timeout(mut self, timeout: u64) -> Self {
1567        self.timeout = Some(timeout);
1568        self
1569    }
1570
1571    fn load_fields_mut(&mut self) -> &mut Vec<(String, Option<String>)> {
1572        if !matches!(self.load, FtHybridLoad::Fields(_)) {
1573            self.load = FtHybridLoad::Fields(Vec::new());
1574        }
1575        match &mut self.load {
1576            FtHybridLoad::Fields(fields) => fields,
1577            FtHybridLoad::None | FtHybridLoad::All => unreachable!(),
1578        }
1579    }
1580
1581    fn append_query_args(&self, args: &mut Vec<Frame>) {
1582        args.push(bulk("SEARCH"));
1583        args.push(bulk(self.search_query.as_str()));
1584        if let Some(scorer) = &self.scorer {
1585            args.push(bulk("SCORER"));
1586            args.push(bulk(scorer.as_str()));
1587        }
1588        if let Some(alias) = &self.search_score_alias {
1589            args.push(bulk("YIELD_SCORE_AS"));
1590            args.push(bulk(alias.as_str()));
1591        }
1592
1593        args.push(bulk("VSIM"));
1594        args.push(bulk(format!("@{}", self.vector_field)));
1595        args.push(bulk(format!("${}", self.vector_param)));
1596        match &self.vector_query {
1597            FtHybridVectorQuery::Default => {}
1598            FtHybridVectorQuery::Knn(knn) => knn.append_args(args),
1599            FtHybridVectorQuery::Range(range) => range.append_args(args),
1600        }
1601        if let Some(filter) = &self.vector_filter {
1602            // The uncounted FILTER form is accepted by Redis 8.4.4 and remains
1603            // supported by newer versions for backward compatibility.
1604            args.push(bulk("FILTER"));
1605            args.push(bulk(filter.as_str()));
1606        }
1607        if let Some(alias) = &self.vector_score_alias {
1608            args.push(bulk("YIELD_SCORE_AS"));
1609            args.push(bulk(alias.as_str()));
1610        }
1611        match &self.combine {
1612            FtHybridCombine::Default => {}
1613            FtHybridCombine::Rrf(rrf) => rrf.append_args(args),
1614            FtHybridCombine::Linear(linear) => linear.append_args(args),
1615        }
1616
1617        if let Some((offset, num)) = self.limit {
1618            args.push(bulk("LIMIT"));
1619            args.push(bulk(offset.to_string()));
1620            args.push(bulk(num.to_string()));
1621        }
1622        if let Some((field, order)) = &self.sortby {
1623            args.push(bulk("SORTBY"));
1624            args.push(bulk("2"));
1625            args.push(bulk(field.as_str()));
1626            match order {
1627                SortOrder::Asc => args.push(bulk("ASC")),
1628                SortOrder::Desc => args.push(bulk("DESC")),
1629            }
1630        } else if self.nosort {
1631            args.push(bulk("NOSORT"));
1632        }
1633
1634        match &self.load {
1635            FtHybridLoad::None => {}
1636            FtHybridLoad::All => {
1637                args.push(bulk("LOAD"));
1638                args.push(bulk("*"));
1639            }
1640            FtHybridLoad::Fields(fields) if !fields.is_empty() => {
1641                // Redis counts serialized LOAD arguments, so `@field AS alias`
1642                // contributes three rather than one.
1643                let count = fields
1644                    .iter()
1645                    .map(|(_, alias)| if alias.is_some() { 3 } else { 1 })
1646                    .sum::<usize>();
1647                args.push(bulk("LOAD"));
1648                args.push(bulk(count.to_string()));
1649                for (field, alias) in fields {
1650                    args.push(bulk(field.as_str()));
1651                    if let Some(alias) = alias {
1652                        args.push(bulk("AS"));
1653                        args.push(bulk(alias.as_str()));
1654                    }
1655                }
1656            }
1657            FtHybridLoad::Fields(_) => {}
1658        }
1659
1660        if let Some(filter) = &self.filter {
1661            args.push(bulk("FILTER"));
1662            args.push(bulk(filter.as_str()));
1663        }
1664
1665        args.push(bulk("PARAMS"));
1666        args.push(bulk(((self.params.len() + 1) * 2).to_string()));
1667        args.push(bulk(self.vector_param.as_str()));
1668        args.push(bulk(self.vector.as_ref()));
1669        for (name, value) in &self.params {
1670            args.push(bulk(name.as_str()));
1671            args.push(bulk(value.as_ref()));
1672        }
1673
1674        if let Some(timeout) = self.timeout {
1675            args.push(bulk("TIMEOUT"));
1676            args.push(bulk(timeout.to_string()));
1677        }
1678    }
1679}
1680
1681fn strip_sigil(value: String, sigil: char) -> String {
1682    value.strip_prefix(sigil).unwrap_or(&value).to_string()
1683}
1684
1685impl Command for FtHybrid {
1686    type Response = Frame;
1687
1688    fn to_frame(&self) -> Frame {
1689        let mut args = vec![bulk("FT.HYBRID"), bulk(self.index.as_str())];
1690        self.append_query_args(&mut args);
1691        array(args)
1692    }
1693
1694    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1695        Ok(frame)
1696    }
1697
1698    fn name(&self) -> &str {
1699        "FT.HYBRID"
1700    }
1701
1702    fn idempotent(&self) -> bool {
1703        true
1704    }
1705}
1706
1707/// The query mode profiled by [`FtProfile`].
1708#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1709pub enum FtProfileType {
1710    /// Profile an `FT.SEARCH` query.
1711    Search,
1712    /// Profile an `FT.HYBRID` query.
1713    Hybrid,
1714    /// Profile an `FT.AGGREGATE` query.
1715    Aggregate,
1716}
1717
1718impl FtProfileType {
1719    fn as_str(self) -> &'static str {
1720        match self {
1721            FtProfileType::Search => "SEARCH",
1722            FtProfileType::Hybrid => "HYBRID",
1723            FtProfileType::Aggregate => "AGGREGATE",
1724        }
1725    }
1726}
1727
1728#[derive(Clone)]
1729enum FtProfileQuery {
1730    Text(String),
1731    Hybrid(Box<FtHybrid>),
1732}
1733
1734/// FT.PROFILE index SEARCH|HYBRID|AGGREGATE \[LIMITED\] QUERY query
1735///
1736/// Runs a `SEARCH`, `HYBRID`, or `AGGREGATE` query and returns both its results
1737/// and a detailed execution profile. The reply is a complex nested structure
1738/// returned as a raw [`Frame`]. Hybrid profiling requires Redis 8.8 or later.
1739///
1740/// # Example
1741///
1742/// ```no_run
1743/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1744/// use redis_tower_commands::FtProfile;
1745/// use redis_tower_core::RedisConnection;
1746///
1747/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
1748///
1749/// let profile = conn
1750///     .execute(FtProfile::search("idx", "hello world").limited())
1751///     .await?;
1752/// # let _ = profile;
1753/// # Ok(())
1754/// # }
1755/// ```
1756#[derive(Clone)]
1757pub struct FtProfile {
1758    index: String,
1759    query_type: FtProfileType,
1760    limited: bool,
1761    query: FtProfileQuery,
1762}
1763
1764impl FtProfile {
1765    /// Profile an `FT.SEARCH` query.
1766    pub fn search(index: impl Into<String>, query: impl Into<String>) -> Self {
1767        Self::new(index, FtProfileType::Search, query)
1768    }
1769
1770    /// Profile an `FT.AGGREGATE` query.
1771    pub fn aggregate(index: impl Into<String>, query: impl Into<String>) -> Self {
1772        Self::new(index, FtProfileType::Aggregate, query)
1773    }
1774
1775    /// Profile an [`FtHybrid`] query.
1776    ///
1777    /// Redis profiles the same typed query tail that [`FtHybrid`] would send,
1778    /// including its binary parameters and pipeline options.
1779    pub fn hybrid(query: FtHybrid) -> Self {
1780        Self {
1781            index: query.index.clone(),
1782            query_type: FtProfileType::Hybrid,
1783            limited: false,
1784            query: FtProfileQuery::Hybrid(Box::new(query)),
1785        }
1786    }
1787
1788    fn new(index: impl Into<String>, query_type: FtProfileType, query: impl Into<String>) -> Self {
1789        Self {
1790            index: index.into(),
1791            query_type,
1792            limited: false,
1793            query: FtProfileQuery::Text(query.into()),
1794        }
1795    }
1796
1797    /// Add the `LIMITED` flag, which removes per-record details from the
1798    /// reply-shadowing profile to reduce its size.
1799    pub fn limited(mut self) -> Self {
1800        self.limited = true;
1801        self
1802    }
1803}
1804
1805impl Command for FtProfile {
1806    type Response = Frame;
1807
1808    fn to_frame(&self) -> Frame {
1809        let mut args = vec![
1810            bulk("FT.PROFILE"),
1811            bulk(self.index.as_str()),
1812            bulk(self.query_type.as_str()),
1813        ];
1814        if self.limited {
1815            args.push(bulk("LIMITED"));
1816        }
1817        args.push(bulk("QUERY"));
1818        match &self.query {
1819            FtProfileQuery::Text(query) => args.push(bulk(query.as_str())),
1820            FtProfileQuery::Hybrid(query) => query.append_query_args(&mut args),
1821        }
1822        array(args)
1823    }
1824
1825    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1826        Ok(frame)
1827    }
1828
1829    fn name(&self) -> &str {
1830        "FT.PROFILE"
1831    }
1832
1833    fn idempotent(&self) -> bool {
1834        true
1835    }
1836}
1837
1838/// FT.TAGVALS index field_name
1839///
1840/// Returns the distinct set of indexed values for a `TAG` field. The values
1841/// are returned as exact bytes because tag values are not required to be UTF-8.
1842///
1843/// # Example
1844///
1845/// ```no_run
1846/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1847/// use redis_tower_commands::FtTagVals;
1848/// use redis_tower_core::RedisConnection;
1849///
1850/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
1851///
1852/// let cities = conn.execute(FtTagVals::new("idx", "city")).await?;
1853/// # let _ = cities;
1854/// # Ok(())
1855/// # }
1856/// ```
1857#[derive(Clone)]
1858pub struct FtTagVals {
1859    index: String,
1860    field: String,
1861}
1862
1863impl FtTagVals {
1864    /// Create a new [`FtTagVals`] command.
1865    pub fn new(index: impl Into<String>, field: impl Into<String>) -> Self {
1866        Self {
1867            index: index.into(),
1868            field: field.into(),
1869        }
1870    }
1871}
1872
1873impl Command for FtTagVals {
1874    type Response = Vec<Bytes>;
1875
1876    fn to_frame(&self) -> Frame {
1877        array(vec![
1878            bulk("FT.TAGVALS"),
1879            bulk(self.index.as_str()),
1880            bulk(self.field.as_str()),
1881        ])
1882    }
1883
1884    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1885        match frame {
1886            Frame::Array(Some(frames)) | Frame::Set(frames) => frames
1887                .into_iter()
1888                .map(|f| match f {
1889                    Frame::BulkString(Some(data)) | Frame::SimpleString(data) => Ok(data),
1890                    other => Err(RedisError::UnexpectedResponse {
1891                        expected: "bulk string",
1892                        actual: format!("{other:?}"),
1893                    }),
1894                })
1895                .collect(),
1896            Frame::Array(None) => Ok(Vec::new()),
1897            other => Err(RedisError::UnexpectedResponse {
1898                expected: "array",
1899                actual: format!("{other:?}"),
1900            }),
1901        }
1902    }
1903
1904    fn name(&self) -> &str {
1905        "FT.TAGVALS"
1906    }
1907
1908    fn idempotent(&self) -> bool {
1909        true
1910    }
1911}
1912
1913#[cfg(test)]
1914mod tests {
1915    use super::*;
1916    use redis_tower_core::Command;
1917    use redis_tower_protocol::helpers::{array, bulk};
1918
1919    #[test]
1920    fn idempotency_flags() {
1921        // Read-only commands are safe to retry.
1922        assert!(FtSearch::new("idx", "*").idempotent());
1923        // Mutating commands keep the default (false).
1924        assert!(!FtCreate::new("idx").idempotent());
1925    }
1926
1927    #[test]
1928    fn ft_list_accepts_resp2_array_and_resp3_sets() {
1929        let command = FtList::new();
1930        let expected = vec![
1931            Bytes::from_static(b"index-a"),
1932            Bytes::from_static(b"index-b"),
1933        ];
1934
1935        assert_eq!(
1936            command
1937                .parse_response(Frame::Array(Some(vec![bulk("index-a"), bulk("index-b")])))
1938                .unwrap(),
1939            expected
1940        );
1941        assert_eq!(
1942            command
1943                .parse_response(Frame::Set(vec![
1944                    Frame::SimpleString(Bytes::from_static(b"index-a")),
1945                    Frame::SimpleString(Bytes::from_static(b"index-b")),
1946                ]))
1947                .unwrap(),
1948            expected
1949        );
1950        assert_eq!(
1951            command
1952                .parse_response(Frame::StreamedSet(vec![
1953                    Frame::SimpleString(Bytes::from_static(b"index-a")),
1954                    Frame::BulkString(Some(Bytes::from_static(b"index-b"))),
1955                ]))
1956                .unwrap(),
1957            expected
1958        );
1959    }
1960
1961    #[test]
1962    fn ft_aggregate_with_cursor_count_to_frame() {
1963        let cmd = FtAggregate::new("idx", "*").with_cursor_count(100);
1964        assert_eq!(
1965            cmd.to_frame(),
1966            array(vec![
1967                bulk("FT.AGGREGATE"),
1968                bulk("idx"),
1969                bulk("*"),
1970                bulk("WITHCURSOR"),
1971                bulk("COUNT"),
1972                bulk("100"),
1973            ])
1974        );
1975    }
1976
1977    #[test]
1978    fn ft_aggregate_with_cursor_maxidle_to_frame() {
1979        let cmd = FtAggregate::new("idx", "*")
1980            .with_cursor()
1981            .cursor_maxidle(5000);
1982        assert_eq!(
1983            cmd.to_frame(),
1984            array(vec![
1985                bulk("FT.AGGREGATE"),
1986                bulk("idx"),
1987                bulk("*"),
1988                bulk("WITHCURSOR"),
1989                bulk("MAXIDLE"),
1990                bulk("5000"),
1991            ])
1992        );
1993    }
1994
1995    #[test]
1996    fn ft_aggregate_without_cursor_unchanged() {
1997        let cmd = FtAggregate::new("idx", "*");
1998        assert_eq!(
1999            cmd.to_frame(),
2000            array(vec![bulk("FT.AGGREGATE"), bulk("idx"), bulk("*")])
2001        );
2002    }
2003
2004    #[test]
2005    fn ft_cursor_read_to_frame() {
2006        let cmd = FtCursorRead::new("idx", 42).count(100);
2007        assert_eq!(
2008            cmd.to_frame(),
2009            array(vec![
2010                bulk("FT.CURSOR"),
2011                bulk("READ"),
2012                bulk("idx"),
2013                bulk("42"),
2014                bulk("COUNT"),
2015                bulk("100"),
2016            ])
2017        );
2018    }
2019
2020    #[test]
2021    fn ft_cursor_read_no_count_to_frame() {
2022        let cmd = FtCursorRead::new("idx", 7);
2023        assert_eq!(
2024            cmd.to_frame(),
2025            array(vec![
2026                bulk("FT.CURSOR"),
2027                bulk("READ"),
2028                bulk("idx"),
2029                bulk("7")
2030            ])
2031        );
2032    }
2033
2034    #[test]
2035    fn ft_cursor_del_to_frame() {
2036        let cmd = FtCursorDel::new("idx", 42);
2037        assert_eq!(
2038            cmd.to_frame(),
2039            array(vec![
2040                bulk("FT.CURSOR"),
2041                bulk("DEL"),
2042                bulk("idx"),
2043                bulk("42")
2044            ])
2045        );
2046    }
2047
2048    #[test]
2049    fn ft_explain_to_frame_and_parse_response() {
2050        let cmd = FtExplain::new("idx", "hello world").dialect(2);
2051        assert_eq!(
2052            cmd.to_frame(),
2053            array(vec![
2054                bulk("FT.EXPLAIN"),
2055                bulk("idx"),
2056                bulk("hello world"),
2057                bulk("DIALECT"),
2058                bulk("2"),
2059            ])
2060        );
2061        assert_eq!(
2062            cmd.parse_response(bulk("INTERSECT {\n  hello\n  world\n}"))
2063                .unwrap(),
2064            "INTERSECT {\n  hello\n  world\n}"
2065        );
2066        assert_eq!(
2067            cmd.parse_response(Frame::VerbatimString(
2068                Bytes::from_static(b"txt"),
2069                Bytes::from_static(b"hello")
2070            ))
2071            .unwrap(),
2072            "hello"
2073        );
2074        assert!(cmd.idempotent());
2075    }
2076
2077    #[test]
2078    fn ft_explain_cli_to_frame_and_parse_response() {
2079        let cmd = FtExplainCli::new("idx", "hello").dialect(4);
2080        assert_eq!(
2081            cmd.to_frame(),
2082            array(vec![
2083                bulk("FT.EXPLAINCLI"),
2084                bulk("idx"),
2085                bulk("hello"),
2086                bulk("DIALECT"),
2087                bulk("4"),
2088            ])
2089        );
2090        assert_eq!(
2091            cmd.parse_response(array(vec![
2092                bulk("UNION {"),
2093                Frame::SimpleString(Bytes::from_static(b"  hello")),
2094                Frame::VerbatimString(Bytes::from_static(b"txt"), Bytes::from_static(b"}")),
2095            ]))
2096            .unwrap(),
2097            vec!["UNION {", "  hello", "}"]
2098        );
2099        assert_eq!(
2100            cmd.parse_response(Frame::Array(None)).unwrap(),
2101            Vec::<String>::new()
2102        );
2103        assert!(cmd.idempotent());
2104    }
2105
2106    #[test]
2107    fn ft_hybrid_minimal_uses_redis_8_4_grammar() {
2108        let vector = Bytes::from_static(&[0, 0, 128, 63]);
2109        let cmd = FtHybrid::new("idx", "laptop", "@embedding", "$query_vec", vector.clone());
2110        assert_eq!(
2111            cmd.to_frame(),
2112            array(vec![
2113                bulk("FT.HYBRID"),
2114                bulk("idx"),
2115                bulk("SEARCH"),
2116                bulk("laptop"),
2117                bulk("VSIM"),
2118                bulk("@embedding"),
2119                bulk("$query_vec"),
2120                bulk("PARAMS"),
2121                bulk("2"),
2122                bulk("query_vec"),
2123                bulk(vector),
2124            ])
2125        );
2126        assert!(cmd.idempotent());
2127    }
2128
2129    #[test]
2130    fn ft_hybrid_knn_rrf_pipeline_counts_tokens() {
2131        let vector = Bytes::from_static(&[0, 0, 128, 63]);
2132        let cmd = FtHybrid::new("idx", "laptop", "embedding", "query_vec", vector.clone())
2133            .scorer("BM25")
2134            .search_score_as("text_score")
2135            .knn(FtHybridKnn::new(5).ef_runtime(100).shard_k_ratio(1.5))
2136            .vector_filter("@category:{tech}")
2137            .vector_score_as("vector_score")
2138            .rrf(
2139                FtHybridRrf::new()
2140                    .constant(50.0)
2141                    .window(20)
2142                    .yield_score_as("combined_score"),
2143            )
2144            .limit(0, 10)
2145            .sortby("@combined_score", SortOrder::Desc)
2146            .load_field("@title")
2147            .load_field_as("@category", "category")
2148            .filter("@price > 10")
2149            .param("$brand", "redis")
2150            .timeout(1000);
2151        assert_eq!(
2152            cmd.to_frame(),
2153            array(vec![
2154                bulk("FT.HYBRID"),
2155                bulk("idx"),
2156                bulk("SEARCH"),
2157                bulk("laptop"),
2158                bulk("SCORER"),
2159                bulk("BM25"),
2160                bulk("YIELD_SCORE_AS"),
2161                bulk("text_score"),
2162                bulk("VSIM"),
2163                bulk("@embedding"),
2164                bulk("$query_vec"),
2165                bulk("KNN"),
2166                bulk("6"),
2167                bulk("K"),
2168                bulk("5"),
2169                bulk("EF_RUNTIME"),
2170                bulk("100"),
2171                bulk("SHARD_K_RATIO"),
2172                bulk("1.5"),
2173                bulk("FILTER"),
2174                bulk("@category:{tech}"),
2175                bulk("YIELD_SCORE_AS"),
2176                bulk("vector_score"),
2177                bulk("COMBINE"),
2178                bulk("RRF"),
2179                bulk("6"),
2180                bulk("CONSTANT"),
2181                bulk("50"),
2182                bulk("WINDOW"),
2183                bulk("20"),
2184                bulk("YIELD_SCORE_AS"),
2185                bulk("combined_score"),
2186                bulk("LIMIT"),
2187                bulk("0"),
2188                bulk("10"),
2189                bulk("SORTBY"),
2190                bulk("2"),
2191                bulk("@combined_score"),
2192                bulk("DESC"),
2193                bulk("LOAD"),
2194                bulk("4"),
2195                bulk("@title"),
2196                bulk("@category"),
2197                bulk("AS"),
2198                bulk("category"),
2199                bulk("FILTER"),
2200                bulk("@price > 10"),
2201                bulk("PARAMS"),
2202                bulk("4"),
2203                bulk("query_vec"),
2204                bulk(vector),
2205                bulk("brand"),
2206                bulk("redis"),
2207                bulk("TIMEOUT"),
2208                bulk("1000"),
2209            ])
2210        );
2211    }
2212
2213    #[test]
2214    fn ft_hybrid_range_linear_load_all_and_nosort() {
2215        let vector = Bytes::from_static(&[0_u8; 8]);
2216        let cmd = FtHybrid::new("idx", "*", "embedding", "query_vec", vector.clone())
2217            .range(FtHybridRange::new(0.8).epsilon(0.1))
2218            .linear(
2219                FtHybridLinear::new(0.3, 0.7)
2220                    .window(40)
2221                    .yield_score_as("combined_score"),
2222            )
2223            .nosort()
2224            .load_all();
2225        assert_eq!(
2226            cmd.to_frame(),
2227            array(vec![
2228                bulk("FT.HYBRID"),
2229                bulk("idx"),
2230                bulk("SEARCH"),
2231                bulk("*"),
2232                bulk("VSIM"),
2233                bulk("@embedding"),
2234                bulk("$query_vec"),
2235                bulk("RANGE"),
2236                bulk("4"),
2237                bulk("RADIUS"),
2238                bulk("0.8"),
2239                bulk("EPSILON"),
2240                bulk("0.1"),
2241                bulk("COMBINE"),
2242                bulk("LINEAR"),
2243                bulk("8"),
2244                bulk("ALPHA"),
2245                bulk("0.3"),
2246                bulk("BETA"),
2247                bulk("0.7"),
2248                bulk("WINDOW"),
2249                bulk("40"),
2250                bulk("YIELD_SCORE_AS"),
2251                bulk("combined_score"),
2252                bulk("NOSORT"),
2253                bulk("LOAD"),
2254                bulk("*"),
2255                bulk("PARAMS"),
2256                bulk("2"),
2257                bulk("query_vec"),
2258                bulk(vector),
2259            ])
2260        );
2261    }
2262
2263    #[test]
2264    fn ft_profile_search_to_frame() {
2265        let cmd = FtProfile::search("idx", "hello");
2266        assert_eq!(
2267            cmd.to_frame(),
2268            array(vec![
2269                bulk("FT.PROFILE"),
2270                bulk("idx"),
2271                bulk("SEARCH"),
2272                bulk("QUERY"),
2273                bulk("hello"),
2274            ])
2275        );
2276    }
2277
2278    #[test]
2279    fn ft_profile_aggregate_limited_to_frame() {
2280        let cmd = FtProfile::aggregate("idx", "*").limited();
2281        assert_eq!(
2282            cmd.to_frame(),
2283            array(vec![
2284                bulk("FT.PROFILE"),
2285                bulk("idx"),
2286                bulk("AGGREGATE"),
2287                bulk("LIMITED"),
2288                bulk("QUERY"),
2289                bulk("*"),
2290            ])
2291        );
2292        assert!(cmd.idempotent());
2293    }
2294
2295    #[test]
2296    fn ft_profile_hybrid_reuses_typed_query_tail() {
2297        let vector = Bytes::from_static(&[0, 0, 128, 63]);
2298        let hybrid = FtHybrid::new("idx", "hello", "embedding", "query_vec", vector.clone())
2299            .knn(FtHybridKnn::new(3))
2300            .limit(0, 2);
2301        let cmd = FtProfile::hybrid(hybrid).limited();
2302        assert_eq!(
2303            cmd.to_frame(),
2304            array(vec![
2305                bulk("FT.PROFILE"),
2306                bulk("idx"),
2307                bulk("HYBRID"),
2308                bulk("LIMITED"),
2309                bulk("QUERY"),
2310                bulk("SEARCH"),
2311                bulk("hello"),
2312                bulk("VSIM"),
2313                bulk("@embedding"),
2314                bulk("$query_vec"),
2315                bulk("KNN"),
2316                bulk("2"),
2317                bulk("K"),
2318                bulk("3"),
2319                bulk("LIMIT"),
2320                bulk("0"),
2321                bulk("2"),
2322                bulk("PARAMS"),
2323                bulk("2"),
2324                bulk("query_vec"),
2325                bulk(vector),
2326            ])
2327        );
2328        assert!(cmd.idempotent());
2329    }
2330
2331    #[test]
2332    fn ft_tagvals_to_frame() {
2333        let cmd = FtTagVals::new("idx", "city");
2334        assert_eq!(
2335            cmd.to_frame(),
2336            array(vec![bulk("FT.TAGVALS"), bulk("idx"), bulk("city")])
2337        );
2338        assert!(cmd.idempotent());
2339    }
2340
2341    #[test]
2342    fn ft_tagvals_parse_response() {
2343        let cmd = FtTagVals::new("idx", "city");
2344        let reply = array(vec![bulk("london"), bulk("paris")]);
2345        assert_eq!(
2346            cmd.parse_response(reply).unwrap(),
2347            vec![Bytes::from_static(b"london"), Bytes::from_static(b"paris")]
2348        );
2349        assert_eq!(
2350            cmd.parse_response(Frame::Array(None)).unwrap(),
2351            Vec::<Bytes>::new()
2352        );
2353    }
2354}