flusso-query 0.9.1

Backend-neutral OpenSearch/Elasticsearch query client for flusso indexes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Sort keys: [`SortOrder`], [`SortMode`], and the [`Sort`] builder produced by
//! `.asc()` / `.desc()` on a sortable handle (or `Geo::distance_sort`,
//! [`Sort::score`], [`Sort::script`]).
//!
//! A [`Sort`] carries the key it sorts on (a field path, `_score`,
//! `_geo_distance`, or `_script`) plus its options (`missing`, `mode`,
//! `unmapped_type`, …); `.missing_first()` / `.mode(..)` chain onto it, and it
//! renders to one entry in the `sort` array. The typed handle is always the
//! entry point — there is no public string-path sort.

use serde_json::{Map, Value};

use super::{Geo, GeoPoint, NumericType, ScriptSortType};
use crate::query::AsQuery;
use crate::{FlussoDocument, nested_boundaries};

/// Sort direction.
#[derive(Debug, Clone, Copy)]
pub enum SortOrder {
    /// Ascending.
    Asc,
    /// Descending.
    Desc,
}

impl SortOrder {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            SortOrder::Asc => "asc",
            SortOrder::Desc => "desc",
        }
    }
}

/// How a multi-valued field collapses to one sort value.
#[derive(Debug, Clone, Copy)]
pub enum SortMode {
    /// Smallest value.
    Min,
    /// Largest value.
    Max,
    /// Arithmetic mean (numeric fields).
    Avg,
    /// Sum (numeric fields).
    Sum,
    /// Median (numeric fields).
    Median,
}

impl SortMode {
    fn as_str(self) -> &'static str {
        match self {
            SortMode::Min => "min",
            SortMode::Max => "max",
            SortMode::Avg => "avg",
            SortMode::Sum => "sum",
            SortMode::Median => "median",
        }
    }
}

/// A single sort key. Produced by `.asc()` / `.desc()` on a sortable handle, by
/// [`Sort::score`] / [`Sort::script`], or by `Geo::distance_sort`; chain the
/// option setters (`missing_first`, `mode`, `unmapped_type`, …) onto it.
#[derive(Debug, Clone)]
pub struct Sort {
    key: String,
    body: Map<String, Value>,
}

impl Sort {
    /// A field/order sort: `{ "<field>": { "order": "asc"|"desc" } }`.
    pub(crate) fn new(field: &str, order: SortOrder) -> Self {
        let mut body = Map::new();
        body.insert(
            "order".to_string(),
            Value::String(order.as_str().to_string()),
        );
        Self {
            key: field.to_string(),
            body,
        }
    }

    /// Sort by relevance `_score` (descending by default).
    #[must_use]
    pub fn score() -> Self {
        let mut sort = Self {
            key: "_score".to_string(),
            body: Map::new(),
        };
        sort.body
            .insert("order".to_string(), Value::String("desc".to_string()));
        sort
    }

    /// Sort by a computed script value. `script_type` is the emitted value type
    /// ([`ScriptSortType::Number`] / [`ScriptSortType::String`]); `source` is
    /// the painless expression.
    #[must_use]
    pub fn script(
        script_type: ScriptSortType,
        source: impl Into<String>,
        order: SortOrder,
    ) -> Self {
        let mut script = Map::new();
        script.insert("source".to_string(), Value::String(source.into()));
        let mut body = Map::new();
        body.insert(
            "type".to_string(),
            Value::String(script_type.as_str().to_string()),
        );
        body.insert("script".to_string(), Value::Object(script));
        body.insert(
            "order".to_string(),
            Value::String(order.as_str().to_string()),
        );
        Self {
            key: "_script".to_string(),
            body,
        }
    }

    /// A pre-built sort clause (e.g. `_geo_distance`).
    pub(crate) fn from_parts(key: String, body: Map<String, Value>) -> Self {
        Self { key, body }
    }

    /// A field sort that is **nesting-aware**: it reads the scope `S`'s path and,
    /// when the field sits inside one or more `nested` arrays, wraps the sort in
    /// the matching `nested` chain (and defaults `mode` from the direction —
    /// `asc → min`, `desc → max`). A root or flattened-object field (empty path)
    /// renders a plain sort. Backs every [`Sortable`] handle.
    pub(crate) fn field<S: FlussoDocument>(path: &str, order: SortOrder) -> Self {
        let mut sort = Sort::new(path, order);
        let boundaries = nested_boundaries(S::PATH);
        if let Some(nested) = nested_clause(&boundaries) {
            sort.body.insert("nested".to_string(), nested);
            sort.body.insert(
                "mode".to_string(),
                Value::String(default_mode(order).to_string()),
            );
        }
        sort
    }

    /// Sort ascending.
    #[must_use]
    pub fn asc(mut self) -> Self {
        self.body
            .insert("order".to_string(), Value::String("asc".to_string()));
        self
    }

