laurus 0.6.0

Unified search library for lexical, vector, and semantic retrieval
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
//! Boolean query implementation for combining multiple queries.

use crate::error::Result;
use crate::lexical::query::Query;
use crate::lexical::query::matcher::{
    AllMatcher, ConjunctionMatcher, ConjunctionNotMatcher, DisjunctionMatcher, EmptyMatcher,
    Matcher, NotMatcher,
};
use crate::lexical::query::scorer::{BM25Scorer, Scorer};
use crate::lexical::reader::LexicalIndexReader;

/// Occurrence requirements for boolean clauses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Occur {
    /// The clause must match (equivalent to AND).
    Must,
    /// The clause should match (equivalent to OR).
    Should,
    /// The clause must not match (equivalent to NOT).
    MustNot,
    /// The clause must match but does not contribute to scoring.
    /// Used for filtering results without affecting relevance scores.
    Filter,
}

/// A clause in a boolean query.
#[derive(Debug)]
pub struct BooleanClause {
    /// The query for this clause.
    pub query: Box<dyn Query>,
    /// The occurrence requirement.
    pub occur: Occur,
}

impl Clone for BooleanClause {
    fn clone(&self) -> Self {
        BooleanClause {
            query: self.query.clone_box(),
            occur: self.occur,
        }
    }
}

impl BooleanClause {
    /// Create a new boolean clause.
    pub fn new(query: Box<dyn Query>, occur: Occur) -> Self {
        BooleanClause { query, occur }
    }

    /// Create a MUST clause.
    pub fn must(query: Box<dyn Query>) -> Self {
        BooleanClause::new(query, Occur::Must)
    }

    /// Create a SHOULD clause.
    pub fn should(query: Box<dyn Query>) -> Self {
        BooleanClause::new(query, Occur::Should)
    }

    /// Create a MUST_NOT clause.
    pub fn must_not(query: Box<dyn Query>) -> Self {
        BooleanClause::new(query, Occur::MustNot)
    }

    /// Create a FILTER clause (matches like Must but does not affect scoring).
    pub fn filter(query: Box<dyn Query>) -> Self {
        BooleanClause::new(query, Occur::Filter)
    }
}

/// A boolean query that combines multiple queries with boolean logic.
#[derive(Debug)]
pub struct BooleanQuery {
    /// The clauses in this boolean query.
    clauses: Vec<BooleanClause>,
    /// The boost factor for this query.
    boost: f32,
    /// Minimum number of should clauses that must match.
    minimum_should_match: usize,
}

impl BooleanQuery {
    /// Create a new empty boolean query.
    pub fn new() -> Self {
        BooleanQuery {
            clauses: Vec::new(),
            boost: 1.0,
            minimum_should_match: 0,
        }
    }

    /// Add a clause to this boolean query.
    pub fn add_clause(&mut self, clause: BooleanClause) {
        self.clauses.push(clause);
    }

    /// Add a MUST clause.
    pub fn add_must(&mut self, query: Box<dyn Query>) {
        self.add_clause(BooleanClause::must(query));
    }

    /// Add a SHOULD clause.
    pub fn add_should(&mut self, query: Box<dyn Query>) {
        self.add_clause(BooleanClause::should(query));
    }

    /// Add a MUST_NOT clause.
    pub fn add_must_not(&mut self, query: Box<dyn Query>) {
        self.add_clause(BooleanClause::must_not(query));
    }

    /// Add a FILTER clause (matches like Must but does not affect scoring).
    pub fn add_filter(&mut self, query: Box<dyn Query>) {
        self.add_clause(BooleanClause::filter(query));
    }

    /// Set the boost factor.
    pub fn with_boost(mut self, boost: f32) -> Self {
        self.boost = boost;
        self
    }

    /// Set the minimum number of should clauses that must match.
    pub fn with_minimum_should_match(mut self, minimum: usize) -> Self {
        self.minimum_should_match = minimum;
        self
    }

