lucisearch 0.8.0

Embeddable, in-process search engine — the SQLite/DuckDB of Elasticsearch
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
//! Query expression types — the output of JSON parsing and input to execution.
//!
//! See [[query-dsl]] and [[architecture-query-execution#Step 3]].

/// Universal query expression — the top level of every search request.
///
/// `Scoring` variants produce per-document scores via the Scorer pipeline.
/// `Ranking` variants compose result sets (fusion, RRF).
/// Type-safe nesting: Bool clauses accept only `ScoringExpression`,
/// Fusion sources accept `QueryExpression` (enabling nested fusion).
///
/// See [[feature-rrf-retrievers]].
#[derive(Clone, Debug, PartialEq)]
pub enum QueryExpression {
    /// Per-document scoring query (BM25, kNN, bool, etc.).
    Scoring(ScoringExpression),
    /// Result-set composition (fusion, RRF).
    Ranking(RankingExpression),
}

/// Result-set composition expressions.
///
/// See [[feature-rrf-retrievers#RankingExpression]].
#[derive(Clone, Debug, PartialEq)]
pub enum RankingExpression {
    /// Fuse N query sources using a configurable method.
    ///
    /// Each source is executed independently, then results are combined
    /// using the specified fusion method. Sources can be scoring queries
    /// or nested fusion expressions.
    Fusion {
        sources: Vec<QueryExpression>,
        method: FusionMethod,
        /// Rank constant k for RRF: `score(d) = Σ 1/(k + rank)`. Default: 60.
        rank_constant: f32,
        /// Number of candidates per source before fusion.
        /// Default: search size.
        rank_window_size: Option<usize>,
        /// Per-source weights for score-based fusion methods.
        /// Default: equal weights (1.0 each).
        weights: Option<Vec<f32>>,
    },
}

/// Fusion method for combining multiple ranked result lists.
///
/// See [[feature-rrf-retrievers#FusionMethod]].
#[derive(Clone, Debug, PartialEq)]
pub enum FusionMethod {
    /// Reciprocal Rank Fusion — rank-based, ignores actual scores.
    /// `score(d) = Σ weight_i / (rank_constant + rank_i(d))`
    ReciprocalRank,
    /// Weighted sum of scores.
    /// `score(d) = Σ weight_i * score_i(d)`
    Sum,
    /// Weighted arithmetic mean.
    ArithmeticMean,
    /// Weighted harmonic mean.
    HarmonicMean,
    /// Weighted geometric mean.
    GeometricMean,
}

impl QueryExpression {
    /// Extract the scoring expression, if this is a Scoring variant.
    pub fn as_scoring(&self) -> Option<&ScoringExpression> {
        match self {
            QueryExpression::Scoring(s) => Some(s),
            QueryExpression::Ranking(_) => None,
        }
    }

    /// Collect all scoring expressions from this query tree.
    /// For Scoring: returns the single expression.
    /// For Ranking(Fusion): recursively collects from all sources.
    pub fn scoring_expressions(&self) -> Vec<&ScoringExpression> {
        match self {
            QueryExpression::Scoring(s) => vec![s],
            QueryExpression::Ranking(RankingExpression::Fusion { sources, .. }) => sources
                .iter()
                .flat_map(|s| s.scoring_expressions())
                .collect(),
        }
    }
}

/// Configuration for inner_hits on nested queries.
/// See [[feature-search-inner-hits]].
#[derive(Clone, Debug, PartialEq)]
pub struct InnerHitsConfig {
    pub name: Option<String>,
    pub size: usize,
    pub from: usize,
}

/// Typed query expression. Each variant maps to an ES-compatible query type.
#[derive(Clone, Debug, PartialEq)]
pub enum ScoringExpression {
    /// Exact term match on a field (no analysis).
    Term { field: String, value: String },

    /// Match any of a set of exact values.
    Terms { field: String, values: Vec<String> },

    /// Full-text match: analyze query text, build bool of term queries.
    Match {
        field: String,
        query: String,
        analyzer: Option<String>,
    },

    /// Phrase match: terms must appear in order at consecutive positions.
    MatchPhrase {
        field: String,
        query: String,
        analyzer: Option<String>,
    },

    /// Match bool prefix: analyzes text, all tokens become term queries
    /// except the last which becomes a prefix query. Rewrites to bool/should.
    MatchBoolPrefix {
        field: String,
        query: String,
        analyzer: Option<String>,
    },