    /// Sort descending.
    #[must_use]
    pub fn desc(mut self) -> Self {
        self.body
            .insert("order".to_string(), Value::String("desc".to_string()));
        self
    }

    /// Place documents missing this field first.
    #[must_use]
    pub fn missing_first(mut self) -> Self {
        self.body
            .insert("missing".to_string(), Value::String("_first".to_string()));
        self
    }

    /// Place documents missing this field last.
    #[must_use]
    pub fn missing_last(mut self) -> Self {
        self.body
            .insert("missing".to_string(), Value::String("_last".to_string()));
        self
    }

    /// Substitute a literal value for documents missing this field.
    #[must_use]
    pub fn missing(mut self, value: impl Into<Value>) -> Self {
        self.body.insert("missing".to_string(), value.into());
        self
    }

    /// How a multi-valued field reduces to one sort value.
    #[must_use]
    pub fn mode(mut self, mode: SortMode) -> Self {
        self.body
            .insert("mode".to_string(), Value::String(mode.as_str().to_string()));
        self
    }

    /// Type to assume when the field is unmapped on some shard (instead of
    /// failing the search), e.g. `"long"`.
    #[must_use]
    pub fn unmapped_type(mut self, unmapped_type: impl Into<String>) -> Self {
        self.body.insert(
            "unmapped_type".to_string(),
            Value::String(unmapped_type.into()),
        );
        self
    }

    /// Numeric type to sort as ([`NumericType`]), for cross-index type coercion.
    #[must_use]
    pub fn numeric_type(mut self, numeric_type: NumericType) -> Self {
        self.body.insert(
            "numeric_type".to_string(),
            Value::String(numeric_type.as_str().to_string()),
        );
        self
    }

    /// Date `format` for a `date` field sort.
    #[must_use]
    pub fn format(mut self, format: impl Into<String>) -> Self {
        self.body
            .insert("format".to_string(), Value::String(format.into()));
        self
    }

    /// Sort by a field inside a `nested` array scoped to `path`, considering
    /// only elements matching `filter`. An escape hatch for the rare
    /// filter-scoped nested sort; ordinary nested sorts come from a
    /// [`Sortable`] handle, which derives the (possibly multi-level) `nested`
    /// chain from the field's scope automatically.
    #[must_use]
    pub fn nested_filtered<S>(mut self, path: impl Into<String>, filter: impl AsQuery<S>) -> Self {
        let mut nested = Map::new();
        nested.insert("path".to_string(), Value::String(path.into()));
        if let Some(query) = filter.into_query() {
            nested.insert("filter".to_string(), query.to_value());
        }
        self.body
            .insert("nested".to_string(), Value::Object(nested));
        self
    }

    pub(crate) fn to_value(&self) -> Value {
        let mut outer = Map::new();
        outer.insert(self.key.clone(), Value::Object(self.body.clone()));
        Value::Object(outer)
    }

    /// The key this sort orders on (a field path, `_score`, `_geo_distance`, or
    /// `_script`) — what [`SortBuilder`] dedups on.
    pub(crate) fn key(&self) -> &str {
        &self.key
    }

    /// Drop the `nested` chain (and its companion `mode`) for use inside
    /// `inner_hits`: there the sort already runs within the nested document, so
    /// the field path is relative and no wrapper applies. A plain or `_score`
    /// sort is unchanged.
    pub(crate) fn without_nested_context(mut self) -> Self {
        if self.body.remove("nested").is_some() {
            self.body.remove("mode");
        }
        self
    }
}

/// Wrap a plain sort in the `nested` chain for `boundaries` (cumulative dotted
/// paths, outermost first). `None` when there is no nesting.
fn nested_clause(boundaries: &[String]) -> Option<Value> {
    let (path, rest) = boundaries.split_first()?;
    let mut clause = Map::new();
    clause.insert("path".to_string(), Value::String(path.clone()));
    if let Some(inner) = nested_clause(rest) {
        clause.insert("nested".to_string(), inner);
    }
    Some(Value::Object(clause))
}

/// The `mode` a nested sort defaults to for `order`: the smallest element value
/// when ascending, the largest when descending (so the chosen element is the one
/// that sorts the parent extremally).
fn default_mode(order: SortOrder) -> &'static str {
    match order {
        SortOrder::Asc => "min",
        SortOrder::Desc => "max",
    }
}

