Blob tique/src/dismax.rs
|
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 |
use tantivy::{
self,
query::{EmptyScorer, Explanation, Query, Scorer, Weight},
DocId, DocSet, Result, Score, Searcher, SegmentReader, SkipResult, TantivyError,
};
/// A Maximum Disjunction query, as popularized by Lucene/Solr
///
/// A DisMax query is one that behaves as the union of its sub-queries and
/// the resulting documents are scored as the best score over each sub-query
/// plus a configurable increment based on additional matches.
///
/// The final score formula is `score = max + (sum - max) * tiebreaker`,
/// so with a tiebreaker of `0.0` you get only the maximum score and if you
/// turn it up to `1.0` the score ends up being the sum of all scores, just
/// like a plain "should" BooleanQuery would.
///
#[derive(Debug)]
pub struct DisMaxQuery {
disjuncts: Vec<Box<dyn Query>>,
tiebreaker: f32,
}
impl DisMaxQuery {
/// Create a union-like query that picks the best score instead of the sum
///
/// Panics if tiebreaker is not within the `[0,1]` range
pub fn new(disjuncts: Vec<Box<dyn Query>>, tiebreaker: f32) -> Self {
assert!((0.0..=1.0).contains(&tiebreaker));
Self {
disjuncts,
tiebreaker,
}
}
}
impl Clone for DisMaxQuery {
fn clone(&self) -> Self {
Self {
disjuncts: self.disjuncts.iter().map(|q| q.box_clone()).collect(),
tiebreaker: self.tiebreaker,
}
}
}
impl Query for DisMaxQuery {
fn weight(&self, searcher: &Searcher, scoring_enabled: bool) -> Result<Box<dyn Weight>> {
Ok(Box::new(DisMaxWeight::new(
self.disjuncts
.iter()
.map(|d| d.weight(searcher, scoring_enabled))
.collect::<Result<Vec<_>>>()?,
self.tiebreaker,
)))
}
}
struct DisMaxWeight {
weights: Vec<Box<dyn Weight>>,
tiebreaker: f32,
}
impl DisMaxWeight {
fn new(weights: Vec<Box<dyn Weight>>, tiebreaker: f32) -> Self {
Self {
weights,
tiebreaker,
}
}
}
impl Weight for DisMaxWeight {
fn scorer(&self, reader: &SegmentReader, boost: f32) -> Result<Box<dyn Scorer>> {
match self.weights.len() {
0 => Ok(Box::new(EmptyScorer)),
1 => self.weights.get(0).unwrap().scorer(reader, boost),
_ => Ok(Box::new(DisMaxScorer::new(
self.weights
.iter()
.map(|w| w.scorer(reader, boost))
.collect::<Result<Vec<_>>>()?,
self.tiebreaker,
))),
}
}
fn explain(&self, reader: &SegmentReader, doc: DocId) -> Result<Explanation> {
let mut scorer = self.scorer(reader, 1.0)?;
if scorer.skip_next(doc) != SkipResult::Reached {
return Err(TantivyError::InvalidArgument("Not a match".to_owned()));
}
let mut explanation = Explanation::new(
format!(
"DisMaxQuery. Score = max + (sum - max) * {}",
self.tiebreaker
),
scorer.score(),
);
for weight in &self.weights {
if let Ok(sub_explanation) = weight.explain(reader, doc) {
explanation.add_detail(sub_explanation);
}
}
Ok(explanation)
}
}
struct DisMaxScorer {
scorers: Vec<Box<dyn Scorer>>,
current: Option<DocId>,
tiebreaker: f32,
}
impl DisMaxScorer {
fn new(scorers: Vec<Box<dyn Scorer>>, tiebreaker: f32) -> Self {
Self {
scorers,
tiebreaker,
current: None,
}
}
}
impl Scorer for DisMaxScorer {
fn score(&mut self) -> Score {
let mut max = 0.0;
let mut sum = 0.0;
debug_assert!(self.current.is_some());
for scorer in &mut self.scorers {
if self.current.map_or(false, |d| scorer.doc() == d) {
let score = scorer.score();
sum += score;
if score > max {
max = score;
}
}
}
max + (sum - max) * self.tiebreaker
}
}
impl DocSet for DisMaxScorer {
fn advance(&mut self) -> bool {
let mut next_target = None;
let mut to_remove = Vec::new();
for (idx, scorer) in self.scorers.iter_mut().enumerate() {
// Advance every scorer that's on target or behind
if self.current.map_or(true, |d| d >= scorer.doc()) && !scorer.advance() {
to_remove.push(idx);
continue;
}
let doc = scorer.doc();
if next_target.map_or(true, |next| doc < next) {
next_target.replace(doc);
}
}
while let Some(idx) = to_remove.pop() {
self.scorers.remove(idx);
}
if let Some(target) = next_target {
self.current.replace(target);
true
} else {
false
}
}
fn doc(&self) -> tantivy::DocId {
debug_assert!(self.current.is_some());
self.current.unwrap_or(0)
}
fn size_hint(&self) -> u32 {
0
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{num::Wrapping, ops::Range};
use tantivy::{
doc,
query::TermQuery,
schema::{IndexRecordOption, SchemaBuilder, TEXT},
DocAddress, Index, Term,
};
// XXX ConstScorer::from(VecDocSet::from(...)), but I can't seem
// import tantivy::query::VecDocSet here??
struct VecScorer {
doc_ids: Vec<DocId>,
cursor: Wrapping<usize>,
}
impl Scorer for VecScorer {
fn score(&mut self) -> Score {
1.0
}
}
impl DocSet for VecScorer {
fn advance(&mut self) -> bool {
self.cursor += Wrapping(1);
self.doc_ids.len() > self.cursor.0
}
fn doc(&self) -> DocId {
self.doc_ids[self.cursor.0]
}
fn size_hint(&self) -> u32 {
self.doc_ids.len() as u32
}
}
fn test_scorer(range: Range<DocId>) -> Box<dyn Scorer> {
Box::new(VecScorer {
doc_ids: range.collect(),
cursor: Wrapping(usize::max_value()),
})
}
#[test]
fn scorer_advances_as_union() {
let scorers = vec![
test_scorer(0..10),
test_scorer(5..20),
test_scorer(9..30),
test_scorer(42..43),
test_scorer(13..13), // empty docset
];
let mut dismax = DisMaxScorer::new(scorers, 0.0);
for i in 0..30 {
assert!(dismax.advance(), "failed advance at i={}", i);
assert_eq!(i, dismax.doc());
}
assert!(dismax.advance());
assert_eq!(42, dismax.doc());
assert!(!dismax.advance(), "scorer should have ended by now");
}
#[test]
#[allow(clippy::float_cmp)]
fn tiebreaker() {
let scorers = vec![test_scorer(4..5), test_scorer(4..6), test_scorer(4..7)];
// So now the score is the sum of scores for
// every matching scorer (VecScorer always yields 1)
let mut dismax = DisMaxScorer::new(scorers, 1.0);
assert!(dismax.advance());
assert_eq!(3.0, dismax.score());
assert!(dismax.advance());
assert_eq!(2.0, dismax.score());
assert!(dismax.advance());
assert_eq!(1.0, dismax.score());
assert!(!dismax.advance(), "scorer should have ended by now");
let scorers = vec![test_scorer(7..8), test_scorer(7..8)];
// With a tiebreaker 0, it actually uses
// the maximum disjunction
let mut dismax = DisMaxScorer::new(scorers, 0.0);
assert!(dismax.advance());
// So now, even though doc=7 occurs twice, the score is 1
assert_eq!(1.0, dismax.score());
assert!(!dismax.advance(), "scorer should have ended by now");
}
#[test]
fn explaination() -> Result<()> {
let mut builder = SchemaBuilder::new();
let field = builder.add_text_field("field", TEXT);
let index = Index::create_in_ram(builder.build());
let mut writer = index.writer_with_num_threads(1, 3_000_000)?;
writer.add_document(doc!(field => "foo"));
writer.add_document(doc!(field => "bar"));
writer.add_document(doc!(field => "foo bar"));
writer.add_document(doc!(field => "baz"));
writer.commit()?;
let foo_query = TermQuery::new(
Term::from_field_text(field, "foo"),
IndexRecordOption::Basic,
);
let bar_query = TermQuery::new(
Term::from_field_text(field, "bar"),
IndexRecordOption::Basic,
);
let reader = index.reader()?;
let searcher = reader.searcher();
let dismax = DisMaxQuery::new(vec![Box::new(foo_query), Box::new(bar_query)], 0.0);
let baz_doc = DocAddress(0, 3);
assert!(
dismax.explain(&searcher, baz_doc).is_err(),
"Shouldn't be able to explain a non-matching doc"
);
// Ensure every other doc can be explained
for doc_id in 0..3 {
let explanation = dismax.explain(&searcher, DocAddress(0, doc_id))?;
assert!(explanation.to_pretty_json().contains("DisMaxQuery"));
}
Ok(())
}
}
|