    /// Boolean combination of sub-queries.
    ///
    /// `minimum_should_match` requires at least N should clauses to match.
    /// Default behavior: if must/filter present and msm is None, should
    /// clauses are optional (boost only). If no must/filter and msm is
    /// None, at least 1 should must match.
    ///
    /// See [[feature-minimum-should-match]].
    Bool {
        must: Vec<ScoringExpression>,
        should: Vec<ScoringExpression>,
        must_not: Vec<ScoringExpression>,
        filter: Vec<ScoringExpression>,
        minimum_should_match: Option<u32>,
    },

    /// Disjunction max: return the score from the best-matching sub-query,
    /// plus tie_breaker * sum of other matching scores.
    DisMax {
        queries: Vec<ScoringExpression>,
        tie_breaker: f32,
    },

    /// Field exists (has a non-null value).
    Exists { field: String },

    /// Prefix match on a field's terms.
    Prefix { field: String, value: String },

    /// Wrap a query in filter context with a constant score.
    ConstantScore {
        query: Box<ScoringExpression>,
        boost: f32,
    },

    /// Nested query: search within nested document arrays.
    Nested {
        path: String,
        query: Box<ScoringExpression>,
        inner_hits: Option<InnerHitsConfig>,
    },

    /// Geographic distance query.
    GeoDistance {
        field: String,
        lat: f64,
        lon: f64,
        distance: String, // e.g. "10km"
    },

    /// Geographic bounding box query.
    GeoBoundingBox {
        field: String,
        top_left_lat: f64,
        top_left_lon: f64,
        bottom_right_lat: f64,
        bottom_right_lon: f64,
    },

    /// Geographic shape query with spatial relation.
    ///
    /// See [[feature-geo-shape]] and [[de-9im]].
    GeoShape {
        field: String,
        shape: GeoShapeValue,
        relation: SpatialRelation,
    },

    /// Numeric range query on a field.
    Range {
        field: String,
        gte: Option<f64>,
        gt: Option<f64>,
        lte: Option<f64>,
        lt: Option<f64>,
    },

    /// Boost wrapper: multiplies inner query's score by a factor.
    Boost {
        query: Box<ScoringExpression>,
        boost: f32,
    },

    /// Script score: compiled expression-based custom scoring.
    ScriptScore {
        query: Box<ScoringExpression>,
        script: String,
        params: std::collections::HashMap<String, f64>,
    },

    /// Function score: modify query scores with scoring functions.
    FunctionScore {
        query: Box<ScoringExpression>,
        functions: Vec<ScoreFunction>,
        score_mode: FunctionScoreMode,
        boost_mode: FunctionBoostMode,
    },

    /// Boosting: positive query with score demotion for negative matches.
    Boosting {
        positive: Box<ScoringExpression>,
        negative: Box<ScoringExpression>,
        negative_boost: f32,
    },

    /// Fuzzy match: terms within edit distance.
    Fuzzy {
        field: String,
        value: String,
        fuzziness: u32,
    },

    /// Regexp match on term dictionary.
    Regexp { field: String, value: String },

    /// Wildcard match: * (any chars) and ? (single char).
    Wildcard { field: String, value: String },

    /// Multi-field match: search the same query across multiple fields.
    /// Defaults to `best_fields` (dis_max with tie_breaker=0.0).
    MultiMatch {
        fields: Vec<String>,
        query: String,
        analyzer: Option<String>,
        tie_breaker: f32,
    },

    /// Span-typed query (position-aware). The inner
    /// [`SpanExpression`] enumerates the concrete span variants; this
    /// single wrapper parallels [`QueryExpression::Scoring`] wrapping
    /// a `ScoringExpression` — one concept, one representation.
    Span(SpanExpression),

    /// Approximate k-nearest-neighbor search on a dense_vector field.
    ///
    /// Results are pre-materialized at bind time via HNSW graph traversal.
    /// The scorer iterates a small sorted array of (doc_id, score) pairs.
    /// Score conversion is metric-specific (see [`crate::vector::distance_to_score`]).
    ///
    /// See [[feature-knn-query-type]].
    Knn {
        field: String,
        query_vector: Vec<f32>,
        k: usize,
        num_candidates: usize,
        /// Minimum score threshold. Results with score < threshold are excluded.
        threshold: Option<f32>,
    },

    /// Match all documents.
    MatchAll,

    /// Match no documents.
    MatchNone,
}

