Skip to main content

hermes_core/query/
traits.rs

1//! Query and Scorer traits with async support
2//!
3//! Provides the core abstractions for search queries and document scoring.
4
5use std::future::Future;
6use std::pin::Pin;
7
8use crate::segment::SegmentReader;
9use crate::{DocId, Result, Score};
10
11/// BM25 parameters
12#[derive(Debug, Clone, Copy)]
13pub struct Bm25Params {
14    /// Term frequency saturation parameter (typically 1.2-2.0)
15    pub k1: f32,
16    /// Length normalization parameter (typically 0.75)
17    pub b: f32,
18}
19
20impl Default for Bm25Params {
21    fn default() -> Self {
22        Self { k1: 1.2, b: 0.75 }
23    }
24}
25
26/// Future type for scorer creation
27#[cfg(not(target_arch = "wasm32"))]
28pub type ScorerFuture<'a> = Pin<Box<dyn Future<Output = Result<Box<dyn Scorer + 'a>>> + Send + 'a>>;
29#[cfg(target_arch = "wasm32")]
30pub type ScorerFuture<'a> = Pin<Box<dyn Future<Output = Result<Box<dyn Scorer + 'a>>> + 'a>>;
31
32/// Future type for count estimation
33#[cfg(not(target_arch = "wasm32"))]
34pub type CountFuture<'a> = Pin<Box<dyn Future<Output = Result<u32>> + Send + 'a>>;
35#[cfg(target_arch = "wasm32")]
36pub type CountFuture<'a> = Pin<Box<dyn Future<Output = Result<u32>> + 'a>>;
37
38/// Info for WAND-optimizable term queries
39#[derive(Debug, Clone)]
40pub struct TermQueryInfo {
41    /// Field being searched
42    pub field: crate::dsl::Field,
43    /// Term bytes (lowercase)
44    pub term: Vec<u8>,
45}
46
47/// A search query (async)
48///
49/// Note: `scorer` takes `&self` (not `&'a self`) so that scorers don't borrow the query.
50/// This enables query composition - queries can create sub-queries locally and get their scorers.
51/// Implementations must clone/capture any data they need during scorer creation.
52#[cfg(not(target_arch = "wasm32"))]
53pub trait Query: Send + Sync {
54    /// Create a scorer for this query against a single segment (async)
55    ///
56    /// The `limit` parameter specifies the maximum number of results to return.
57    /// This is passed from the top-level search limit.
58    ///
59    /// Note: The scorer borrows only the reader, not the query. Implementations
60    /// should capture any needed query data (field, terms, etc.) during creation.
61    fn scorer<'a>(&self, reader: &'a SegmentReader, limit: usize) -> ScorerFuture<'a>;
62
63    /// Estimated number of matching documents in a segment (async)
64    fn count_estimate<'a>(&self, reader: &'a SegmentReader) -> CountFuture<'a>;
65
66    /// Return term info if this is a simple term query eligible for WAND optimization
67    ///
68    /// Returns None for complex queries (boolean, phrase, etc.)
69    fn as_term_query_info(&self) -> Option<TermQueryInfo> {
70        None
71    }
72}
73
74/// A search query (async) - WASM version without Send bounds
75#[cfg(target_arch = "wasm32")]
76pub trait Query {
77    /// Create a scorer for this query against a single segment (async)
78    ///
79    /// The `limit` parameter specifies the maximum number of results to return.
80    /// This is passed from the top-level search limit.
81    fn scorer<'a>(&self, reader: &'a SegmentReader, limit: usize) -> ScorerFuture<'a>;
82
83    /// Estimated number of matching documents in a segment (async)
84    fn count_estimate<'a>(&self, reader: &'a SegmentReader) -> CountFuture<'a>;
85
86    /// Return term info if this is a simple term query eligible for WAND optimization
87    fn as_term_query_info(&self) -> Option<TermQueryInfo> {
88        None
89    }
90}
91
92impl Query for Box<dyn Query> {
93    fn scorer<'a>(&self, reader: &'a SegmentReader, limit: usize) -> ScorerFuture<'a> {
94        (**self).scorer(reader, limit)
95    }
96
97    fn count_estimate<'a>(&self, reader: &'a SegmentReader) -> CountFuture<'a> {
98        (**self).count_estimate(reader)
99    }
100
101    fn as_term_query_info(&self) -> Option<TermQueryInfo> {
102        (**self).as_term_query_info()
103    }
104}
105
106/// Matched positions for a field (field_id, list of encoded positions)
107pub type MatchedPositions = Vec<(u32, Vec<u32>)>;
108
109/// Scorer that iterates over matching documents and computes scores
110#[cfg(not(target_arch = "wasm32"))]
111pub trait Scorer: Send {
112    /// Current document ID, or TERMINATED if exhausted
113    fn doc(&self) -> DocId;
114
115    /// Score for current document
116    fn score(&self) -> Score;
117
118    /// Advance to next document
119    fn advance(&mut self) -> DocId;
120
121    /// Seek to first doc >= target
122    fn seek(&mut self, target: DocId) -> DocId;
123
124    /// Size hint for remaining documents
125    fn size_hint(&self) -> u32;
126
127    /// Get matched positions for the current document (if available)
128    /// Returns (field_id, positions) pairs where positions are encoded as per PositionMode
129    fn matched_positions(&self) -> Option<MatchedPositions> {
130        None
131    }
132}
133
134/// Scorer that iterates over matching documents and computes scores (WASM version)
135#[cfg(target_arch = "wasm32")]
136pub trait Scorer {
137    /// Current document ID, or TERMINATED if exhausted
138    fn doc(&self) -> DocId;
139
140    /// Score for current document
141    fn score(&self) -> Score;
142
143    /// Advance to next document
144    fn advance(&mut self) -> DocId;
145
146    /// Seek to first doc >= target
147    fn seek(&mut self, target: DocId) -> DocId;
148
149    /// Size hint for remaining documents
150    fn size_hint(&self) -> u32;
151
152    /// Get matched positions for the current document (if available)
153    fn matched_positions(&self) -> Option<MatchedPositions> {
154        None
155    }
156}
157
158/// Empty scorer for terms that don't exist
159pub struct EmptyScorer;
160
161impl Scorer for EmptyScorer {
162    fn doc(&self) -> DocId {
163        crate::structures::TERMINATED
164    }
165
166    fn score(&self) -> Score {
167        0.0
168    }
169
170    fn advance(&mut self) -> DocId {
171        crate::structures::TERMINATED
172    }
173
174    fn seek(&mut self, _target: DocId) -> DocId {
175        crate::structures::TERMINATED
176    }
177
178    fn size_hint(&self) -> u32 {
179        0
180    }
181}