    /// Get the clauses.
    pub fn clauses(&self) -> &[BooleanClause] {
        &self.clauses
    }

    /// Get the minimum should match value.
    pub fn minimum_should_match(&self) -> usize {
        self.minimum_should_match
    }

    /// Check if this query is empty.
    pub fn is_empty(&self) -> bool {
        self.clauses.is_empty()
    }

    /// Get clauses by occurrence type.
    pub fn clauses_by_occur(&self, occur: Occur) -> Vec<&BooleanClause> {
        self.clauses.iter().filter(|c| c.occur == occur).collect()
    }
}

impl Default for BooleanQuery {
    fn default() -> Self {
        Self::new()
    }
}

impl Clone for BooleanQuery {
    fn clone(&self) -> Self {
        BooleanQuery {
            clauses: self
                .clauses
                .iter()
                .map(|c| BooleanClause {
                    query: c.query.clone_box(),
                    occur: c.occur,
                })
                .collect(),
            boost: self.boost,
            minimum_should_match: self.minimum_should_match,
        }
    }
}

impl Query for BooleanQuery {
    fn matcher(&self, reader: &dyn LexicalIndexReader) -> Result<Box<dyn Matcher>> {
        if self.clauses.is_empty() {
            return Ok(Box::new(EmptyMatcher::new()));
        }

        let must_clauses = self.clauses_by_occur(Occur::Must);
        let filter_clauses = self.clauses_by_occur(Occur::Filter);
        let should_clauses = self.clauses_by_occur(Occur::Should);
        let must_not_clauses = self.clauses_by_occur(Occur::MustNot);

        // Combine Must and Filter clauses for matching (Filter behaves like Must)
        let mut required_clauses: Vec<&BooleanClause> = Vec::new();
        required_clauses.extend(&must_clauses);
        required_clauses.extend(&filter_clauses);

        // Handle MUST/FILTER and MUST_NOT clauses
        if !required_clauses.is_empty()
            || (!must_not_clauses.is_empty() && should_clauses.is_empty())
        {
            // Create positive matcher from MUST and FILTER clauses
            let mut positive_matcher = if !required_clauses.is_empty() {
                if required_clauses.len() == 1 {
                    // Single required clause
                    required_clauses[0].query.matcher(reader)?
                } else {
                    // Multiple required clauses - use ConjunctionMatcher
                    let mut matchers = Vec::new();
                    for clause in &required_clauses {
                        let matcher = clause.query.matcher(reader)?;
                        if matcher.is_exhausted() {
                            return Ok(Box::new(EmptyMatcher::new()));
                        }
                        matchers.push(matcher);
                    }
                    Box::new(ConjunctionMatcher::new(matchers))
                }
            } else {
                // No required clauses, but we have MUST_NOT clauses and no SHOULD clauses
                // Match all documents and exclude the ones matching MUST_NOT
                Box::new(AllMatcher::new(reader.max_doc()))
            };

            // If minimum_should_match is set and we have SHOULD clauses, combine them with MUST
            if self.minimum_should_match > 0 && !should_clauses.is_empty() {
                let mut should_matchers = Vec::new();
                for clause in &should_clauses {
                    let matcher = clause.query.matcher(reader)?;
                    if !matcher.is_exhausted() {
                        should_matchers.push(matcher);
                    }
                }

                if !should_matchers.is_empty() {
                    let should_matcher = if should_matchers.len() == 1 {
                        should_matchers.into_iter().next().unwrap()
                    } else {
                        Box::new(DisjunctionMatcher::new(should_matchers))
                    };

                    // Combine MUST and SHOULD with ConjunctionMatcher
                    positive_matcher = Box::new(ConjunctionMatcher::new(vec![
                        positive_matcher,
                        should_matcher,
                    ]));
                } else if !required_clauses.is_empty() {
                    // SHOULD clauses are exhausted but minimum_should_match requires them
                    // This means no documents can match
                    return Ok(Box::new(EmptyMatcher::new()));
                }
            }

            // Handle MUST_NOT clauses
            if !must_not_clauses.is_empty() {
                let mut negative_matchers = Vec::new();
                for clause in &must_not_clauses {
                    let matcher = clause.query.matcher(reader)?;
                    if !matcher.is_exhausted() {
                        negative_matchers.push(matcher);
                    }
                }

                if !negative_matchers.is_empty() {
                    if required_clauses.is_empty() {
                        // Only MUST_NOT clauses - use NotMatcher
                        if negative_matchers.len() == 1 {
                            Ok(Box::new(NotMatcher::new(
                                negative_matchers.into_iter().next().unwrap(),
                                reader.max_doc(),
                            )))
                        } else {
                            // Multiple MUST_NOT clauses - combine them with DisjunctionMatcher
                            let combined_negatives =
                                Box::new(DisjunctionMatcher::new(negative_matchers));
                            Ok(Box::new(NotMatcher::new(
                                combined_negatives,
                                reader.max_doc(),
                            )))
                        }
                    } else {
                        // Both MUST and MUST_NOT clauses - use ConjunctionNotMatcher
                        Ok(Box::new(ConjunctionNotMatcher::new(
                            positive_matcher,
                            negative_matchers,
                        )))
                    }
                } else {
                    // All negative matchers are exhausted, just return positive matcher
                    Ok(positive_matcher)
                }
            } else {
                // No MUST_NOT clauses, just return positive matcher
                Ok(positive_matcher)
            }
        } else if !should_clauses.is_empty() {
            // SHOULD clauses (possibly with MUST_NOT)
            let mut should_matchers = Vec::new();
            for clause in &should_clauses {
                let matcher = clause.query.matcher(reader)?;
                if !matcher.is_exhausted() {
                    should_matchers.push(matcher);
                }
            }

            if should_matchers.is_empty() {
                return Ok(Box::new(EmptyMatcher::new()));
            }

            let positive_matcher = if should_matchers.len() == 1 {
                should_matchers.into_iter().next().unwrap()
            } else {
                Box::new(DisjunctionMatcher::new(should_matchers))
            };

            // Handle MUST_NOT clauses with SHOULD
            if !must_not_clauses.is_empty() {
                let mut negative_matchers = Vec::new();
                for clause in &must_not_clauses {
                    let matcher = clause.query.matcher(reader)?;
                    if !matcher.is_exhausted() {
                        negative_matchers.push(matcher);
                    }
                }

                if !negative_matchers.is_empty() {
                    // Combine SHOULD (positive) with MUST_NOT (negative)
                    Ok(Box::new(ConjunctionNotMatcher::new(
                        positive_matcher,
                        negative_matchers,
                    )))
                } else {
                    Ok(positive_matcher)
                }
            } else {
                Ok(positive_matcher)
            }
        } else {
            Ok(Box::new(EmptyMatcher::new()))
        }
    }

