Skip to main content

hermes_core/query/
boost.rs

1//! Boost query - multiplies the score of the inner query
2
3use std::sync::Arc;
4
5use crate::segment::SegmentReader;
6use crate::{DocId, Score};
7
8use super::{CountFuture, Query, Scorer, ScorerFuture};
9
10/// Boost query - multiplies the score of the inner query
11#[derive(Clone)]
12pub struct BoostQuery {
13    pub inner: Arc<dyn Query>,
14    pub boost: f32,
15}
16
17impl std::fmt::Debug for BoostQuery {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        f.debug_struct("BoostQuery")
20            .field("boost", &self.boost)
21            .finish()
22    }
23}
24
25impl std::fmt::Display for BoostQuery {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        write!(f, "{}^{}", self.inner, self.boost)
28    }
29}
30
31impl BoostQuery {
32    pub fn new(query: impl Query + 'static, boost: f32) -> Self {
33        Self {
34            inner: Arc::new(query),
35            boost,
36        }
37    }
38}
39
40impl Query for BoostQuery {
41    fn scorer<'a>(&self, reader: &'a SegmentReader, limit: usize) -> ScorerFuture<'a> {
42        self.scorer_with_options(reader, limit, super::ScorerOptions::with_positions())
43    }
44
45    fn scorer_with_options<'a>(
46        &self,
47        reader: &'a SegmentReader,
48        limit: usize,
49        options: super::ScorerOptions,
50    ) -> ScorerFuture<'a> {
51        let inner = self.inner.clone();
52        let boost = self.boost;
53        Box::pin(async move {
54            if !boost.is_finite() {
55                return Err(crate::Error::Query(
56                    "boost must be a finite number".to_string(),
57                ));
58            }
59            let inner_scorer = inner.scorer_with_options(reader, limit, options).await?;
60            Ok(Box::new(BoostScorer {
61                inner: inner_scorer,
62                boost,
63            }) as Box<dyn Scorer + 'a>)
64        })
65    }
66
67    #[cfg(feature = "sync")]
68    fn scorer_sync<'a>(
69        &self,
70        reader: &'a SegmentReader,
71        limit: usize,
72    ) -> crate::Result<Box<dyn Scorer + 'a>> {
73        self.scorer_sync_with_options(reader, limit, super::ScorerOptions::with_positions())
74    }
75
76    #[cfg(feature = "sync")]
77    fn scorer_sync_with_options<'a>(
78        &self,
79        reader: &'a SegmentReader,
80        limit: usize,
81        options: super::ScorerOptions,
82    ) -> crate::Result<Box<dyn Scorer + 'a>> {
83        if !self.boost.is_finite() {
84            return Err(crate::Error::Query(
85                "boost must be a finite number".to_string(),
86            ));
87        }
88        let inner_scorer = self
89            .inner
90            .scorer_sync_with_options(reader, limit, options)?;
91        Ok(Box::new(BoostScorer {
92            inner: inner_scorer,
93            boost: self.boost,
94        }) as Box<dyn Scorer + 'a>)
95    }
96
97    fn count_estimate<'a>(&self, reader: &'a SegmentReader) -> CountFuture<'a> {
98        let inner = self.inner.clone();
99        Box::pin(async move { inner.count_estimate(reader).await })
100    }
101
102    fn is_filter(&self) -> bool {
103        self.boost == 1.0 && self.inner.is_filter()
104    }
105
106    fn as_doc_predicate<'a>(&self, reader: &'a SegmentReader) -> Option<super::DocPredicate<'a>> {
107        (self.boost == 1.0)
108            .then(|| self.inner.as_doc_predicate(reader))
109            .flatten()
110    }
111
112    fn decompose(&self) -> super::QueryDecomposition {
113        if self.boost == 1.0 {
114            self.inner.decompose()
115        } else {
116            super::QueryDecomposition::Opaque
117        }
118    }
119}
120
121struct BoostScorer<'a> {
122    inner: Box<dyn Scorer + 'a>,
123    boost: f32,
124}
125
126impl super::docset::DocSet for BoostScorer<'_> {
127    fn doc(&self) -> DocId {
128        self.inner.doc()
129    }
130
131    fn advance(&mut self) -> DocId {
132        self.inner.advance()
133    }
134
135    fn seek(&mut self, target: DocId) -> DocId {
136        self.inner.seek(target)
137    }
138
139    fn size_hint(&self) -> u32 {
140        self.inner.size_hint()
141    }
142}
143
144impl Scorer for BoostScorer<'_> {
145    fn score(&self) -> Score {
146        self.inner.score() * self.boost
147    }
148
149    fn matched_positions(&self) -> Option<super::MatchedPositions> {
150        let mut positions = self.inner.matched_positions()?;
151        for (_, scored_positions) in &mut positions {
152            for position in scored_positions {
153                position.score *= self.boost;
154            }
155        }
156        Some(positions)
157    }
158}