Skip to main content

hermes_core/query/
term.rs

1//! Term query - matches documents containing a specific term
2
3use std::sync::Arc;
4
5use crate::dsl::Field;
6use crate::segment::SegmentReader;
7use crate::structures::BlockPostingList;
8use crate::structures::TERMINATED;
9use crate::{DocId, Score};
10
11use super::{CountFuture, EmptyScorer, GlobalStats, Query, Scorer, ScorerFuture, TermQueryInfo};
12
13/// Term query - matches documents containing a specific term
14#[derive(Clone)]
15pub struct TermQuery {
16    pub field: Field,
17    pub term: Vec<u8>,
18    /// Optional global statistics for cross-segment IDF
19    global_stats: Option<Arc<GlobalStats>>,
20}
21
22impl std::fmt::Debug for TermQuery {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        f.debug_struct("TermQuery")
25            .field("field", &self.field)
26            .field("term", &String::from_utf8_lossy(&self.term))
27            .field("has_global_stats", &self.global_stats.is_some())
28            .finish()
29    }
30}
31
32impl std::fmt::Display for TermQuery {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        write!(
35            f,
36            "Term({}:\"{}\")",
37            self.field.0,
38            String::from_utf8_lossy(&self.term)
39        )
40    }
41}
42
43impl TermQuery {
44    pub fn new(field: Field, term: impl Into<Vec<u8>>) -> Self {
45        Self {
46            field,
47            term: term.into(),
48            global_stats: None,
49        }
50    }
51
52    pub fn text(field: Field, text: &str) -> Self {
53        Self {
54            field,
55            term: text.to_lowercase().into_bytes(),
56            global_stats: None,
57        }
58    }
59
60    /// Create with global statistics for cross-segment IDF
61    pub fn with_global_stats(field: Field, text: &str, stats: Arc<GlobalStats>) -> Self {
62        Self {
63            field,
64            term: text.to_lowercase().into_bytes(),
65            global_stats: Some(stats),
66        }
67    }
68
69    /// Set global statistics for cross-segment IDF
70    pub fn set_global_stats(&mut self, stats: Arc<GlobalStats>) {
71        self.global_stats = Some(stats);
72    }
73}
74
75/// Compute (idf, avg_field_len) from a posting list, using global stats when available.
76fn compute_term_idf(
77    posting_list: &BlockPostingList,
78    field: Field,
79    reader: &SegmentReader,
80    global_stats: Option<&Arc<GlobalStats>>,
81    term: &[u8],
82) -> (f32, f32) {
83    if let Some(stats) = global_stats {
84        let term_str = String::from_utf8_lossy(term);
85        let global_idf = stats.text_idf(field, &term_str);
86        if global_idf > 0.0 {
87            return (global_idf, stats.avg_field_len(field));
88        }
89    }
90    let num_docs = reader.num_docs() as f32;
91    let doc_freq = posting_list.doc_count() as f32;
92    (
93        super::bm25_idf(doc_freq, num_docs),
94        reader.avg_field_len(field),
95    )
96}
97
98// ── Unified term scorer macro ────────────────────────────────────────────
99//
100// Parameterised on:
101//   $get_postings_fn – get_postings | get_postings_sync
102//   $get_positions_fn – get_positions | get_positions_sync
103//   $($aw)*          – .await  (present for async, absent for sync)
104macro_rules! term_plan {
105    ($field:expr, $term:expr, $global_stats:expr, $reader:expr,
106     $load_positions:expr, $get_postings_fn:ident, $get_positions_fn:ident
107     $(, $aw:tt)*) => {{
108        let field: Field = $field;
109        let term: &[u8] = $term;
110        let global_stats: Option<&Arc<GlobalStats>> = $global_stats;
111        let reader: &SegmentReader = $reader;
112
113        // Non-indexed fields → fast-field-only path
114        let is_indexed = reader.schema().get_field_entry(field).is_none_or(|e| e.indexed);
115        if !is_indexed {
116            let term_str = String::from_utf8_lossy(term);
117            if let Some(scorer) = FastFieldTextScorer::try_new(reader, field, &term_str) {
118                return Ok(Box::new(scorer) as Box<dyn Scorer + '_>);
119            }
120            return Ok(Box::new(EmptyScorer) as Box<dyn Scorer + '_>);
121        }
122
123        let postings = reader.$get_postings_fn(field, term) $(. $aw)* ?;
124
125        match postings {
126            Some(posting_list) => {
127                let (idf, avg_field_len) =
128                    compute_term_idf(&posting_list, field, reader, global_stats, term);
129
130                let positions = if $load_positions {
131                    reader.$get_positions_fn(field, term) $(. $aw)* ?
132                } else {
133                    None
134                };
135
136                let mut scorer = TermScorer::new(posting_list, idf, avg_field_len, 1.0);
137                if let Some(pos) = positions {
138                    scorer = scorer.with_positions(field.0, pos);
139                }
140                Ok(Box::new(scorer) as Box<dyn Scorer + '_>)
141            }
142            None => {
143                let term_str = String::from_utf8_lossy(term);
144                if let Some(scorer) = FastFieldTextScorer::try_new(reader, field, &term_str) {
145                    Ok(Box::new(scorer) as Box<dyn Scorer + '_>)
146                } else {
147                    Ok(Box::new(EmptyScorer) as Box<dyn Scorer + '_>)
148                }
149            }
150        }
151    }};
152}
153
154impl Query for TermQuery {
155    fn scorer<'a>(&self, reader: &'a SegmentReader, limit: usize) -> ScorerFuture<'a> {
156        self.scorer_with_options(reader, limit, super::ScorerOptions::with_positions())
157    }
158
159    fn scorer_with_options<'a>(
160        &self,
161        reader: &'a SegmentReader,
162        _limit: usize,
163        options: super::ScorerOptions,
164    ) -> ScorerFuture<'a> {
165        let field = self.field;
166        let term = self.term.clone();
167        let global_stats = self.global_stats.clone();
168        let load_positions = options.collect_positions;
169        Box::pin(async move {
170            term_plan!(
171                field,
172                &term,
173                global_stats.as_ref(),
174                reader,
175                load_positions,
176                get_postings,
177                get_positions,
178                await
179            )
180        })
181    }
182
183    fn count_estimate<'a>(&self, reader: &'a SegmentReader) -> CountFuture<'a> {
184        let field = self.field;
185        let term = self.term.clone();
186        Box::pin(async move {
187            match reader.get_postings(field, &term).await? {
188                Some(list) => Ok(list.doc_count()),
189                None => Ok(0),
190            }
191        })
192    }
193
194    #[cfg(feature = "sync")]
195    fn scorer_sync<'a>(
196        &self,
197        reader: &'a SegmentReader,
198        limit: usize,
199    ) -> crate::Result<Box<dyn Scorer + 'a>> {
200        self.scorer_sync_with_options(reader, limit, super::ScorerOptions::with_positions())
201    }
202
203    #[cfg(feature = "sync")]
204    fn scorer_sync_with_options<'a>(
205        &self,
206        reader: &'a SegmentReader,
207        _limit: usize,
208        options: super::ScorerOptions,
209    ) -> crate::Result<Box<dyn Scorer + 'a>> {
210        term_plan!(
211            self.field,
212            &self.term,
213            self.global_stats.as_ref(),
214            reader,
215            options.collect_positions,
216            get_postings_sync,
217            get_positions_sync
218        )
219    }
220
221    fn as_doc_predicate<'a>(&self, reader: &'a SegmentReader) -> Option<super::DocPredicate<'a>> {
222        let fast_field = reader.fast_field(self.field.0)?;
223        let term_str = String::from_utf8_lossy(&self.term);
224        match fast_field.text_ordinal(&term_str) {
225            Some(target_ordinal) => Some(Box::new(move |doc_id: DocId| -> bool {
226                fast_field.get_u64(doc_id) == target_ordinal
227            })),
228            // Term doesn't exist in this segment — no doc can match.
229            None => Some(Box::new(|_| false)),
230        }
231    }
232
233    #[cfg(feature = "sync")]
234    fn bitset_cardinality_estimate(&self, reader: &SegmentReader) -> Option<u64> {
235        // Exact: the posting list header carries the doc count.
236        let pl = reader.get_postings_sync(self.field, &self.term).ok()??;
237        Some(pl.doc_count() as u64)
238    }
239
240    #[cfg(feature = "sync")]
241    fn as_doc_bitset(&self, reader: &SegmentReader) -> Option<super::DocBitset> {
242        // Build bitset from posting list: O(M) where M = matching doc count.
243        // Much faster than O(N) fast-field scan for selective terms.
244        let pl = reader.get_postings_sync(self.field, &self.term).ok()??;
245        let mut bitset = super::DocBitset::new(reader.num_docs());
246        let mut iter = pl.iterator();
247        loop {
248            let doc = iter.doc();
249            if doc == crate::structures::TERMINATED {
250                break;
251            }
252            bitset.set(doc);
253            iter.advance();
254        }
255        Some(bitset)
256    }
257
258    fn decompose(&self) -> super::QueryDecomposition {
259        super::QueryDecomposition::TextTerm(TermQueryInfo {
260            field: self.field,
261            term: self.term.clone(),
262        })
263    }
264}
265
266struct TermScorer {
267    iterator: crate::structures::BlockPostingIterator<'static>,
268    idf: f32,
269    /// Average field length for this field
270    avg_field_len: f32,
271    /// Field boost/weight for BM25F
272    field_boost: f32,
273    /// Field ID for position reporting
274    field_id: u32,
275    /// Position posting list (if positions are enabled)
276    positions: Option<crate::structures::PositionPostingList>,
277}
278
279impl TermScorer {
280    pub fn new(
281        posting_list: BlockPostingList,
282        idf: f32,
283        avg_field_len: f32,
284        field_boost: f32,
285    ) -> Self {
286        Self {
287            iterator: posting_list.into_iterator(),
288            idf,
289            avg_field_len,
290            field_boost,
291            field_id: 0,
292            positions: None,
293        }
294    }
295
296    pub fn with_positions(
297        mut self,
298        field_id: u32,
299        positions: crate::structures::PositionPostingList,
300    ) -> Self {
301        self.field_id = field_id;
302        self.positions = Some(positions);
303        self
304    }
305}
306
307impl super::docset::DocSet for TermScorer {
308    fn doc(&self) -> DocId {
309        self.iterator.doc()
310    }
311
312    fn advance(&mut self) -> DocId {
313        self.iterator.advance()
314    }
315
316    fn seek(&mut self, target: DocId) -> DocId {
317        self.iterator.seek(target)
318    }
319
320    fn size_hint(&self) -> u32 {
321        0
322    }
323}
324
325// ── Fast field text equality scorer ──────────────────────────────────────
326
327/// Scorer that scans a text fast field for exact string equality.
328/// Used as fallback when a TermQuery targets a fast-only text field (no inverted index).
329/// Returns score 1.0 for matching docs (filter-style, like RangeScorer).
330struct FastFieldTextScorer<'a> {
331    fast_field: &'a crate::structures::fast_field::FastFieldReader,
332    target_ordinal: u64,
333    current: u32,
334    num_docs: u32,
335}
336
337impl<'a> FastFieldTextScorer<'a> {
338    fn try_new(reader: &'a SegmentReader, field: Field, text: &str) -> Option<Self> {
339        let fast_field = reader.fast_field(field.0)?;
340        let target_ordinal = fast_field.text_ordinal(text)?;
341        let num_docs = reader.num_docs();
342        let mut scorer = Self {
343            fast_field,
344            target_ordinal,
345            current: 0,
346            num_docs,
347        };
348        // Position on first matching doc
349        if num_docs > 0 && fast_field.get_u64(0) != target_ordinal {
350            scorer.scan_forward();
351        }
352        Some(scorer)
353    }
354
355    fn scan_forward(&mut self) {
356        loop {
357            self.current += 1;
358            if self.current >= self.num_docs {
359                self.current = self.num_docs;
360                return;
361            }
362            if self.fast_field.get_u64(self.current) == self.target_ordinal {
363                return;
364            }
365        }
366    }
367}
368
369impl super::docset::DocSet for FastFieldTextScorer<'_> {
370    fn doc(&self) -> DocId {
371        if self.current >= self.num_docs {
372            TERMINATED
373        } else {
374            self.current
375        }
376    }
377
378    fn advance(&mut self) -> DocId {
379        self.scan_forward();
380        self.doc()
381    }
382
383    fn seek(&mut self, target: DocId) -> DocId {
384        if target > self.current {
385            self.current = target;
386            if self.current < self.num_docs
387                && self.fast_field.get_u64(self.current) != self.target_ordinal
388            {
389                self.scan_forward();
390            }
391        }
392        self.doc()
393    }
394
395    fn size_hint(&self) -> u32 {
396        0
397    }
398}
399
400impl Scorer for FastFieldTextScorer<'_> {
401    fn score(&self) -> Score {
402        1.0
403    }
404}
405
406impl Scorer for TermScorer {
407    fn score(&self) -> Score {
408        let tf = self.iterator.term_freq() as f32;
409        // Note: Using tf as doc_len proxy since we don't store per-doc field lengths.
410        // This is a common approximation - longer docs tend to have higher TF.
411        super::bm25f_score(tf, self.idf, tf, self.avg_field_len, self.field_boost)
412    }
413
414    fn matched_positions(&self) -> Option<super::MatchedPositions> {
415        let positions = self.positions.as_ref()?;
416        let doc_id = self.iterator.doc();
417        let pos = positions.get_positions(doc_id)?;
418        let score = self.score();
419        // Each position contributes equally to the term score
420        let per_position_score = if pos.is_empty() {
421            0.0
422        } else {
423            score / pos.len() as f32
424        };
425        let scored_positions: Vec<super::ScoredPosition> = pos
426            .iter()
427            .map(|&p| super::ScoredPosition::new(p, per_position_score))
428            .collect();
429        Some(vec![(self.field_id, scored_positions)])
430    }
431}