    fn scorer(&self, reader: &dyn LexicalIndexReader) -> Result<Box<dyn Scorer>> {
        use crate::lexical::query::scorer::BooleanScorer;

        let mut sub_queries = Vec::new();

        // Collect queries from MUST and SHOULD clauses
        for clause in &self.clauses {
            if clause.occur == Occur::Must || clause.occur == Occur::Should {
                sub_queries.push(clause.query.clone_box());
            }
        }

        if sub_queries.is_empty() {
            // Fallback for empty boolean query
            let scorer = BM25Scorer::new(
                1,
                1,
                reader.doc_count(),
                10.0,
                reader.doc_count(),
                self.boost,
            );
            return Ok(Box::new(scorer));
        }

        let mut boolean_scorer = BooleanScorer::new(reader, sub_queries)?;
        boolean_scorer.set_boost(self.boost);
        Ok(Box::new(boolean_scorer))
    }

    fn boost(&self) -> f32 {
        self.boost
    }

    fn set_boost(&mut self, boost: f32) {
        self.boost = boost;
    }

    fn description(&self) -> String {
        if self.clauses.is_empty() {
            return "()".to_string();
        }

        let mut parts = Vec::new();

        for clause in &self.clauses {
            let clause_desc = match clause.occur {
                Occur::Must => format!("+{}", clause.query.description()),
                Occur::Should => clause.query.description(),
                Occur::MustNot => format!("-{}", clause.query.description()),
                Occur::Filter => format!("#{}", clause.query.description()),
            };
            parts.push(clause_desc);
        }

        let result = format!("({})", parts.join(" "));

        if self.boost == 1.0 {
            result
        } else {
            format!("{}^{}", result, self.boost)
        }
    }