/// Span-typed expression — the subset of queries that yield
/// `(doc, start, end)` span tuples and can be composed by span
/// operators (`SpanFirst`, `SpanNot`, `SpanNear`).
///
/// The parser produces this type for `span_first.match` and
/// `span_not.include / exclude`, so the AST makes it unrepresentable
/// to place a non-span query inside a span composition operator —
/// the mistake would require constructing an invalid enum variant,
/// which doesn't type-check. This replaces runtime dispatch and
/// default-trait-error rejection in the engine.
#[derive(Clone, Debug, PartialEq)]
pub enum SpanExpression {
    /// Single term with position awareness.
    SpanTerm { field: String, value: String },
    /// Terms within slop positions, optionally ordered.
    SpanNear {
        field: String,
        terms: Vec<String>,
        slop: u32,
        in_order: bool,
    },
    /// Include spans minus exclude spans (doc-level overlap in Luci).
    SpanNot {
        include: Box<SpanExpression>,
        exclude: Box<SpanExpression>,
    },
    /// Spans ending at position ≤ end.
    SpanFirst {
        query: Box<SpanExpression>,
        end: u32,
    },
}

/// A scoring function for function_score queries.
#[derive(Clone, Debug, PartialEq)]
pub enum ScoreFunction {
    /// Multiply score by a constant weight.
    Weight(f32),
    /// Score based on a numeric field's value.
    FieldValueFactor {
        field: String,
        factor: f32,
        modifier: FieldValueModifier,
        missing: f64,
    },
    /// Random score (deterministic per seed + doc).
    RandomScore { seed: u64 },
}

/// Modifier for field_value_factor.
#[derive(Clone, Debug, PartialEq)]
pub enum FieldValueModifier {
    None,
    Log1p,
    Log2p,
    Ln1p,
    Ln2p,
    Sqrt,
    Square,
    Reciprocal,
}

/// How to combine multiple function scores.
#[derive(Clone, Debug, PartialEq)]
pub enum FunctionScoreMode {
    Multiply,
    Sum,
    Avg,
    First,
    Max,
    Min,
}

/// How to combine the function result with the query score.
#[derive(Clone, Debug, PartialEq)]
pub enum FunctionBoostMode {
    Multiply,
    Replace,
    Sum,
    Avg,
    Max,
    Min,
}

/// Spatial relation for geo_shape queries.
///
/// Supports the full [[ogc-simple-features]] / [[de-9im]] predicate set.
#[derive(Clone, Debug, PartialEq)]
pub enum SpatialRelation {
    /// Query and document shapes share any area or boundary (default).
    Intersects,
    /// Document shape is entirely inside the query shape.
    Within,
    /// Document shape entirely contains the query shape.
    Contains,
    /// Query and document shapes share no area or boundary.
    Disjoint,
    /// Shapes meet at boundary but don't overlap interiors.
    Touches,
    /// Interiors intersect but neither contains the other.
    Crosses,
    /// Shared interior area, same dimension, neither contains the other.
    Overlaps,
    /// Geometries are topologically identical.
    Equals,
    /// Like Contains but includes boundary contact.
    Covers,
    /// Like Within but includes boundary contact.
    CoveredBy,
    /// Interior of document shape contains all of query shape (strict).
    ContainsProperly,
}

/// A parsed GeoJSON shape for use in geo_shape queries.
#[derive(Clone, Debug, PartialEq)]
pub struct GeoShapeValue {
    /// The raw GeoJSON shape object (type + coordinates).
    pub json: serde_json::Value,
}

impl ScoringExpression {
    /// Convenience constructor for a bool query.
    pub fn bool_query(
        must: Vec<ScoringExpression>,
        should: Vec<ScoringExpression>,
        must_not: Vec<ScoringExpression>,
        filter: Vec<ScoringExpression>,
    ) -> Self {
        Self::Bool {
            must,
            should,
            must_not,
            filter,
            minimum_should_match: None,
        }
    }
}