/// A handle that can produce a field [`Sort`]. The compile-time gate for
/// [`SortBuilder::by`] / [`tiebreak`](SortBuilder::tiebreak): implemented for the
/// orderable leaf handles (`Keyword`, `Text`, `Number<K>`, `Date`, `Bool`) and
/// **not** for `Geo` / `Object` / map handles, so `by(geo_handle, …)` fails to
/// compile (geo sorts go through [`SortBuilder::near`] / [`raw`](SortBuilder::raw)).
///
/// `.asc()` / `.desc()` are nesting-aware: a field inside one or more `nested`
/// arrays renders the matching `nested` chain automatically, from the handle's
/// scope.
pub trait Sortable {
    /// Sort ascending.
    fn asc(&self) -> Sort;
    /// Sort descending.
    fn desc(&self) -> Sort;
}

/// Where to place documents missing the sorted field (a field-sort `missing`).
#[derive(Debug, Clone)]
pub enum Missing {
    /// Missing values sort first (`_first`).
    First,
    /// Missing values sort last (`_last`).
    Last,
    /// Missing values take this substitute value.
    Value(Value),
}

/// A field sort minus the field — a direction plus the field-sort modifiers,
/// ready to attach to whatever handle [`SortBuilder::by`] is given.
///
/// This is what a consumer converts its own request enum into, once
/// (`impl From<MyDir> for OrderBy`). It carries full parity with [`Sort`]'s
/// field-sort options; everything but the direction defaults to unset.
#[derive(Debug, Clone)]
pub struct OrderBy {
    order: SortOrder,
    missing: Option<Missing>,
    mode: Option<SortMode>,
    numeric_type: Option<NumericType>,
    unmapped_type: Option<String>,
    format: Option<String>,
}

impl OrderBy {
    /// Ascending, no modifiers.
    #[must_use]
    pub fn asc() -> Self {
        Self::new(SortOrder::Asc)
    }

    /// Descending, no modifiers.
    #[must_use]
    pub fn desc() -> Self {
        Self::new(SortOrder::Desc)
    }

    fn new(order: SortOrder) -> Self {
        Self {
            order,
            missing: None,
            mode: None,
            numeric_type: None,
            unmapped_type: None,
            format: None,
        }
    }

    /// Place documents missing this field first.
    #[must_use]
    pub fn missing_first(mut self) -> Self {
        self.missing = Some(Missing::First);
        self
    }

    /// Place documents missing this field last.
    #[must_use]
    pub fn missing_last(mut self) -> Self {
        self.missing = Some(Missing::Last);
        self
    }

    /// Substitute a literal value for documents missing this field.
    #[must_use]
    pub fn missing(mut self, value: impl Into<Value>) -> Self {
        self.missing = Some(Missing::Value(value.into()));
        self
    }

    /// How a multi-valued field reduces to one sort value.
    #[must_use]
    pub fn mode(mut self, mode: SortMode) -> Self {
        self.mode = Some(mode);
        self
    }

    /// Numeric type to sort as, for cross-index type coercion.
    #[must_use]
    pub fn numeric_type(mut self, numeric_type: NumericType) -> Self {
        self.numeric_type = Some(numeric_type);
        self
    }

    /// Type to assume when the field is unmapped on some shard.
    #[must_use]
    pub fn unmapped_type(mut self, unmapped_type: impl Into<String>) -> Self {
        self.unmapped_type = Some(unmapped_type.into());
        self
    }

    /// Date `format` for a `date` field sort.
    #[must_use]
    pub fn format(mut self, format: impl Into<String>) -> Self {
        self.format = Some(format.into());
        self
    }

    /// Build the field [`Sort`] for `handle`, in this order with these modifiers.
    fn into_sort<H: Sortable>(self, handle: &H) -> Sort {
        let mut sort = match self.order {
            SortOrder::Asc => handle.asc(),
            SortOrder::Desc => handle.desc(),
        };
        sort = match self.missing {
            Some(Missing::First) => sort.missing_first(),
            Some(Missing::Last) => sort.missing_last(),
            Some(Missing::Value(value)) => sort.missing(value),
            None => sort,
        };
        if let Some(mode) = self.mode {
            sort = sort.mode(mode);
        }
        if let Some(numeric_type) = self.numeric_type {
            sort = sort.numeric_type(numeric_type);
        }
        if let Some(unmapped_type) = self.unmapped_type {
            sort = sort.unmapped_type(unmapped_type);
        }
        if let Some(format) = self.format {
            sort = sort.format(format);
        }
        sort
    }
}

impl From<SortOrder> for OrderBy {
    fn from(order: SortOrder) -> Self {
        Self::new(order)
    }
}

/// The optionality carrier for [`SortBuilder::by`]: an absent order skips the
/// field. A local newtype because coherence forbids `impl From<…> for Option<_>`.
///
/// `SortOrder`, `OrderBy`, and — via the umbrella impl — `Option<T: Into<OrderBy>>`
/// all flow in, so a consumer's `Option<MyDir>` self-skips on `None` after one
/// `impl From<MyDir> for OrderBy`.
#[derive(Debug, Clone)]
pub struct MaybeOrderBy(Option<OrderBy>);