    fn clone_box(&self) -> Box<dyn Query> {
        Box::new(self.clone())
    }

    fn is_empty(&self, reader: &dyn LexicalIndexReader) -> Result<bool> {
        if self.clauses.is_empty() {
            return Ok(true);
        }

        // Check if any clause can match
        for clause in &self.clauses {
            if !clause.query.is_empty(reader)? {
                return Ok(false);
            }
        }

        Ok(true)
    }

    fn cost(&self, reader: &dyn LexicalIndexReader) -> Result<u64> {
        let mut total_cost = 0;

        for clause in &self.clauses {
            total_cost += clause.query.cost(reader)?;
        }

        Ok(total_cost)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn apply_field_boosts(&mut self, boosts: &std::collections::HashMap<String, f32>) {
        // Apply overall boost if targeted (BooleanQuery doesn't target a field usually, but we check anyway)
        if let Some(f) = self.field()
            && let Some(&b) = boosts.get(f)
        {
            self.set_boost(self.boost() * b);
        }

        // Recursively apply to all clauses
        for clause in &mut self.clauses {
            clause.query.apply_field_boosts(boosts);
        }
    }
}

/// Builder for creating boolean queries.
#[derive(Debug)]
pub struct BooleanQueryBuilder {
    query: BooleanQuery,
}

impl BooleanQueryBuilder {
    /// Create a new boolean query builder.
    pub fn new() -> Self {
        BooleanQueryBuilder {
            query: BooleanQuery::new(),
        }
    }

    /// Add a MUST clause.
    pub fn must(mut self, query: Box<dyn Query>) -> Self {
        self.query.add_must(query);
        self
    }

    /// Add a SHOULD clause.
    pub fn should(mut self, query: Box<dyn Query>) -> Self {
        self.query.add_should(query);
        self
    }

    /// Add a MUST_NOT clause.
    pub fn must_not(mut self, query: Box<dyn Query>) -> Self {
        self.query.add_must_not(query);
        self
    }

    /// Add a FILTER clause (matches like Must but does not affect scoring).
    pub fn filter(mut self, query: Box<dyn Query>) -> Self {
        self.query.add_filter(query);
        self
    }

    /// Set the boost factor.
    pub fn boost(mut self, boost: f32) -> Self {
        self.query = self.query.with_boost(boost);
        self
    }

    /// Set the minimum should match.
    pub fn minimum_should_match(mut self, minimum: usize) -> Self {
        self.query = self.query.with_minimum_should_match(minimum);
        self
    }

    /// Build the boolean query.
    pub fn build(self) -> BooleanQuery {
        self.query
    }
}

impl Default for BooleanQueryBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lexical::index::inverted::reader::{InvertedIndexReader, InvertedIndexReaderConfig};
    use crate::lexical::query::term::TermQuery;

    use crate::storage::memory::MemoryStorage;
    use crate::storage::memory::MemoryStorageConfig;
    use std::sync::Arc;

    #[allow(dead_code)]
    #[test]
    fn test_boolean_query_creation() {
        let query = BooleanQuery::new();

        assert!(query.is_empty());
        assert_eq!(query.clauses().len(), 0);
        assert_eq!(query.boost(), 1.0);
        assert_eq!(query.minimum_should_match(), 0);
    }

