Skip to main content

flusso_query/handles/
map.rs

1//! Map field handles: dynamic-key objects whose values share one leaf kind.
2//!
3//! A `map` field (e.g. translations `{"en": …, "it": …}`) has runtime-determined
4//! keys but a compile-time-known value kind. That split is the whole point:
5//! `.key(runtime_str)` returns a **fully-typed** leaf handle of the declared kind
6//! — [`Text`] for a [`TextMap`], [`Keyword`] for a [`KeywordMap`], [`Number`]
7//! for a [`NumberMap`], [`Date`] for a [`DateMap`] — so a specific key is queried
8//! with full type safety while keys stay open-ended.
9//!
10//! Three operators are shared by every map handle:
11//!
12//! - [`key`](TextMap::key) — a specific key → a typed leaf handle.
13//! - [`has_key`](TextMap::has_key) — a presence check on one key.
14//! - [`exists`](TextMap::exists) — a presence check on the whole field.
15//!
16//! [`TextMap`] additionally offers [`search`](TextMap::search): full-text across
17//! *every* key at once, with optional per-key preference — the common
18//! cross-language case, without enumerating keys or silently missing one.
19//!
20//! ```
21//! use flusso_query::{AsQuery, Root, TextMap};
22//!
23//! // A specific key — a fully-typed `Text` leaf.
24//! let q = TextMap::<Root>::at("title").key("it").matches("ciao").to_value();
25//! assert_eq!(q["match"]["title.it"], serde_json::json!("ciao"));
26//!
27//! // Cross-key search, preferring Italian then English.
28//! let q = TextMap::<Root>::at("title")
29//!     .search("ciao")
30//!     .prefer("it", 3.0)
31//!     .prefer("en", 2.0)
32//!     .to_value();
33//! assert_eq!(q["multi_match"]["type"], serde_json::json!("best_fields"));
34//! ```
35
36use std::marker::PhantomData;
37
38use serde_json::{Map, Value};
39
40use super::{
41    Common, Date, Fuzziness, Keyword, MinimumShouldMatch, Number, Operator, Text, common_opts,
42    exists_q, wrap,
43};
44use crate::query::{AsQuery, Query, Root};
45
46/// Define a concrete map handle over leaf kind `$Leaf`. Each carries a field
47/// path and scope `S`, exposes `key`/`has_key`/`exists`, and `key` returns a
48/// fully-typed `$Leaf<S>` leaf handle.
49macro_rules! map_handle {
50    ($(#[$meta:meta])* $Name:ident => $Leaf:ident, $kind:literal) => {
51        $(#[$meta])*
52        #[derive(Debug, Clone)]
53        pub struct $Name<S = Root> {
54            path: String,
55            _scope: PhantomData<fn() -> S>,
56        }
57
58        impl<S> $Name<S> {
59            pub fn at(path: impl Into<String>) -> Self {
60                Self {
61                    path: path.into(),
62                    _scope: PhantomData,
63                }
64            }
65
66            #[doc = concat!("A specific runtime key → a fully-typed `", $kind, "` leaf handle, \
67                queried like any other ", $kind, " field.")]
68            pub fn key(&self, key: impl AsRef<str>) -> $Leaf<S> {
69                $Leaf::at(format!("{}.{}", self.path, key.as_ref()))
70            }
71
72            /// The map holds the given key with a non-null value.
73            pub fn has_key(&self, key: impl AsRef<str>) -> Query<S> {
74                exists_q(&format!("{}.{}", self.path, key.as_ref()))
75            }
76
77            /// The map field itself is present (has at least one key).
78            pub fn exists(&self) -> Query<S> {
79                exists_q(&self.path)
80            }
81        }
82    };
83}
84
85map_handle!(
86    /// A dynamic-key object whose values are analyzed full text (`map` with a
87    /// `text`/`identifier` value kind). [`key`](Self::key) yields a [`Text`]
88    /// leaf; [`search`](Self::search) runs full text across every key.
89    TextMap => Text, "text"
90);
91map_handle!(
92    /// A dynamic-key object whose values are exact strings (`map` with a
93    /// `keyword`/`enum`/`uuid` value kind). [`key`](Self::key) yields a
94    /// [`Keyword`] leaf for exact match. No `search` — exact-match maps use
95    /// `key(..).eq(..)` / `has_key(..)`, consistent with the leaf split.
96    KeywordMap => Keyword, "keyword"
97);
98map_handle!(
99    /// A dynamic-key object whose values are dates (`map` with a
100    /// `date`/`timestamp` value kind). [`key`](Self::key) yields a [`Date`]
101    /// leaf for range/exact operators (`gte`/`between`/`eq`/…).
102    DateMap => Date, "date"
103);
104
105/// A dynamic-key object whose values are numbers (`map` with a numeric value
106/// kind — `short`…`double`, `decimal`). [`key`](Self::key) yields a [`Number`]
107/// leaf for range/exact operators (`gt`/`between`/`eq`/…). `has_key`/`exists`
108/// are presence checks. No `search` — numbers aren't full text.
109#[derive(Debug, Clone)]
110pub struct NumberMap<K, S = Root> {
111    path: String,
112    _marker: PhantomData<fn() -> (K, S)>,
113}
114
115impl<K, S> NumberMap<K, S> {
116    pub fn at(path: impl Into<String>) -> Self {
117        Self {
118            path: path.into(),
119            _marker: PhantomData,
120        }
121    }
122
123    /// A specific runtime key → a [`Number`] leaf handle of value kind `K`,
124    /// queried like any other numeric field.
125    pub fn key(&self, key: impl AsRef<str>) -> Number<K, S> {
126        Number::at(format!("{}.{}", self.path, key.as_ref()))
127    }
128
129    /// The map holds the given key with a non-null value.
130    pub fn has_key(&self, key: impl AsRef<str>) -> Query<S> {
131        exists_q(&format!("{}.{}", self.path, key.as_ref()))
132    }
133
134    /// The map field itself is present (has at least one key).
135    pub fn exists(&self) -> Query<S> {
136        exists_q(&self.path)
137    }
138}
139
140impl<S> TextMap<S> {
141    /// Full-text search across *every* key at once, with optional per-key
142    /// preference. Returns a [`MapSearch`] builder; add [`prefer`](MapSearch::prefer)
143    /// to weight a key (e.g. the user's locale).
144    pub fn search(&self, query: impl Into<String>) -> MapSearch<S> {
145        MapSearch::new(&self.path, query.into())
146    }
147}
148
149/// A cross-key full-text query over a [`TextMap`]: one analyzed `query` matched
150/// against every key, with optional per-key preference. Renders a `multi_match`
151/// of `type: best_fields` over the preferred keys (each `field^weight`) plus the
152/// wildcard `path.*` fallback, so the best-scoring key wins without
153/// double-counting. [`only_preferred`](Self::only_preferred) drops the fallback.
154#[derive(Debug, Clone)]
155pub struct MapSearch<S = Root> {
156    path: String,
157    query: String,
158    preferred: Vec<String>,
159    include_all: bool,
160    opts: Map<String, Value>,
161    common: Common,
162    _scope: PhantomData<fn() -> S>,
163}
164
165impl<S> MapSearch<S> {
166    fn new(path: &str, query: String) -> Self {
167        Self {
168            path: path.to_string(),
169            query,
170            preferred: Vec::new(),
171            include_all: true,
172            opts: Map::new(),
173            common: Common::default(),
174            _scope: PhantomData,
175        }
176    }
177
178    /// Prefer a key, weighting its score by `weight` (`path.key^weight`). Add
179    /// several to rank keys (e.g. the user's locale highest).
180    #[must_use]
181    pub fn prefer(mut self, key: impl AsRef<str>, weight: f32) -> Self {
182        self.preferred
183            .push(format!("{}.{}^{weight}", self.path, key.as_ref()));
184        self
185    }
186
187    /// Search only the preferred keys — drop the `path.*` fallback that
188    /// otherwise also searches every other key.
189    #[must_use]
190    pub fn only_preferred(mut self) -> Self {
191        self.include_all = false;
192        self
193    }
194
195    fn set(mut self, key: &str, value: Value) -> Self {
196        self.opts.insert(key.to_string(), value);
197        self
198    }
199
200    /// Combine analyzed terms with [`Operator::And`] or [`Operator::Or`]
201    /// (default `Or`).
202    #[must_use]
203    pub fn operator(self, operator: Operator) -> Self {
204        self.set("operator", Value::String(operator.as_str().to_string()))
205    }
206
207    /// Edit distance for analyzed terms ([`Fuzziness::Auto`] is the usual choice).
208    #[must_use]
209    pub fn fuzziness(self, fuzziness: Fuzziness) -> Self {
210        self.set("fuzziness", fuzziness.to_value())
211    }
212
213    /// How many of the analyzed terms must match
214    /// (e.g. `2`, `MinimumShouldMatch::percent(75)`).
215    #[must_use]
216    pub fn minimum_should_match(self, value: impl Into<MinimumShouldMatch>) -> Self {
217        self.set("minimum_should_match", value.into().to_value())
218    }
219
220    common_opts!(common);
221}
222
223impl<S> AsQuery<S> for MapSearch<S> {
224    fn into_query(self) -> Option<Query<S>> {
225        let mut fields: Vec<Value> = self.preferred.iter().cloned().map(Value::String).collect();
226        if self.include_all {
227            fields.push(Value::String(format!("{}.*", self.path)));
228        }
229        let mut body = self.opts;
230        body.insert("query".to_string(), Value::String(self.query));
231        body.insert("fields".to_string(), Value::Array(fields));
232        // `best_fields` takes the max score per field, so the same term matching
233        // several keys isn't double-counted.
234        body.entry("type")
235            .or_insert_with(|| Value::String("best_fields".to_string()));
236        self.common.write(&mut body);
237        Some(wrap("multi_match", body))
238    }
239}