impl super::Query for ScoringExpression {
    /// Bind this query expression to index statistics, producing a BoundQuery.
    ///
    /// Recursively compiles the expression tree into executable form,
    /// binding to the Searcher's index-level statistics (IDF, avg field
    /// lengths, etc.). Each variant directly constructs the concrete query
    /// struct and binds it, bypassing the `ast_to_query` indirection.
    /// Sub-queries bind recursively via `ScoringExpression::bind`.
    fn bind(
        &self,
        searcher: &crate::search::searcher::Searcher,
        score_mode: crate::core::ScoreMode,
    ) -> crate::core::Result<Box<dyn super::BoundQuery>> {
        match self {
            // --- Simple term-level queries ---
            ScoringExpression::Term { field, value } => crate::query::term::TermQuery {
                field: field.clone(),
                value: value.clone(),
            }
            .bind(searcher, score_mode),

            ScoringExpression::Terms { field, values } => {
                // Rewrite to Bool { should: [Term * N] }
                let should: Vec<ScoringExpression> = values
                    .iter()
                    .map(|v| ScoringExpression::Term {
                        field: field.clone(),
                        value: v.clone(),
                    })
                    .collect();
                ScoringExpression::Bool {
                    must: vec![],
                    should,
                    must_not: vec![],
                    filter: vec![],
                    minimum_should_match: None,
                }
                .bind(searcher, score_mode)
            }

            // --- Full-text queries ---
            ScoringExpression::Match {
                field,
                query,
                analyzer,
            } => crate::query::match_query::MatchQuery {
                field: field.clone(),
                query_text: query.clone(),
                analyzer: analyzer.clone(),
            }
            .bind(searcher, score_mode),

            ScoringExpression::MatchPhrase {
                field,
                query,
                analyzer,
            } => crate::query::phrase::MatchPhraseQuery {
                field: field.clone(),
                query_text: query.clone(),
                analyzer: analyzer.clone(),
            }
            .bind(searcher, score_mode),

            ScoringExpression::MatchBoolPrefix {
                field,
                query,
                analyzer,
            } => {
                // Rewrite: analyze text using the searcher's analyzer
                // registry (must respect custom and field-configured
                // analyzers), all tokens -> term queries, last ->
                // prefix query, wrap in Bool/should.
                // See [[investigation-20260405-06-match-bool-prefix-analyzer]].
                let analyzer_name = searcher.resolve_search_analyzer(field, analyzer.as_deref());
                let analyzers = searcher.analyzers();
                let analyzer_impl = analyzers.get(analyzer_name);
                let analyzed = analyzer_impl.analyze(query);
                let tokens: Vec<String> = analyzed.into_iter().map(|t| t.text).collect();
                if tokens.is_empty() {
                    crate::query::convert::MatchNoneQuery.bind(searcher, score_mode)
                } else {
                    let mut should: Vec<ScoringExpression> = Vec::new();
                    for (i, token) in tokens.iter().enumerate() {
                        if i == tokens.len() - 1 {
                            should.push(ScoringExpression::Prefix {
                                field: field.clone(),
                                value: token.clone(),
                            });
                        } else {
                            should.push(ScoringExpression::Term {
                                field: field.clone(),
                                value: token.clone(),
                            });
                        }
                    }
                    ScoringExpression::Bool {
                        must: vec![],
                        should,
                        must_not: vec![],
                        filter: vec![],
                        minimum_should_match: None,
                    }
                    .bind(searcher, score_mode)
                }
            }

            ScoringExpression::MultiMatch {
                fields,
                query,
                analyzer,
                tie_breaker,
            } => {
                // Rewrite to DisMax (best_fields). With tie_breaker=0.0
                // (default), score = max(field_scores). With tie_breaker=1.0
                // (most_fields), score = sum(field_scores).
                // See [[investigation-20260405-04-multi-match-wrong-rewrite]].
                let queries: Vec<ScoringExpression> = fields
                    .iter()
                    .map(|f| ScoringExpression::Match {
                        field: f.clone(),
                        query: query.clone(),
                        analyzer: analyzer.clone(),
                    })
                    .collect();
                ScoringExpression::DisMax {
                    queries,
                    tie_breaker: *tie_breaker,
                }
                .bind(searcher, score_mode)
            }

            // --- Compound queries (recursive) ---
            ScoringExpression::Bool {
                must,
                should,
                must_not,
                filter,
                minimum_should_match,
            } => crate::query::boolean::BoolQuery {
                must: must
                    .iter()
                    .map(|q| -> Box<dyn super::Query> { Box::new(q.clone()) })
                    .collect(),
                should: should
                    .iter()
                    .map(|q| -> Box<dyn super::Query> { Box::new(q.clone()) })
                    .collect(),
                must_not: must_not
                    .iter()
                    .map(|q| -> Box<dyn super::Query> { Box::new(q.clone()) })
                    .collect(),
                filter: filter
                    .iter()
                    .map(|q| -> Box<dyn super::Query> { Box::new(q.clone()) })
                    .collect(),
                minimum_should_match: *minimum_should_match,
            }
            .bind(searcher, score_mode),

            ScoringExpression::DisMax {
                queries,
                tie_breaker,
            } => crate::query::dis_max::DisMaxQuery {
                queries: queries
                    .iter()
                    .map(|q| -> Box<dyn super::Query> { Box::new(q.clone()) })
                    .collect(),
                tie_breaker: *tie_breaker,
            }
            .bind(searcher, score_mode),

            ScoringExpression::ConstantScore { query, boost } => {
                crate::query::constant_score::ConstantScoreQuery {
                    inner: Box::new(query.as_ref().clone()),
                    boost: *boost,
                }
                .bind(searcher, score_mode)
            }

            ScoringExpression::Boost { query, boost } => crate::query::boost::BoostQuery {
                inner: Box::new(query.as_ref().clone()),
                boost: *boost,
            }
            .bind(searcher, score_mode),

            ScoringExpression::Boosting {
                positive,
                negative,
                negative_boost,
            } => crate::query::boosting::BoostingQuery {
                positive: Box::new(positive.as_ref().clone()),
                negative: Box::new(negative.as_ref().clone()),
                negative_boost: *negative_boost,
            }
            .bind(searcher, score_mode),

            ScoringExpression::ScriptScore {
                query,
                script,
                params,
            } => crate::query::script_score::ScriptScoreQuery {
                query: Box::new(query.as_ref().clone()),
                script: script.clone(),
                params: params.clone(),
            }
            .bind(searcher, score_mode),

            ScoringExpression::FunctionScore {
                query,
                functions,
                score_mode: fn_score_mode,
                boost_mode,
            } => crate::query::function_score::FunctionScoreQuery {
                query: Box::new(query.as_ref().clone()),
                functions: functions.clone(),
                score_mode: fn_score_mode.clone(),
                boost_mode: boost_mode.clone(),
            }
            .bind(searcher, score_mode),

            ScoringExpression::Nested {
                path,
                query,
                inner_hits,
            } => crate::query::nested::NestedQuery {
                path: path.clone(),
                inner: Box::new(query.as_ref().clone()),
                inner_hits: inner_hits.clone(),
            }
            .bind(searcher, score_mode),

            // --- Filter-context queries ---
            ScoringExpression::Exists { field } => crate::query::exists::ExistsQuery {
                field: field.clone(),
            }
            .bind(searcher, score_mode),

            ScoringExpression::Prefix { field, value } => crate::query::prefix::PrefixQuery {
                field: field.clone(),
                value: value.clone(),
            }
            .bind(searcher, score_mode),

            ScoringExpression::Range {
                field,
                gte,
                gt,
                lte,
                lt,
            } => crate::query::range::RangeQuery {
                field: field.clone(),
                gte: *gte,
                gt: *gt,
                lte: *lte,
                lt: *lt,
            }
            .bind(searcher, score_mode),

            // --- Rewrite queries (scan term dict, then bind) ---
            ScoringExpression::Fuzzy {
                field,
                value,
                fuzziness,
            } => crate::query::fuzzy::FuzzyQuery {
                field: field.clone(),
                value: value.clone(),
                fuzziness: *fuzziness,
            }
            .bind(searcher, score_mode),

            ScoringExpression::Wildcard { field, value } => crate::query::wildcard::WildcardQuery {
                field: field.clone(),
                pattern: value.clone(),
            }
            .bind(searcher, score_mode),

            ScoringExpression::Regexp { field, value } => crate::query::regexp::RegexpQuery {
                field: field.clone(),
                pattern: value.clone(),
            }
            .bind(searcher, score_mode),

            // --- Geo queries ---
            ScoringExpression::GeoDistance {
                field,
                lat,
                lon,
                distance,
            } => {
                let distance_km = crate::query::parser::parse_distance_km(distance);
                crate::spatial::query::GeoDistanceQuery {
                    field: field.clone(),
                    center: crate::spatial::geo::GeoPoint::new(*lat, *lon),
                    distance_km,
                }
                .bind(searcher, score_mode)
            }

            ScoringExpression::GeoBoundingBox {
                field,
                top_left_lat,
                top_left_lon,
                bottom_right_lat,
                bottom_right_lon,
            } => crate::spatial::query::GeoBoundingBoxQuery {
                field: field.clone(),
                top_left: crate::spatial::geo::GeoPoint::new(*top_left_lat, *top_left_lon),
                bottom_right: crate::spatial::geo::GeoPoint::new(
                    *bottom_right_lat,
                    *bottom_right_lon,
                ),
            }
            .bind(searcher, score_mode),

            ScoringExpression::GeoShape {
                field,
                shape,
                relation,
            } => {
                let query_geom = crate::spatial::shape::parse_geojson(&shape.json)
                    .unwrap_or(::geo::Geometry::Point(::geo::Point::new(0.0, 0.0)));
                let query_bbox = crate::spatial::shape::compute_bbox(&query_geom)
                    .unwrap_or((0.0, 0.0, 0.0, 0.0));
                crate::spatial::query::GeoShapeQuery {
                    field: field.clone(),
                    query_shape: query_geom,
                    query_bbox,
                    relation: relation.clone(),
                }
                .bind(searcher, score_mode)
            }

            // --- Span queries ---
            // Single Span(...) wrapper delegates to the span runtime
            // layer — mirrors QueryExpression::Scoring(ScoringExpression).
            ScoringExpression::Span(span_ast) => {
                Ok(crate::query::convert::ast_to_span_query(span_ast)
                    .bind_span(searcher, score_mode)?)
            }

            // --- Vector queries ---
            ScoringExpression::Knn {
                field,
                query_vector,
                k,
                num_candidates,
                threshold,
            } => crate::vector::query::KnnQuery {
                field: field.clone(),
                query_vector: query_vector.clone(),
                k: *k,
                num_candidates: *num_candidates,
                threshold: *threshold,
            }
            .bind(searcher, score_mode),

            // --- Terminal queries ---
            ScoringExpression::MatchAll => {
                crate::query::convert::MatchAllQuery.bind(searcher, score_mode)
            }

            ScoringExpression::MatchNone => {
                crate::query::convert::MatchNoneQuery.bind(searcher, score_mode)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn term_query() {
        let q = ScoringExpression::Term {
            field: "status".into(),
            value: "active".into(),
        };
        assert_eq!(
            q,
            ScoringExpression::Term {
                field: "status".into(),
                value: "active".into()
            }
        );
    }

    #[test]
    fn bool_query_construction() {
        let q = ScoringExpression::bool_query(
            vec![ScoringExpression::Term {
                field: "f".into(),
                value: "v".into(),
            }],
            vec![],
            vec![],
            vec![],
        );
        if let ScoringExpression::Bool { must, .. } = &q {
            assert_eq!(must.len(), 1);
        } else {
            panic!("expected Bool");
        }
    }

    #[test]
    fn nested_bool() {
        let inner = ScoringExpression::bool_query(
            vec![ScoringExpression::MatchAll],
            vec![],
            vec![],
            vec![],
        );
        let outer = ScoringExpression::bool_query(vec![inner], vec![], vec![], vec![]);
        if let ScoringExpression::Bool { must, .. } = &outer {
            assert!(matches!(&must[0], ScoringExpression::Bool { .. }));
        }
    }

    #[test]
    fn constant_score_wraps() {
        let q = ScoringExpression::ConstantScore {
            query: Box::new(ScoringExpression::Term {
                field: "f".into(),
                value: "v".into(),
            }),
            boost: 1.5,
        };
        if let ScoringExpression::ConstantScore { boost, .. } = q {
            assert_eq!(boost, 1.5);
        }
    }

    #[test]
    fn match_query() {
        let q = ScoringExpression::Match {
            field: "body".into(),
            query: "search engine".into(),
            analyzer: None,
        };
        if let ScoringExpression::Match { field, query, .. } = &q {
            assert_eq!(field, "body");
            assert_eq!(query, "search engine");
        }
    }

    #[test]
    fn debug_format() {
        let q = ScoringExpression::MatchAll;
        let s = format!("{q:?}");
        assert!(s.contains("MatchAll"));
    }

    #[test]
    fn clone_works() {
        let q = ScoringExpression::Term {
            field: "f".into(),
            value: "v".into(),
        };
        let q2 = q.clone();
        assert_eq!(q, q2);
    }

    #[test]
    fn terms_query() {
        let q = ScoringExpression::Terms {
            field: "tags".into(),
            values: vec!["a".into(), "b".into(), "c".into()],
        };
        if let ScoringExpression::Terms { values, .. } = &q {
            assert_eq!(values.len(), 3);
        }
    }
}