impl From<OrderBy> for MaybeOrderBy {
    fn from(order: OrderBy) -> Self {
        Self(Some(order))
    }
}

impl From<SortOrder> for MaybeOrderBy {
    fn from(order: SortOrder) -> Self {
        Self(Some(order.into()))
    }
}

impl<T: Into<OrderBy>> From<Option<T>> for MaybeOrderBy {
    fn from(order: Option<T>) -> Self {
        Self(order.map(Into::into))
    }
}

/// Builds the `sort` array, one fluent verb per concern — each absorbing its own
/// optionality so a request maps straight through with no per-field `if let`.
///
/// `by`/`near`/`tiebreak`/`or_default` **dedup** by sort key (first wins), so a
/// field added twice — or an explicit sort that a tiebreak/default would repeat —
/// appears once; `raw` is exempt. `or_default` only contributes when the builder
/// would otherwise be empty.
///
/// ```
/// use flusso_query::{SortBuilder, SortOrder, OrderBy};
/// # use flusso_query::{Keyword, Number, kind, Root};
/// # fn keyword(p: &str) -> Keyword<Root> { Keyword::at(p) }
/// # fn count() -> Number<kind::Long, Root> { Number::at("orderCount") }
/// let sorts = SortBuilder::new()
///     .score_if(true)
///     .by(count(), SortOrder::Desc)
///     .by(keyword("city"), None::<OrderBy>)   // skipped
///     .tiebreak(keyword("id"))
///     .build();
/// assert_eq!(sorts.len(), 3);                 // _score, orderCount, id
/// ```
#[derive(Debug, Default)]
pub struct SortBuilder {
    sorts: Vec<Sort>,
    fallback: Option<Sort>,
}

impl SortBuilder {
    /// An empty builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Push `sort` unless its key is already present (first wins).
    fn push_unique(&mut self, sort: Sort) {
        if !self
            .sorts
            .iter()
            .any(|existing| existing.key() == sort.key())
        {
            self.sorts.push(sort);
        }
    }

    /// Sort by a field. `dir` accepts a [`SortOrder`], an [`OrderBy`], or an
    /// `Option` of either (a `None` skips the field) — so a request's
    /// `Option<dir>` flows straight in. Nesting-aware: a field inside `nested`
    /// arrays renders the right `nested` chain from its scope.
    #[must_use]
    pub fn by<H: Sortable>(mut self, handle: H, dir: impl Into<MaybeOrderBy>) -> Self {
        if let Some(order) = dir.into().0 {
            self.push_unique(order.into_sort(&handle));
        }
        self
    }

    /// Sort by distance from `center` (`_geo_distance`, nearest first). A `None`
    /// center skips it. Pass a unit / script geo sort through [`raw`](Self::raw).
    #[must_use]
    pub fn near<S>(mut self, handle: Geo<S>, center: impl Into<Option<GeoPoint>>) -> Self {
        if let Some(center) = center.into() {
            self.push_unique(handle.distance_from(center));
        }
        self
    }

    /// Sort by relevance `_score` (descending).
    #[must_use]
    pub fn score(mut self) -> Self {
        self.push_unique(Sort::score());
        self
    }

    /// Sort by `_score` only when `cond` holds (e.g. a free-text query is present).
    #[must_use]
    pub fn score_if(self, cond: bool) -> Self {
        if cond { self.score() } else { self }
    }

    /// Append a pre-built [`Sort`] verbatim — the escape hatch for sorts the
    /// typed verbs don't cover (`_script`, a geo sort with options). A `None`
    /// adds nothing. **Not** deduped.
    #[must_use]
    pub fn raw(mut self, sort: impl Into<Option<Sort>>) -> Self {
        if let Some(sort) = sort.into() {
            self.sorts.push(sort);
        }
        self
    }

    /// A stable final sort key (ascending) — append a unique field so equal
    /// leading keys still page deterministically.
    #[must_use]
    pub fn tiebreak<H: Sortable>(mut self, handle: H) -> Self {
        self.push_unique(handle.asc());
        self
    }

    /// A fallback used only if nothing else lands in the builder.
    #[must_use]
    pub fn or_default(mut self, sort: impl Into<Sort>) -> Self {
        if self.fallback.is_none() {
            self.fallback = Some(sort.into());
        }
        self
    }

    /// Finish: the `sort` array (the fallback, if set, when otherwise empty).
    #[must_use]
    pub fn build(mut self) -> Vec<Sort> {
        if self.sorts.is_empty()
            && let Some(fallback) = self.fallback
        {
            self.sorts.push(fallback);
        }
        self.sorts
    }
}

impl IntoIterator for SortBuilder {
    type Item = Sort;
    type IntoIter = std::vec::IntoIter<Sort>;

    fn into_iter(self) -> Self::IntoIter {
        self.build().into_iter()
    }
}