    #[test]
    fn test_boolean_query_clauses() {
        let mut query = BooleanQuery::new();

        query.add_must(Box::new(TermQuery::new("title", "hello")));
        query.add_should(Box::new(TermQuery::new("body", "world")));
        query.add_must_not(Box::new(TermQuery::new("title", "spam")));

        assert_eq!(query.clauses().len(), 3);
        assert!(!query.is_empty());

        let must_clauses = query.clauses_by_occur(Occur::Must);
        let should_clauses = query.clauses_by_occur(Occur::Should);
        let must_not_clauses = query.clauses_by_occur(Occur::MustNot);

        assert_eq!(must_clauses.len(), 1);
        assert_eq!(should_clauses.len(), 1);
        assert_eq!(must_not_clauses.len(), 1);
    }

    #[test]
    fn test_boolean_query_builder() {
        let query = BooleanQueryBuilder::new()
            .must(Box::new(TermQuery::new("title", "hello")))
            .should(Box::new(TermQuery::new("body", "world")))
            .must_not(Box::new(TermQuery::new("title", "spam")))
            .boost(2.0)
            .minimum_should_match(1)
            .build();

        assert_eq!(query.clauses().len(), 3);
        assert_eq!(query.boost(), 2.0);
        assert_eq!(query.minimum_should_match(), 1);
    }

    #[test]
    fn test_boolean_query_description() {
        let query = BooleanQueryBuilder::new()
            .must(Box::new(TermQuery::new("title", "hello")))
            .should(Box::new(TermQuery::new("body", "world")))
            .must_not(Box::new(TermQuery::new("title", "spam")))
            .build();

        let desc = query.description();
        assert!(desc.contains("+title:hello"));
        assert!(desc.contains("body:world"));
        assert!(desc.contains("-title:spam"));
    }

    #[test]
    fn test_boolean_query_matcher() {
        let storage = Arc::new(MemoryStorage::new(MemoryStorageConfig::default()));
        let reader =
            InvertedIndexReader::new(vec![], storage, InvertedIndexReaderConfig::default())
                .unwrap();

        let query = BooleanQueryBuilder::new()
            .must(Box::new(TermQuery::new("title", "hello")))
            .build();

        let matcher = query.matcher(&reader).unwrap();
        // Should create a matcher without error
        assert!(matcher.is_exhausted() || matcher.doc_id() != u64::MAX);
    }

    #[test]
    fn test_boolean_query_scorer() {
        let storage = Arc::new(MemoryStorage::new(MemoryStorageConfig::default()));
        let reader =
            InvertedIndexReader::new(vec![], storage, InvertedIndexReaderConfig::default())
                .unwrap();

        let query = BooleanQueryBuilder::new()
            .must(Box::new(TermQuery::new("title", "hello")))
            .build();

        let scorer = query.scorer(&reader).unwrap();
        // Should create a scorer without error
        assert!(scorer.score(0, 1.0, None) >= 0.0);
    }

    #[test]
    fn test_boolean_clause_creation() {
        let query = Box::new(TermQuery::new("title", "hello"));

        let must_clause = BooleanClause::must(query.clone_box());
        assert_eq!(must_clause.occur, Occur::Must);

        let should_clause = BooleanClause::should(query.clone_box());
        assert_eq!(should_clause.occur, Occur::Should);

        let must_not_clause = BooleanClause::must_not(query.clone_box());
        assert_eq!(must_not_clause.occur, Occur::MustNot);
    }

    #[test]
    fn test_empty_boolean_query() {
        let storage = Arc::new(MemoryStorage::new(MemoryStorageConfig::default()));
        let reader =
            InvertedIndexReader::new(vec![], storage, InvertedIndexReaderConfig::default())
                .unwrap();

        let query = BooleanQuery::new();

        assert!(query.is_empty());
        assert_eq!(query.cost(&reader).unwrap(), 0);

        let matcher = query.matcher(&reader).unwrap();
        assert!(matcher.is_exhausted());
    }
}