Skip to main content

redis_tower_commands/
geo.rs

1//! Geospatial indexes backed by Redis sorted sets.
2//!
3//! [`GeoAdd`] stores longitude/latitude members. [`GeoSearch`] returns matching
4//! member names, [`GeoPos`] returns optional coordinates, [`GeoHash`] returns
5//! optional geohashes, [`GeoSearchStore`] returns a stored count, and
6//! [`GeoDist`] returns an optional distance. Units are explicit through
7//! [`GeoUnit`].
8//!
9//! ```
10//! use redis_tower_commands::GeoAdd;
11//! use redis_tower_core::Command;
12//!
13//! let command = GeoAdd::new("places").member(-122.4194, 37.7749, "sf");
14//! assert_eq!(command.name(), "GEOADD");
15//! ```
16//!
17//! See the [command cookbook] for choosing and executing typed commands.
18//!
19//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#typed-commands-and-response-shapes
20
21use crate::CommandArg;
22use bytes::Bytes;
23use redis_tower_core::{Command, Frame, RedisError};
24use redis_tower_protocol::helpers::{array, bulk};
25
26/// Unit of distance for geospatial commands.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum GeoUnit {
29    /// Meters
30    Meters,
31    /// Kilometers
32    Kilometers,
33    /// Feet
34    Feet,
35    /// Miles
36    Miles,
37}
38
39impl GeoUnit {
40    fn as_str(&self) -> &str {
41        match self {
42            GeoUnit::Meters => "M",
43            GeoUnit::Kilometers => "KM",
44            GeoUnit::Feet => "FT",
45            GeoUnit::Miles => "MI",
46        }
47    }
48}
49
50/// GEOADD key \[NX|XX\] \[CH\] longitude latitude member \[longitude latitude member ...\]
51///
52/// Adds the specified geospatial items (longitude, latitude, name) to the
53/// specified key. Returns the number of elements added to the sorted set
54/// (excluding score updates when `CH` is not set).
55#[derive(Clone)]
56pub struct GeoAdd {
57    key: CommandArg,
58    members: Vec<(f64, f64, CommandArg)>,
59    nx: bool,
60    xx: bool,
61    ch: bool,
62}
63
64impl GeoAdd {
65    /// Create a new [`GeoAdd`] command.
66    pub fn new(key: impl Into<CommandArg>) -> Self {
67        Self {
68            key: key.into(),
69            members: Vec::new(),
70            nx: false,
71            xx: false,
72            ch: false,
73        }
74    }
75
76    /// Adds a member with the given longitude and latitude.
77    pub fn member(mut self, longitude: f64, latitude: f64, name: impl Into<CommandArg>) -> Self {
78        self.members.push((longitude, latitude, name.into()));
79        self
80    }
81
82    /// Only add new elements. Do not update already existing elements.
83    pub fn nx(mut self) -> Self {
84        self.nx = true;
85        self.xx = false;
86        self
87    }
88
89    /// Only update elements that already exist. Do not add new elements.
90    pub fn xx(mut self) -> Self {
91        self.xx = true;
92        self.nx = false;
93        self
94    }
95
96    /// Modify the return value from the number of new elements added to the
97    /// total number of elements changed (including score updates).
98    pub fn ch(mut self) -> Self {
99        self.ch = true;
100        self
101    }
102}
103
104impl Command for GeoAdd {
105    type Response = i64;
106
107    fn to_frame(&self) -> Frame {
108        let mut args = vec![bulk("GEOADD"), bulk(&self.key)];
109        if self.nx {
110            args.push(bulk("NX"));
111        } else if self.xx {
112            args.push(bulk("XX"));
113        }
114        if self.ch {
115            args.push(bulk("CH"));
116        }
117        for (longitude, latitude, name) in &self.members {
118            args.push(bulk(longitude.to_string()));
119            args.push(bulk(latitude.to_string()));
120            args.push(bulk(name));
121        }
122        array(args)
123    }
124
125    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
126        match frame {
127            Frame::Integer(n) => Ok(n),
128            other => Err(RedisError::UnexpectedResponse {
129                expected: "integer",
130                actual: format!("{other:?}"),
131            }),
132        }
133    }
134
135    fn name(&self) -> &str {
136        "GEOADD"
137    }
138}
139
140/// GEODIST key member1 member2 \[M|KM|FT|MI\]
141///
142/// Returns the distance between two members of a geospatial index. The
143/// distance is returned as a floating-point number in the specified unit,
144/// or `None` if one or both members are missing.
145#[derive(Clone)]
146pub struct GeoDist {
147    key: CommandArg,
148    member1: CommandArg,
149    member2: CommandArg,
150    unit: Option<GeoUnit>,
151}
152
153impl GeoDist {
154    /// Create a new [`GeoDist`] command.
155    pub fn new(
156        key: impl Into<CommandArg>,
157        member1: impl Into<CommandArg>,
158        member2: impl Into<CommandArg>,
159    ) -> Self {
160        Self {
161            key: key.into(),
162            member1: member1.into(),
163            member2: member2.into(),
164            unit: None,
165        }
166    }
167
168    /// Sets the unit of the returned distance.
169    pub fn unit(mut self, unit: GeoUnit) -> Self {
170        self.unit = Some(unit);
171        self
172    }
173}
174
175impl Command for GeoDist {
176    type Response = Option<f64>;
177
178    fn to_frame(&self) -> Frame {
179        let mut args = vec![
180            bulk("GEODIST"),
181            bulk(&self.key),
182            bulk(&self.member1),
183            bulk(&self.member2),
184        ];
185        if let Some(unit) = &self.unit {
186            args.push(bulk(unit.as_str()));
187        }
188        array(args)
189    }
190
191    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
192        match frame {
193            Frame::BulkString(Some(data)) => {
194                let s = String::from_utf8_lossy(&data);
195                let dist = s
196                    .parse::<f64>()
197                    .map_err(|_| RedisError::UnexpectedResponse {
198                        expected: "float string",
199                        actual: format!("{s}"),
200                    })?;
201                Ok(Some(dist))
202            }
203            Frame::Double(d) => Ok(Some(d)),
204            Frame::BulkString(None) | Frame::Null => Ok(None),
205            other => Err(RedisError::UnexpectedResponse {
206                expected: "bulk string, double, or null",
207                actual: format!("{other:?}"),
208            }),
209        }
210    }
211
212    fn name(&self) -> &str {
213        "GEODIST"
214    }
215}
216
217/// GEOHASH key member \[member ...\]
218///
219/// Returns the Geohash strings representing the position of each member.
220/// Each element is `Some(hash)` if the member exists, or `None` if it
221/// does not.
222#[derive(Clone)]
223pub struct GeoHash {
224    key: CommandArg,
225    members: Vec<CommandArg>,
226}
227
228impl GeoHash {
229    /// Create a new [`GeoHash`] command.
230    pub fn new(key: impl Into<CommandArg>, member: impl Into<CommandArg>) -> Self {
231        Self {
232            key: key.into(),
233            members: vec![member.into()],
234        }
235    }
236
237    /// Creates a `GeoHash` command for multiple members.
238    pub fn members(
239        key: impl Into<CommandArg>,
240        members: impl IntoIterator<Item = impl Into<CommandArg>>,
241    ) -> Self {
242        Self {
243            key: key.into(),
244            members: members.into_iter().map(Into::into).collect(),
245        }
246    }
247}
248
249impl Command for GeoHash {
250    type Response = Vec<Option<String>>;
251
252    fn to_frame(&self) -> Frame {
253        let mut args = vec![bulk("GEOHASH"), bulk(&self.key)];
254        for member in &self.members {
255            args.push(bulk(member));
256        }
257        array(args)
258    }
259
260    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
261        match frame {
262            Frame::Array(Some(frames)) => frames
263                .into_iter()
264                .map(|f| match f {
265                    Frame::BulkString(Some(data)) => {
266                        Ok(Some(String::from_utf8_lossy(&data).into_owned()))
267                    }
268                    Frame::BulkString(None) | Frame::Null => Ok(None),
269                    other => Err(RedisError::UnexpectedResponse {
270                        expected: "bulk string or null",
271                        actual: format!("{other:?}"),
272                    }),
273                })
274                .collect(),
275            other => Err(RedisError::UnexpectedResponse {
276                expected: "array",
277                actual: format!("{other:?}"),
278            }),
279        }
280    }
281
282    fn name(&self) -> &str {
283        "GEOHASH"
284    }
285}
286
287/// GEOPOS key member \[member ...\]
288///
289/// Returns the longitude and latitude of each specified member. Each
290/// element is `Some((longitude, latitude))` if the member exists, or
291/// `None` if it does not.
292#[derive(Clone)]
293pub struct GeoPos {
294    key: CommandArg,
295    members: Vec<CommandArg>,
296}
297
298impl GeoPos {
299    /// Create a new [`GeoPos`] command.
300    pub fn new(key: impl Into<CommandArg>, member: impl Into<CommandArg>) -> Self {
301        Self {
302            key: key.into(),
303            members: vec![member.into()],
304        }
305    }
306
307    /// Creates a `GeoPos` command for multiple members.
308    pub fn members(
309        key: impl Into<CommandArg>,
310        members: impl IntoIterator<Item = impl Into<CommandArg>>,
311    ) -> Self {
312        Self {
313            key: key.into(),
314            members: members.into_iter().map(Into::into).collect(),
315        }
316    }
317}
318
319impl GeoPos {
320    /// Parses a single coordinate pair from a two-element array of bulk strings
321    /// or doubles.
322    fn parse_coordinate(frames: Vec<Frame>) -> Result<(f64, f64), RedisError> {
323        if frames.len() != 2 {
324            return Err(RedisError::UnexpectedResponse {
325                expected: "two-element array",
326                actual: format!("array of length {}", frames.len()),
327            });
328        }
329        let lon = Self::parse_f64(&frames[0])?;
330        let lat = Self::parse_f64(&frames[1])?;
331        Ok((lon, lat))
332    }
333
334    fn parse_f64(frame: &Frame) -> Result<f64, RedisError> {
335        match frame {
336            Frame::BulkString(Some(data)) => {
337                let s = String::from_utf8_lossy(data);
338                s.parse::<f64>()
339                    .map_err(|_| RedisError::UnexpectedResponse {
340                        expected: "float string",
341                        actual: format!("{s}"),
342                    })
343            }
344            Frame::Double(d) => Ok(*d),
345            other => Err(RedisError::UnexpectedResponse {
346                expected: "bulk string or double",
347                actual: format!("{other:?}"),
348            }),
349        }
350    }
351}
352
353impl Command for GeoPos {
354    type Response = Vec<Option<(f64, f64)>>;
355
356    fn to_frame(&self) -> Frame {
357        let mut args = vec![bulk("GEOPOS"), bulk(&self.key)];
358        for member in &self.members {
359            args.push(bulk(member));
360        }
361        array(args)
362    }
363
364    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
365        match frame {
366            Frame::Array(Some(frames)) => frames
367                .into_iter()
368                .map(|f| match f {
369                    Frame::Array(Some(coords)) => Self::parse_coordinate(coords).map(Some),
370                    Frame::Array(None) | Frame::Null | Frame::BulkString(None) => Ok(None),
371                    other => Err(RedisError::UnexpectedResponse {
372                        expected: "array or null",
373                        actual: format!("{other:?}"),
374                    }),
375                })
376                .collect(),
377            other => Err(RedisError::UnexpectedResponse {
378                expected: "array",
379                actual: format!("{other:?}"),
380            }),
381        }
382    }
383
384    fn name(&self) -> &str {
385        "GEOPOS"
386    }
387}
388
389/// Origin for a GEOSEARCH or GEOSEARCHSTORE command.
390#[derive(Clone)]
391enum GeoSearchOrigin {
392    Member(CommandArg),
393    LonLat(f64, f64),
394}
395
396/// Shape predicate for a GEOSEARCH or GEOSEARCHSTORE command.
397#[derive(Clone)]
398enum GeoSearchShape {
399    Radius(f64, GeoUnit),
400    Box(f64, f64, GeoUnit),
401}
402
403/// Sort order for GEOSEARCH results.
404#[derive(Debug, Clone, Copy, PartialEq, Eq)]
405enum GeoSearchOrder {
406    Asc,
407    Desc,
408}
409
410/// GEOSEARCH key FROMMEMBER member|FROMLONLAT longitude latitude BYRADIUS radius M|KM|FT|MI|BYBOX width height M|KM|FT|MI \[ASC|DESC\] \[COUNT count \[ANY\]\]
411///
412/// Returns the members of a sorted set populated with geospatial data
413/// that are within the borders of the area specified by a given shape.
414#[derive(Clone)]
415pub struct GeoSearch {
416    key: CommandArg,
417    origin: GeoSearchOrigin,
418    shape: GeoSearchShape,
419    order: Option<GeoSearchOrder>,
420    count: Option<i64>,
421    any: bool,
422}
423
424impl GeoSearch {
425    fn new_with_origin(key: impl Into<CommandArg>, origin: GeoSearchOrigin) -> Self {
426        Self {
427            key: key.into(),
428            origin,
429            shape: GeoSearchShape::Radius(0.0, GeoUnit::Meters),
430            order: None,
431            count: None,
432            any: false,
433        }
434    }
435
436    /// Searches from an existing member in the sorted set.
437    pub fn from_member(key: impl Into<CommandArg>, member: impl Into<CommandArg>) -> Self {
438        Self::new_with_origin(key, GeoSearchOrigin::Member(member.into()))
439    }
440
441    /// Searches from the given longitude and latitude.
442    pub fn from_lonlat(key: impl Into<CommandArg>, longitude: f64, latitude: f64) -> Self {
443        Self::new_with_origin(key, GeoSearchOrigin::LonLat(longitude, latitude))
444    }
445
446    /// Searches within a circular area of the given radius.
447    pub fn by_radius(mut self, radius: f64, unit: GeoUnit) -> Self {
448        self.shape = GeoSearchShape::Radius(radius, unit);
449        self
450    }
451
452    /// Searches within a rectangular area of the given width and height.
453    pub fn by_box(mut self, width: f64, height: f64, unit: GeoUnit) -> Self {
454        self.shape = GeoSearchShape::Box(width, height, unit);
455        self
456    }
457
458    /// Sorts results from nearest to farthest.
459    pub fn asc(mut self) -> Self {
460        self.order = Some(GeoSearchOrder::Asc);
461        self
462    }
463
464    /// Sorts results from farthest to nearest.
465    pub fn desc(mut self) -> Self {
466        self.order = Some(GeoSearchOrder::Desc);
467        self
468    }
469
470    /// Limits the number of results to `count`.
471    pub fn count(mut self, count: i64) -> Self {
472        self.count = Some(count);
473        self.any = false;
474        self
475    }
476
477    /// Limits the number of results to `count`, but allows returning
478    /// results as soon as enough matches are found (not necessarily the
479    /// closest ones).
480    pub fn count_any(mut self, count: i64) -> Self {
481        self.count = Some(count);
482        self.any = true;
483        self
484    }
485
486    /// Builds the common argument list for GEOSEARCH and GEOSEARCHSTORE.
487    fn build_search_args(&self) -> Vec<Frame> {
488        let mut args = Vec::new();
489        match &self.origin {
490            GeoSearchOrigin::Member(member) => {
491                args.push(bulk("FROMMEMBER"));
492                args.push(bulk(member));
493            }
494            GeoSearchOrigin::LonLat(lon, lat) => {
495                args.push(bulk("FROMLONLAT"));
496                args.push(bulk(lon.to_string()));
497                args.push(bulk(lat.to_string()));
498            }
499        }
500        match &self.shape {
501            GeoSearchShape::Radius(radius, unit) => {
502                args.push(bulk("BYRADIUS"));
503                args.push(bulk(radius.to_string()));
504                args.push(bulk(unit.as_str()));
505            }
506            GeoSearchShape::Box(width, height, unit) => {
507                args.push(bulk("BYBOX"));
508                args.push(bulk(width.to_string()));
509                args.push(bulk(height.to_string()));
510                args.push(bulk(unit.as_str()));
511            }
512        }
513        if let Some(order) = &self.order {
514            args.push(bulk(match order {
515                GeoSearchOrder::Asc => "ASC",
516                GeoSearchOrder::Desc => "DESC",
517            }));
518        }
519        if let Some(count) = self.count {
520            args.push(bulk("COUNT"));
521            args.push(bulk(count.to_string()));
522            if self.any {
523                args.push(bulk("ANY"));
524            }
525        }
526        args
527    }
528}
529
530impl Command for GeoSearch {
531    type Response = Vec<Bytes>;
532
533    fn to_frame(&self) -> Frame {
534        let mut args = vec![bulk("GEOSEARCH"), bulk(&self.key)];
535        args.extend(self.build_search_args());
536        array(args)
537    }
538
539    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
540        match frame {
541            Frame::Array(Some(frames)) => frames
542                .into_iter()
543                .map(|f| match f {
544                    Frame::BulkString(Some(data)) => Ok(data),
545                    other => Err(RedisError::UnexpectedResponse {
546                        expected: "bulk string",
547                        actual: format!("{other:?}"),
548                    }),
549                })
550                .collect(),
551            Frame::Array(None) => Ok(Vec::new()),
552            other => Err(RedisError::UnexpectedResponse {
553                expected: "array",
554                actual: format!("{other:?}"),
555            }),
556        }
557    }
558
559    fn name(&self) -> &str {
560        "GEOSEARCH"
561    }
562}
563
564/// GEOSEARCHSTORE destination source FROMMEMBER member|FROMLONLAT longitude latitude BYRADIUS radius M|KM|FT|MI|BYBOX width height M|KM|FT|MI \[ASC|DESC\] \[COUNT count \[ANY\]\] \[STOREDIST\]
565///
566/// Like \[`GeoSearch`\], but stores the result in `destination`. Returns the
567/// number of elements stored. When `store_dist` is set, the sorted set
568/// stores distances instead of geospatial data.
569#[derive(Clone)]
570pub struct GeoSearchStore {
571    destination: CommandArg,
572    source: CommandArg,
573    origin: GeoSearchOrigin,
574    shape: GeoSearchShape,
575    order: Option<GeoSearchOrder>,
576    count: Option<i64>,
577    any: bool,
578    store_dist: bool,
579}
580
581impl GeoSearchStore {
582    fn new_with_origin(
583        destination: impl Into<CommandArg>,
584        source: impl Into<CommandArg>,
585        origin: GeoSearchOrigin,
586    ) -> Self {
587        Self {
588            destination: destination.into(),
589            source: source.into(),
590            origin,
591            shape: GeoSearchShape::Radius(0.0, GeoUnit::Meters),
592            order: None,
593            count: None,
594            any: false,
595            store_dist: false,
596        }
597    }
598
599    /// Searches from an existing member in the source sorted set.
600    pub fn from_member(
601        destination: impl Into<CommandArg>,
602        source: impl Into<CommandArg>,
603        member: impl Into<CommandArg>,
604    ) -> Self {
605        Self::new_with_origin(destination, source, GeoSearchOrigin::Member(member.into()))
606    }
607
608    /// Searches from the given longitude and latitude.
609    pub fn from_lonlat(
610        destination: impl Into<CommandArg>,
611        source: impl Into<CommandArg>,
612        longitude: f64,
613        latitude: f64,
614    ) -> Self {
615        Self::new_with_origin(
616            destination,
617            source,
618            GeoSearchOrigin::LonLat(longitude, latitude),
619        )
620    }
621
622    /// Searches within a circular area of the given radius.
623    pub fn by_radius(mut self, radius: f64, unit: GeoUnit) -> Self {
624        self.shape = GeoSearchShape::Radius(radius, unit);
625        self
626    }
627
628    /// Searches within a rectangular area of the given width and height.
629    pub fn by_box(mut self, width: f64, height: f64, unit: GeoUnit) -> Self {
630        self.shape = GeoSearchShape::Box(width, height, unit);
631        self
632    }
633
634    /// Sorts results from nearest to farthest.
635    pub fn asc(mut self) -> Self {
636        self.order = Some(GeoSearchOrder::Asc);
637        self
638    }
639
640    /// Sorts results from farthest to nearest.
641    pub fn desc(mut self) -> Self {
642        self.order = Some(GeoSearchOrder::Desc);
643        self
644    }
645
646    /// Limits the number of results to `count`.
647    pub fn count(mut self, count: i64) -> Self {
648        self.count = Some(count);
649        self.any = false;
650        self
651    }
652
653    /// Limits the number of results to `count`, but allows returning
654    /// results as soon as enough matches are found (not necessarily the
655    /// closest ones).
656    pub fn count_any(mut self, count: i64) -> Self {
657        self.count = Some(count);
658        self.any = true;
659        self
660    }
661
662    /// Stores distances in the destination sorted set instead of
663    /// geospatial data.
664    pub fn store_dist(mut self) -> Self {
665        self.store_dist = true;
666        self
667    }
668
669    /// Builds the search-specific argument list (shared logic with
670    /// \[`GeoSearch`\]).
671    fn build_search_args(&self) -> Vec<Frame> {
672        let mut args = Vec::new();
673        match &self.origin {
674            GeoSearchOrigin::Member(member) => {
675                args.push(bulk("FROMMEMBER"));
676                args.push(bulk(member));
677            }
678            GeoSearchOrigin::LonLat(lon, lat) => {
679                args.push(bulk("FROMLONLAT"));
680                args.push(bulk(lon.to_string()));
681                args.push(bulk(lat.to_string()));
682            }
683        }
684        match &self.shape {
685            GeoSearchShape::Radius(radius, unit) => {
686                args.push(bulk("BYRADIUS"));
687                args.push(bulk(radius.to_string()));
688                args.push(bulk(unit.as_str()));
689            }
690            GeoSearchShape::Box(width, height, unit) => {
691                args.push(bulk("BYBOX"));
692                args.push(bulk(width.to_string()));
693                args.push(bulk(height.to_string()));
694                args.push(bulk(unit.as_str()));
695            }
696        }
697        if let Some(order) = &self.order {
698            args.push(bulk(match order {
699                GeoSearchOrder::Asc => "ASC",
700                GeoSearchOrder::Desc => "DESC",
701            }));
702        }
703        if let Some(count) = self.count {
704            args.push(bulk("COUNT"));
705            args.push(bulk(count.to_string()));
706            if self.any {
707                args.push(bulk("ANY"));
708            }
709        }
710        args
711    }
712}
713
714impl Command for GeoSearchStore {
715    type Response = i64;
716
717    fn to_frame(&self) -> Frame {
718        let mut args = vec![
719            bulk("GEOSEARCHSTORE"),
720            bulk(&self.destination),
721            bulk(&self.source),
722        ];
723        args.extend(self.build_search_args());
724        if self.store_dist {
725            args.push(bulk("STOREDIST"));
726        }
727        array(args)
728    }
729
730    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
731        match frame {
732            Frame::Integer(n) => Ok(n),
733            other => Err(RedisError::UnexpectedResponse {
734                expected: "integer",
735                actual: format!("{other:?}"),
736            }),
737        }
738    }
739
740    fn name(&self) -> &str {
741        "GEOSEARCHSTORE"
742    }
743}