Skip to main content

redis_tower_commands/
vector_sets.rs

1//! Redis 8 Vector Set commands.
2//!
3//! Available with the `vector-sets` feature (included by `stack`) and requiring
4//! a Redis server with Vector Set support. [`VAdd`] accepts typed floating-point
5//! vectors; similarity queries return command-specific element/score shapes.
6//! Verify the server version before enabling this family.
7//!
8//! ```
9//! use redis_tower_commands::VAdd;
10//! use redis_tower_core::Command;
11//!
12//! let command = VAdd::new("embeddings", vec![0.1, 0.2, 0.3], "doc:1");
13//! assert_eq!(command.name(), "VADD");
14//! ```
15//!
16//! See the [command cookbook] for feature and server prerequisites.
17//!
18//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#feature-gated-and-versioned-families
19
20use crate::CommandArg;
21use bytes::Bytes;
22use redis_tower_core::{Command, Frame, RedisError};
23use redis_tower_protocol::helpers::{array, bulk};
24
25/// Quantization type for VADD.
26#[derive(Clone)]
27pub enum VQuantization {
28    /// 8-bit quantization.
29    Q8,
30    /// 16-bit brain float quantization.
31    Bf16,
32    /// No quantization.
33    NoQuant,
34}
35
36/// VADD key (FP32 vector | VALUES num val ...) element \[REDUCE dim\] \[CAS\]
37/// \[M cap\] \[EF build\] \[SETATTR json\] \[QUANT Q8|BF16|NOQUANT\]
38///
39/// Adds an element with its vector to the vector set at `key`. Returns `true`
40/// if the element was added, `false` if it already existed (and was updated).
41#[derive(Clone)]
42pub struct VAdd {
43    key: CommandArg,
44    vector: Vec<f32>,
45    element: CommandArg,
46    reduce: Option<u64>,
47    cas: bool,
48    m: Option<u64>,
49    ef: Option<u64>,
50    setattr: Option<String>,
51    quant: Option<VQuantization>,
52}
53
54impl VAdd {
55    /// Create a new [`VAdd`] command.
56    pub fn new(
57        key: impl Into<CommandArg>,
58        vector: impl Into<Vec<f32>>,
59        element: impl Into<CommandArg>,
60    ) -> Self {
61        Self {
62            key: key.into(),
63            vector: vector.into(),
64            element: element.into(),
65            reduce: None,
66            cas: false,
67            m: None,
68            ef: None,
69            setattr: None,
70            quant: None,
71        }
72    }
73
74    /// Reduce the vector to `dim` dimensions.
75    pub fn reduce(mut self, dim: u64) -> Self {
76        self.reduce = Some(dim);
77        self
78    }
79
80    /// Enable check-and-set semantics.
81    pub fn cas(mut self) -> Self {
82        self.cas = true;
83        self
84    }
85
86    /// Set the maximum number of links per node.
87    pub fn m(mut self, cap: u64) -> Self {
88        self.m = Some(cap);
89        self
90    }
91
92    /// Set the EF construction parameter.
93    pub fn ef(mut self, build: u64) -> Self {
94        self.ef = Some(build);
95        self
96    }
97
98    /// Set a JSON attribute on the element.
99    pub fn setattr(mut self, json: impl Into<String>) -> Self {
100        self.setattr = Some(json.into());
101        self
102    }
103
104    /// Set the quantization type.
105    pub fn quant(mut self, q: VQuantization) -> Self {
106        self.quant = Some(q);
107        self
108    }
109}
110
111impl Command for VAdd {
112    type Response = bool;
113
114    fn to_frame(&self) -> Frame {
115        let mut args = vec![
116            bulk("VADD"),
117            bulk(&self.key),
118            bulk("VALUES"),
119            bulk(self.vector.len().to_string()),
120        ];
121        for v in &self.vector {
122            args.push(bulk(v.to_string()));
123        }
124        args.push(bulk(&self.element));
125
126        if let Some(dim) = self.reduce {
127            args.push(bulk("REDUCE"));
128            args.push(bulk(dim.to_string()));
129        }
130        if self.cas {
131            args.push(bulk("CAS"));
132        }
133        if let Some(cap) = self.m {
134            args.push(bulk("M"));
135            args.push(bulk(cap.to_string()));
136        }
137        if let Some(build) = self.ef {
138            args.push(bulk("EF"));
139            args.push(bulk(build.to_string()));
140        }
141        if let Some(ref json) = self.setattr {
142            args.push(bulk("SETATTR"));
143            args.push(bulk(json.as_str()));
144        }
145        match &self.quant {
146            Some(VQuantization::Q8) => args.push(bulk("Q8")),
147            Some(VQuantization::Bf16) => args.push(bulk("BF16")),
148            Some(VQuantization::NoQuant) => args.push(bulk("NOQUANT")),
149            None => {}
150        }
151
152        array(args)
153    }
154
155    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
156        match frame {
157            Frame::Integer(1) => Ok(true),
158            Frame::Integer(0) => Ok(false),
159            Frame::Boolean(b) => Ok(b),
160            other => Err(RedisError::UnexpectedResponse {
161                expected: "integer 0 or 1",
162                actual: format!("{other:?}"),
163            }),
164        }
165    }
166
167    fn name(&self) -> &str {
168        "VADD"
169    }
170}
171
172/// VREM key element
173///
174/// Removes an element from the vector set at `key`. Returns `true` if the
175/// element was removed, `false` if it did not exist.
176#[derive(Clone)]
177pub struct VRem {
178    key: CommandArg,
179    element: CommandArg,
180}
181
182impl VRem {
183    /// Create a new [`VRem`] command.
184    pub fn new(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
185        Self {
186            key: key.into(),
187            element: element.into(),
188        }
189    }
190}
191
192impl Command for VRem {
193    type Response = bool;
194
195    fn to_frame(&self) -> Frame {
196        array(vec![bulk("VREM"), bulk(&self.key), bulk(&self.element)])
197    }
198
199    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
200        match frame {
201            Frame::Integer(1) => Ok(true),
202            Frame::Integer(0) => Ok(false),
203            Frame::Boolean(b) => Ok(b),
204            other => Err(RedisError::UnexpectedResponse {
205                expected: "integer 0 or 1",
206                actual: format!("{other:?}"),
207            }),
208        }
209    }
210
211    fn name(&self) -> &str {
212        "VREM"
213    }
214}
215
216/// VCARD key
217///
218/// Returns the number of elements in the vector set at `key`.
219#[derive(Clone)]
220pub struct VCard {
221    key: CommandArg,
222}
223
224impl VCard {
225    /// Create a new [`VCard`] command.
226    pub fn new(key: impl Into<CommandArg>) -> Self {
227        Self { key: key.into() }
228    }
229}
230
231impl Command for VCard {
232    type Response = i64;
233
234    fn to_frame(&self) -> Frame {
235        array(vec![bulk("VCARD"), bulk(&self.key)])
236    }
237
238    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
239        match frame {
240            Frame::Integer(n) => Ok(n),
241            other => Err(RedisError::UnexpectedResponse {
242                expected: "integer",
243                actual: format!("{other:?}"),
244            }),
245        }
246    }
247
248    fn name(&self) -> &str {
249        "VCARD"
250    }
251}
252
253/// VDIM key
254///
255/// Returns the dimensionality of the vectors in the vector set at `key`.
256#[derive(Clone)]
257pub struct VDim {
258    key: CommandArg,
259}
260
261impl VDim {
262    /// Create a new [`VDim`] command.
263    pub fn new(key: impl Into<CommandArg>) -> Self {
264        Self { key: key.into() }
265    }
266}
267
268impl Command for VDim {
269    type Response = i64;
270
271    fn to_frame(&self) -> Frame {
272        array(vec![bulk("VDIM"), bulk(&self.key)])
273    }
274
275    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
276        match frame {
277            Frame::Integer(n) => Ok(n),
278            other => Err(RedisError::UnexpectedResponse {
279                expected: "integer",
280                actual: format!("{other:?}"),
281            }),
282        }
283    }
284
285    fn name(&self) -> &str {
286        "VDIM"
287    }
288}
289
290/// VISMEMBER key element
291///
292/// Checks whether `element` exists in the vector set at `key`. Returns `true`
293/// when it exists and `false` when either the element or key does not exist.
294///
295/// Redis returns an integer under RESP2 and a boolean under RESP3; both response
296/// shapes are normalized to [`bool`].
297#[derive(Clone)]
298pub struct VIsMember {
299    key: CommandArg,
300    element: CommandArg,
301}
302
303impl VIsMember {
304    /// Creates a membership check for `element` in the vector set at `key`.
305    pub fn new(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
306        Self {
307            key: key.into(),
308            element: element.into(),
309        }
310    }
311}
312
313impl Command for VIsMember {
314    type Response = bool;
315
316    fn to_frame(&self) -> Frame {
317        array(vec![
318            bulk("VISMEMBER"),
319            bulk(&self.key),
320            bulk(&self.element),
321        ])
322    }
323
324    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
325        match frame {
326            Frame::Integer(1) => Ok(true),
327            Frame::Integer(0) => Ok(false),
328            Frame::Boolean(value) => Ok(value),
329            other => Err(RedisError::UnexpectedResponse {
330                expected: "integer 0 or 1, or boolean",
331                actual: format!("{other:?}"),
332            }),
333        }
334    }
335
336    fn name(&self) -> &str {
337        "VISMEMBER"
338    }
339
340    fn idempotent(&self) -> bool {
341        true
342    }
343}
344
345/// VEMB key element \[RAW\]
346///
347/// Returns the vector embedding for `element` in the vector set at `key`.
348/// Without RAW, returns an array of doubles. With RAW, returns the raw FP32
349/// binary blob.
350#[derive(Clone)]
351pub struct VEmb {
352    key: CommandArg,
353    element: CommandArg,
354    raw: bool,
355}
356
357impl VEmb {
358    /// Create a new [`VEmb`] command.
359    pub fn new(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
360        Self {
361            key: key.into(),
362            element: element.into(),
363            raw: false,
364        }
365    }
366
367    /// Request the raw FP32 binary blob instead of parsed doubles.
368    pub fn raw(mut self) -> Self {
369        self.raw = true;
370        self
371    }
372}
373
374impl Command for VEmb {
375    type Response = Vec<f64>;
376
377    fn to_frame(&self) -> Frame {
378        let mut args = vec![bulk("VEMB"), bulk(&self.key), bulk(&self.element)];
379        if self.raw {
380            args.push(bulk("RAW"));
381        }
382        array(args)
383    }
384
385    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
386        match frame {
387            Frame::Array(Some(frames)) => frames
388                .into_iter()
389                .map(|f| match f {
390                    Frame::BulkString(Some(data)) => {
391                        let s = String::from_utf8_lossy(&data);
392                        s.parse::<f64>()
393                            .map_err(|_| RedisError::UnexpectedResponse {
394                                expected: "float string",
395                                actual: format!("{s}"),
396                            })
397                    }
398                    Frame::Double(d) => Ok(d),
399                    other => Err(RedisError::UnexpectedResponse {
400                        expected: "bulk string or double",
401                        actual: format!("{other:?}"),
402                    }),
403                })
404                .collect(),
405            other => Err(RedisError::UnexpectedResponse {
406                expected: "array",
407                actual: format!("{other:?}"),
408            }),
409        }
410    }
411
412    fn name(&self) -> &str {
413        "VEMB"
414    }
415}
416
417/// VSIM key (ELE element | VALUES num val ... | FP32 blob) \[COUNT n\]
418/// \[EF n\] \[FILTER expr\] \[FILTER-EF n\] \[WITHSCORES\] \[NOTHREAD\] \[TRUTH\]
419///
420/// Finds the most similar elements to the given vector or element in the
421/// vector set. Returns element names, or (element, score) pairs when
422/// WITHSCORES is specified.
423#[derive(Clone)]
424pub struct VSim {
425    key: CommandArg,
426    target: VSimTarget,
427    count: Option<u64>,
428    ef: Option<u64>,
429    filter: Option<String>,
430    filter_ef: Option<u64>,
431    withscores: bool,
432    nothread: bool,
433    truth: bool,
434}
435
436/// Target for VSIM: search by existing element name or by vector values.
437#[derive(Clone)]
438pub enum VSimTarget {
439    /// Search by existing element name.
440    Element(CommandArg),
441    /// Search by vector values.
442    Values(Vec<f32>),
443}
444
445impl VSim {
446    /// Search by existing element name.
447    pub fn by_element(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
448        Self {
449            key: key.into(),
450            target: VSimTarget::Element(element.into()),
451            count: None,
452            ef: None,
453            filter: None,
454            filter_ef: None,
455            withscores: false,
456            nothread: false,
457            truth: false,
458        }
459    }
460
461    /// Search by vector values.
462    pub fn by_values(key: impl Into<CommandArg>, vector: impl Into<Vec<f32>>) -> Self {
463        Self {
464            key: key.into(),
465            target: VSimTarget::Values(vector.into()),
466            count: None,
467            ef: None,
468            filter: None,
469            filter_ef: None,
470            withscores: false,
471            nothread: false,
472            truth: false,
473        }
474    }
475
476    /// Limit the number of results.
477    pub fn count(mut self, n: u64) -> Self {
478        self.count = Some(n);
479        self
480    }
481
482    /// Set the EF search parameter.
483    pub fn ef(mut self, n: u64) -> Self {
484        self.ef = Some(n);
485        self
486    }
487
488    /// Filter results by attribute expression.
489    pub fn filter(mut self, expr: impl Into<String>) -> Self {
490        self.filter = Some(expr.into());
491        self
492    }
493
494    /// Set the EF parameter for filtered search.
495    pub fn filter_ef(mut self, n: u64) -> Self {
496        self.filter_ef = Some(n);
497        self
498    }
499
500    /// Include similarity scores in the response.
501    pub fn withscores(mut self) -> Self {
502        self.withscores = true;
503        self
504    }
505
506    /// Disable multi-threading for this query.
507    pub fn nothread(mut self) -> Self {
508        self.nothread = true;
509        self
510    }
511
512    /// Use brute-force (exact) search instead of approximate.
513    pub fn truth(mut self) -> Self {
514        self.truth = true;
515        self
516    }
517}
518
519fn parse_vector_result_name(frame: Frame) -> Result<Bytes, RedisError> {
520    match frame {
521        Frame::BulkString(Some(data)) | Frame::SimpleString(data) => Ok(data),
522        other => Err(RedisError::UnexpectedResponse {
523            expected: "bulk or simple string",
524            actual: format!("{other:?}"),
525        }),
526    }
527}
528
529fn parse_vector_result_score(frame: Frame) -> Result<f64, RedisError> {
530    match frame {
531        Frame::BulkString(Some(data)) | Frame::SimpleString(data) => {
532            let score = String::from_utf8_lossy(&data);
533            score
534                .parse::<f64>()
535                .map_err(|_| RedisError::UnexpectedResponse {
536                    expected: "float string",
537                    actual: score.into_owned(),
538                })
539        }
540        Frame::Double(score) => Ok(score),
541        Frame::Integer(score) => Ok(score as f64),
542        other => Err(RedisError::UnexpectedResponse {
543            expected: "string, double, or integer score",
544            actual: format!("{other:?}"),
545        }),
546    }
547}
548
549fn parse_vector_results(
550    frame: Frame,
551    withscores: bool,
552) -> Result<Vec<(Bytes, Option<f64>)>, RedisError> {
553    match frame {
554        Frame::Array(Some(frames)) if withscores => {
555            if frames.len() % 2 != 0 {
556                return Err(RedisError::UnexpectedResponse {
557                    expected: "even number of elements for WITHSCORES",
558                    actual: format!("got {} elements", frames.len()),
559                });
560            }
561            let mut result = Vec::with_capacity(frames.len() / 2);
562            let mut frames = frames.into_iter();
563            while let (Some(name), Some(score)) = (frames.next(), frames.next()) {
564                result.push((
565                    parse_vector_result_name(name)?,
566                    Some(parse_vector_result_score(score)?),
567                ));
568            }
569            Ok(result)
570        }
571        Frame::Array(Some(frames)) => frames
572            .into_iter()
573            .map(|name| Ok((parse_vector_result_name(name)?, None)))
574            .collect(),
575        Frame::Map(entries) | Frame::StreamedMap(entries) if withscores => entries
576            .into_iter()
577            .map(|(name, score)| {
578                Ok((
579                    parse_vector_result_name(name)?,
580                    Some(parse_vector_result_score(score)?),
581                ))
582            })
583            .collect(),
584        other => Err(RedisError::UnexpectedResponse {
585            expected: if withscores { "array or map" } else { "array" },
586            actual: format!("{other:?}"),
587        }),
588    }
589}
590
591impl Command for VSim {
592    type Response = Vec<(Bytes, Option<f64>)>;
593
594    fn to_frame(&self) -> Frame {
595        let mut args = vec![bulk("VSIM"), bulk(&self.key)];
596
597        match &self.target {
598            VSimTarget::Element(elem) => {
599                args.push(bulk("ELE"));
600                args.push(bulk(elem));
601            }
602            VSimTarget::Values(vector) => {
603                args.push(bulk("VALUES"));
604                args.push(bulk(vector.len().to_string()));
605                for v in vector {
606                    args.push(bulk(v.to_string()));
607                }
608            }
609        }
610
611        if let Some(n) = self.count {
612            args.push(bulk("COUNT"));
613            args.push(bulk(n.to_string()));
614        }
615        if let Some(n) = self.ef {
616            args.push(bulk("EF"));
617            args.push(bulk(n.to_string()));
618        }
619        if let Some(ref expr) = self.filter {
620            args.push(bulk("FILTER"));
621            args.push(bulk(expr.as_str()));
622        }
623        if let Some(n) = self.filter_ef {
624            args.push(bulk("FILTER-EF"));
625            args.push(bulk(n.to_string()));
626        }
627        if self.withscores {
628            args.push(bulk("WITHSCORES"));
629        }
630        if self.nothread {
631            args.push(bulk("NOTHREAD"));
632        }
633        if self.truth {
634            args.push(bulk("TRUTH"));
635        }
636
637        array(args)
638    }
639
640    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
641        parse_vector_results(frame, self.withscores)
642    }
643
644    fn name(&self) -> &str {
645        "VSIM"
646    }
647}
648
649/// VRANDMEMBER key \[COUNT n\]
650///
651/// Returns one or more random elements from the vector set at `key`.
652#[derive(Clone)]
653pub struct VRandMember {
654    key: CommandArg,
655    count: Option<i64>,
656}
657
658impl VRandMember {
659    /// Create a new [`VRandMember`] command.
660    pub fn new(key: impl Into<CommandArg>) -> Self {
661        Self {
662            key: key.into(),
663            count: None,
664        }
665    }
666
667    /// Return `n` random elements. Negative values allow duplicates.
668    pub fn count(mut self, n: i64) -> Self {
669        self.count = Some(n);
670        self
671    }
672}
673
674impl Command for VRandMember {
675    type Response = Vec<Bytes>;
676
677    fn to_frame(&self) -> Frame {
678        let mut args = vec![bulk("VRANDMEMBER"), bulk(&self.key)];
679        if let Some(n) = self.count {
680            args.push(bulk(n.to_string()));
681        }
682        array(args)
683    }
684
685    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
686        match frame {
687            Frame::Array(Some(frames)) => frames
688                .into_iter()
689                .map(|f| match f {
690                    Frame::BulkString(Some(data)) => Ok(data),
691                    other => Err(RedisError::UnexpectedResponse {
692                        expected: "bulk string",
693                        actual: format!("{other:?}"),
694                    }),
695                })
696                .collect(),
697            // Without COUNT, Redis returns a single bulk string.
698            Frame::BulkString(Some(data)) => Ok(vec![data]),
699            Frame::BulkString(None) | Frame::Null => Ok(vec![]),
700            other => Err(RedisError::UnexpectedResponse {
701                expected: "array or bulk string",
702                actual: format!("{other:?}"),
703            }),
704        }
705    }
706
707    fn name(&self) -> &str {
708        "VRANDMEMBER"
709    }
710}
711
712/// VRANGE key start end \[count\]
713///
714/// Returns elements from the vector set at `key` in byte-wise lexicographical
715/// order. The `start` and `end` arguments use Redis range syntax:
716///
717/// - `[element` includes the boundary.
718/// - `(element` excludes the boundary.
719/// - `-` selects the minimum start.
720/// - `+` selects the maximum end.
721///
722/// Use [`VRange::count`] to bound the number of returned elements. Unlike range
723/// commands whose limit is introduced by a `COUNT` token, `VRANGE` takes its
724/// optional count as a bare positional argument.
725#[derive(Clone)]
726pub struct VRange {
727    key: CommandArg,
728    start: CommandArg,
729    end: CommandArg,
730    count: Option<i64>,
731}
732
733impl VRange {
734    /// Creates a lexicographical range query for the vector set at `key`.
735    pub fn new(
736        key: impl Into<CommandArg>,
737        start: impl Into<CommandArg>,
738        end: impl Into<CommandArg>,
739    ) -> Self {
740        Self {
741            key: key.into(),
742            start: start.into(),
743            end: end.into(),
744            count: None,
745        }
746    }
747
748    /// Limits the number of returned elements.
749    ///
750    /// A negative count returns every matching element and zero returns an empty
751    /// array.
752    pub fn count(mut self, count: i64) -> Self {
753        self.count = Some(count);
754        self
755    }
756}
757
758impl Command for VRange {
759    type Response = Vec<Bytes>;
760
761    fn to_frame(&self) -> Frame {
762        let mut args = vec![
763            bulk("VRANGE"),
764            bulk(&self.key),
765            bulk(&self.start),
766            bulk(&self.end),
767        ];
768        if let Some(count) = self.count {
769            args.push(bulk(count.to_string()));
770        }
771        array(args)
772    }
773
774    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
775        match frame {
776            Frame::Array(Some(frames)) => frames
777                .into_iter()
778                .map(|frame| match frame {
779                    Frame::BulkString(Some(element)) => Ok(element),
780                    other => Err(RedisError::UnexpectedResponse {
781                        expected: "bulk string element",
782                        actual: format!("{other:?}"),
783                    }),
784                })
785                .collect(),
786            other => Err(RedisError::UnexpectedResponse {
787                expected: "array",
788                actual: format!("{other:?}"),
789            }),
790        }
791    }
792
793    fn name(&self) -> &str {
794        "VRANGE"
795    }
796
797    fn idempotent(&self) -> bool {
798        true
799    }
800}
801
802/// VGETATTR key element
803///
804/// Returns the JSON attribute string for `element` in the vector set at `key`,
805/// or `None` if no attribute is set.
806#[derive(Clone)]
807pub struct VGetAttr {
808    key: CommandArg,
809    element: CommandArg,
810}
811
812impl VGetAttr {
813    /// Create a new [`VGetAttr`] command.
814    pub fn new(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
815        Self {
816            key: key.into(),
817            element: element.into(),
818        }
819    }
820}
821
822impl Command for VGetAttr {
823    type Response = Option<String>;
824
825    fn to_frame(&self) -> Frame {
826        array(vec![bulk("VGETATTR"), bulk(&self.key), bulk(&self.element)])
827    }
828
829    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
830        match frame {
831            Frame::BulkString(Some(data)) => {
832                let s = String::from_utf8(data.to_vec()).map_err(|_| {
833                    RedisError::UnexpectedResponse {
834                        expected: "valid UTF-8 string",
835                        actual: "invalid UTF-8".to_string(),
836                    }
837                })?;
838                Ok(Some(s))
839            }
840            Frame::BulkString(None) | Frame::Null => Ok(None),
841            other => Err(RedisError::UnexpectedResponse {
842                expected: "bulk string or null",
843                actual: format!("{other:?}"),
844            }),
845        }
846    }
847
848    fn name(&self) -> &str {
849        "VGETATTR"
850    }
851}
852
853/// VSETATTR key element json
854///
855/// Sets a JSON attribute on `element` in the vector set at `key`. Returns
856/// `true` on success.
857#[derive(Clone)]
858pub struct VSetAttr {
859    key: CommandArg,
860    element: CommandArg,
861    json: String,
862}
863
864impl VSetAttr {
865    /// Create a new [`VSetAttr`] command.
866    pub fn new(
867        key: impl Into<CommandArg>,
868        element: impl Into<CommandArg>,
869        json: impl Into<String>,
870    ) -> Self {
871        Self {
872            key: key.into(),
873            element: element.into(),
874            json: json.into(),
875        }
876    }
877}
878
879impl Command for VSetAttr {
880    type Response = bool;
881
882    fn to_frame(&self) -> Frame {
883        array(vec![
884            bulk("VSETATTR"),
885            bulk(&self.key),
886            bulk(&self.element),
887            bulk(self.json.as_str()),
888        ])
889    }
890
891    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
892        match frame {
893            Frame::Integer(1) => Ok(true),
894            Frame::Integer(0) => Ok(false),
895            Frame::Boolean(b) => Ok(b),
896            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(true),
897            other => Err(RedisError::UnexpectedResponse {
898                expected: "integer 0 or 1, or OK",
899                actual: format!("{other:?}"),
900            }),
901        }
902    }
903
904    fn name(&self) -> &str {
905        "VSETATTR"
906    }
907}
908
909/// Delete the attribute from `element` in the vector set at `key`.
910///
911/// Redis has no `VDELATTR` command; an attribute is cleared by setting it to
912/// the empty string, so this builder sends `VSETATTR key element ""`. The
913/// ergonomic `VDelAttr` name is kept. Returns `true` if the element exists
914/// (its attribute is cleared), `false` if the element is not in the set.
915#[derive(Clone)]
916pub struct VDelAttr {
917    key: CommandArg,
918    element: CommandArg,
919}
920
921impl VDelAttr {
922    /// Create a new [`VDelAttr`] command.
923    pub fn new(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
924        Self {
925            key: key.into(),
926            element: element.into(),
927        }
928    }
929}
930
931impl Command for VDelAttr {
932    type Response = bool;
933
934    fn to_frame(&self) -> Frame {
935        // No VDELATTR command exists in Redis; clear the attribute by setting
936        // it to the empty string via VSETATTR.
937        array(vec![
938            bulk("VSETATTR"),
939            bulk(&self.key),
940            bulk(&self.element),
941            bulk(""),
942        ])
943    }
944
945    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
946        match frame {
947            Frame::Integer(1) => Ok(true),
948            Frame::Integer(0) => Ok(false),
949            Frame::Boolean(b) => Ok(b),
950            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(true),
951            other => Err(RedisError::UnexpectedResponse {
952                expected: "integer 0 or 1, or OK",
953                actual: format!("{other:?}"),
954            }),
955        }
956    }
957
958    fn name(&self) -> &str {
959        // VSETATTR is what actually goes on the wire.
960        "VSETATTR"
961    }
962}
963
964/// VINFO key
965///
966/// Returns information about the vector set at `key` as a flat array of
967/// alternating field names and values.
968#[derive(Clone)]
969pub struct VInfo {
970    key: CommandArg,
971}
972
973impl VInfo {
974    /// Create a new [`VInfo`] command.
975    pub fn new(key: impl Into<CommandArg>) -> Self {
976        Self { key: key.into() }
977    }
978}
979
980impl Command for VInfo {
981    type Response = Vec<Frame>;
982
983    fn to_frame(&self) -> Frame {
984        array(vec![bulk("VINFO"), bulk(&self.key)])
985    }
986
987    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
988        match frame {
989            Frame::Array(Some(frames)) => Ok(frames),
990            // RESP3 returns a Map -- flatten key-value pairs into a flat array.
991            Frame::Map(pairs) => {
992                let mut frames = Vec::with_capacity(pairs.len() * 2);
993                for (k, v) in pairs {
994                    frames.push(k);
995                    frames.push(v);
996                }
997                Ok(frames)
998            }
999            other => Err(RedisError::UnexpectedResponse {
1000                expected: "array or map",
1001                actual: format!("{other:?}"),
1002            }),
1003        }
1004    }
1005
1006    fn name(&self) -> &str {
1007        "VINFO"
1008    }
1009}
1010
1011/// VLINKS key element \[WITHSCORES\]
1012///
1013/// Returns the neighbor links of `element` in the vector set at `key`.
1014/// With WITHSCORES, returns (element, score) pairs.
1015#[derive(Clone)]
1016pub struct VLinks {
1017    key: CommandArg,
1018    element: CommandArg,
1019    withscores: bool,
1020}
1021
1022impl VLinks {
1023    /// Create a new [`VLinks`] command.
1024    pub fn new(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
1025        Self {
1026            key: key.into(),
1027            element: element.into(),
1028            withscores: false,
1029        }
1030    }
1031
1032    /// Include similarity scores in the response.
1033    pub fn withscores(mut self) -> Self {
1034        self.withscores = true;
1035        self
1036    }
1037}
1038
1039impl Command for VLinks {
1040    type Response = Vec<(Bytes, Option<f64>)>;
1041
1042    fn to_frame(&self) -> Frame {
1043        let mut args = vec![bulk("VLINKS"), bulk(&self.key), bulk(&self.element)];
1044        if self.withscores {
1045            args.push(bulk("WITHSCORES"));
1046        }
1047        array(args)
1048    }
1049
1050    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1051        parse_vector_results(frame, self.withscores)
1052    }
1053
1054    fn name(&self) -> &str {
1055        "VLINKS"
1056    }
1057}
1058
1059#[cfg(test)]
1060mod tests {
1061    use super::*;
1062
1063    #[test]
1064    fn vismember_serializes_key_and_element() {
1065        let command = VIsMember::new("vectors", "member");
1066
1067        assert_eq!(
1068            command.to_frame(),
1069            array(vec![bulk("VISMEMBER"), bulk("vectors"), bulk("member")])
1070        );
1071        assert_eq!(command.name(), "VISMEMBER");
1072        assert!(command.idempotent());
1073    }
1074
1075    #[test]
1076    fn vismember_parses_resp2_integer_reply() {
1077        let command = VIsMember::new("vectors", "member");
1078
1079        assert!(command.parse_response(Frame::Integer(1)).unwrap());
1080        assert!(!command.parse_response(Frame::Integer(0)).unwrap());
1081    }
1082
1083    #[test]
1084    fn vismember_parses_resp3_boolean_reply() {
1085        let command = VIsMember::new("vectors", "member");
1086
1087        assert!(command.parse_response(Frame::Boolean(true)).unwrap());
1088        assert!(!command.parse_response(Frame::Boolean(false)).unwrap());
1089    }
1090
1091    #[test]
1092    fn vismember_rejects_invalid_reply() {
1093        let command = VIsMember::new("vectors", "member");
1094
1095        assert!(command.parse_response(Frame::Integer(2)).is_err());
1096        assert!(
1097            command
1098                .parse_response(Frame::BulkString(Some(Bytes::from_static(b"1"))))
1099                .is_err()
1100        );
1101    }
1102
1103    #[test]
1104    fn vector_score_replies_accept_resp2_arrays_and_resp3_maps() {
1105        let resp2 = Frame::Array(Some(vec![
1106            bulk("a"),
1107            bulk("1.0"),
1108            Frame::SimpleString(Bytes::from_static(b"b")),
1109            Frame::Double(0.5),
1110        ]));
1111        let resp3 = Frame::Map(vec![
1112            (bulk("a"), Frame::Double(1.0)),
1113            (
1114                Frame::SimpleString(Bytes::from_static(b"b")),
1115                Frame::Integer(1),
1116            ),
1117        ]);
1118        let expected = vec![
1119            (Bytes::from_static(b"a"), Some(1.0)),
1120            (Bytes::from_static(b"b"), Some(0.5)),
1121        ];
1122
1123        assert_eq!(
1124            VSim::by_element("vectors", "a")
1125                .withscores()
1126                .parse_response(resp2)
1127                .unwrap(),
1128            expected
1129        );
1130        assert_eq!(
1131            VSim::by_element("vectors", "a")
1132                .withscores()
1133                .parse_response(resp3.clone())
1134                .unwrap(),
1135            vec![
1136                (Bytes::from_static(b"a"), Some(1.0)),
1137                (Bytes::from_static(b"b"), Some(1.0)),
1138            ]
1139        );
1140        assert_eq!(
1141            VLinks::new("vectors", "a")
1142                .withscores()
1143                .parse_response(resp3)
1144                .unwrap(),
1145            vec![
1146                (Bytes::from_static(b"a"), Some(1.0)),
1147                (Bytes::from_static(b"b"), Some(1.0)),
1148            ]
1149        );
1150    }
1151
1152    #[test]
1153    fn vrange_serializes_without_count() {
1154        let command = VRange::new("vectors", "[apple", "(pear");
1155
1156        assert_eq!(
1157            command.to_frame(),
1158            array(vec![
1159                bulk("VRANGE"),
1160                bulk("vectors"),
1161                bulk("[apple"),
1162                bulk("(pear")
1163            ])
1164        );
1165        assert_eq!(command.name(), "VRANGE");
1166        assert!(command.idempotent());
1167    }
1168
1169    #[test]
1170    fn vrange_serializes_positional_count() {
1171        for count in [10, 0, -1] {
1172            let command = VRange::new("vectors", "-", "+").count(count);
1173
1174            assert_eq!(
1175                command.to_frame(),
1176                array(vec![
1177                    bulk("VRANGE"),
1178                    bulk("vectors"),
1179                    bulk("-"),
1180                    bulk("+"),
1181                    bulk(count.to_string())
1182                ])
1183            );
1184        }
1185    }
1186
1187    #[test]
1188    fn vrange_parses_ordered_binary_safe_elements() {
1189        let command = VRange::new("vectors", "-", "+");
1190        let binary = Bytes::from_static(b"\0binary\xff");
1191
1192        let result = command
1193            .parse_response(Frame::Array(Some(vec![
1194                Frame::BulkString(Some(Bytes::from_static(b"apple"))),
1195                Frame::BulkString(Some(binary.clone())),
1196                Frame::BulkString(Some(Bytes::from_static(b"pear"))),
1197            ])))
1198            .unwrap();
1199
1200        assert_eq!(
1201            result,
1202            vec![
1203                Bytes::from_static(b"apple"),
1204                binary,
1205                Bytes::from_static(b"pear")
1206            ]
1207        );
1208    }
1209
1210    #[test]
1211    fn vrange_parses_empty_array() {
1212        let command = VRange::new("vectors", "-", "+");
1213
1214        assert_eq!(
1215            command
1216                .parse_response(Frame::Array(Some(Vec::new())))
1217                .unwrap(),
1218            Vec::<Bytes>::new()
1219        );
1220    }
1221
1222    #[test]
1223    fn vrange_rejects_invalid_reply_shapes() {
1224        let command = VRange::new("vectors", "-", "+");
1225
1226        assert!(
1227            command
1228                .parse_response(Frame::BulkString(Some(Bytes::from_static(b"member"))))
1229                .is_err()
1230        );
1231        assert!(command.parse_response(Frame::Array(None)).is_err());
1232        assert!(
1233            command
1234                .parse_response(Frame::Array(Some(vec![Frame::BulkString(None)])))
1235                .is_err()
1236        );
1237        assert!(
1238            command
1239                .parse_response(Frame::Array(Some(vec![Frame::Integer(1)])))
1240                .is_err()
1241        );
1242    }
1243}