rlucene 0.1.0-alpha.3

A Rust port of Apache Lucene, a full-text search engine library
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
use crate::core::index::index_reader::IndexReader;
use crate::core::index::index_reader_context::{IRCLeafReader, IndexReaderContext};
use crate::core::index::leaf_reader_context::LeafReaderContext;
use crate::core::search::abstract_multi_term_query_constant_score_wrapper::BOOLEAN_REWRITE_TERM_COUNT_THRESHOLD;
use crate::core::search::boolean_clause::Occur;
use crate::core::search::boolean_clause::Occur::{Filter, Must};
use crate::core::search::boolean_query::BooleanQuery;
use crate::core::search::boolean_scorer_supplier::BooleanScorerSupplier;
use crate::core::search::doc_id_set_iterator::DocIdSetIterator;
use crate::core::search::explanation::Explanation;
use crate::core::search::index_searcher::IndexSearcher;
use crate::core::search::matches_utils::from_sub_matches;
use crate::core::search::query::QueryRef;
use crate::core::search::query::{QueryBase, QueryWeight};
use crate::core::search::scorable::Scorable;
use crate::core::search::score_mode::ScoreMode;
use crate::core::search::segment_cacheable::SegmentCacheable;
use crate::core::search::similarities_impl::similarities::Similarity;
use crate::core::search::weight::Weight;
use crate::core::util::error::lucene_error::{LuceneError, Result};
use std::collections::HashMap;

pub struct BooleanWeight<
  IRC: IndexReaderContext + 'static,
  SIM = crate::core::search::similarities_impl::bm25_similarity::BM25Similarity,
> where
  SIM: Similarity,
{
  pub(crate) weighted_clauses: Box<[WeightedBooleanClause<IRC, SIM>]>,
  pub(crate) query: BooleanQuery,
  pub(crate) score_mode: ScoreMode,
}

impl<IRC, SIM> BooleanWeight<IRC, SIM>
where
  SIM: Similarity,
  IRC: IndexReaderContext + 'static,
{
  /// Return the number of matches of required clauses, or -1 if unknown, or numDocs if there are no
  /// required clauses.
  fn req_count(
    &self,
    context: &LeafReaderContext<IRCLeafReader<IRC>>,
    searcher: &IndexSearcher<IRC, SIM>,
  ) -> Result<i32>
  where
    IndexSearcher<IRC, SIM>: Sync,
  {
    let num_docs = context.reader().num_docs()?;
    let mut req_count = num_docs;

    for weighted_clause in &self.weighted_clauses {
      if !self.query.clauses()[weighted_clause.clause_index].is_required() {
        continue;
      }

      let count = weighted_clause.weight.count(context, searcher)?;

      if count == -1 || count == 0 {
        // If the count of one clause is unknown, then the count of the conjunction is unknown
        // too. If one clause doesn't match any docs then the conjunction doesn't match any docs
        // either.
        return Ok(count);
      } else if count == num_docs {
        // the query matches all docs, it can be safely ignored
      } else if req_count == num_docs {
        // all clauses seen so far match all docs, so the count of the new clause is also the
        // count of the conjunction
        req_count = count;
      } else {
        // We have two clauses whose count is in [1, numDocs), we can't figure out the number of
        // docs that match the conjunction without running the query.
        return Ok(-1);
      }
    }

    Ok(req_count)
  }

  /// Return the number of matches of optional clauses, or -1 if unknown, or 0 if there are no
  /// optional clauses.
  fn opt_count(
    &self,
    context: &LeafReaderContext<IRCLeafReader<IRC>>,
    occur: Occur,
    searcher: &IndexSearcher<IRC, SIM>,
  ) -> Result<i32>
  where
    IndexSearcher<IRC, SIM>: Sync,
  {
    let num_docs = context.reader().num_docs()?;
    let mut opt_count = 0i32;
    let mut unknown_count = false;

    for weighted_clause in &self.weighted_clauses {
      if *self.query.clauses()[weighted_clause.clause_index].occur() != occur {
        continue;
      }

      let count = weighted_clause.weight.count(context, searcher)?;

      if count == -1 {
        // If one clause has a number of matches that is unknown, let's be more aggressive to
        // check whether remain clauses could match all docs.
        unknown_count = true;
        continue;
      } else if count == num_docs {
        // If either clause matches all docs, then the disjunction matches all docs.
        return Ok(count);
      } else if count == 0 {
        // We can safely ignore this clause, it doesn't affect the count.
      } else if opt_count == 0 {
        // This is the first clause we see that has a non-zero count, it becomes the count of
        // the disjunction.
        opt_count = count;
      } else {
        // We have two clauses whose count is in [1, numDocs), we can't figure out the number of
        // docs that match the disjunction without running the query.
        unknown_count = true;
      }
    }

    // If at least one of clauses has a number of matches that is unknown and no clause matches all
    // docs, then the number of matches of the disjunction is unknown.
    Ok(if unknown_count { -1 } else { opt_count })
  }
}

impl<IRC, SIM> SegmentCacheable<IRC> for BooleanWeight<IRC, SIM>
where
  SIM: Similarity,
  IRC: IndexReaderContext + 'static,
{
  fn is_cacheable(&self, ctx: &LeafReaderContext<IRCLeafReader<IRC>>) -> Result<bool> {
    // Disallow caching large boolean queries to not encourage users
    // to build large boolean queries as a workaround to the fact that
    // we disallow caching large TermInSetQueries.
    if self.query.clauses().len() > BOOLEAN_REWRITE_TERM_COUNT_THRESHOLD {
      return Ok(false);
    }

    for wc in &self.weighted_clauses {
      if !wc.weight.is_cacheable(ctx)? {
        return Ok(false);
      }
    }

    Ok(true)
  }
}

impl<IRC, SIM> Weight<IRC, SIM> for BooleanWeight<IRC, SIM>
where
  SIM: Similarity,
  IRC: IndexReaderContext + 'static,
{
  fn matches<'a>(
    &'a self,
    context: &'a LeafReaderContext<IRCLeafReader<IRC>>,
    doc: i32,
    searcher: &'a IndexSearcher<IRC, SIM>,
  ) -> Result<Option<crate::core::search::query::QueryWeightMatches<'a, IRC, SIM>>>
  where
    IndexSearcher<IRC, SIM>: Sync,
  {
    let mut matches = Vec::new();
    let mut should_match_count = 0;
    for weighted_clause in &self.weighted_clauses {
      let clause = &self.query.clauses()[weighted_clause.clause_index];
      let clause_matches = weighted_clause.weight.matches(context, doc, searcher)?;
      if clause.is_prohibited() {
        if clause_matches.is_some() {
          return Ok(None);
        }
      } else if clause.is_required() {
        let Some(clause_matches) = clause_matches else {
          return Ok(None);
        };
        matches.push(clause_matches);
      } else if let Some(clause_matches) = clause_matches {
        matches.push(clause_matches);
        should_match_count += 1;
      }
    }
    if should_match_count < self.query.get_minimum_number_should_match() {
      return Ok(None);
    }
    Ok(from_sub_matches(matches))
  }

  fn explain(
    &self,
    context: &LeafReaderContext<IRCLeafReader<IRC>>,
    doc: i32,
    searcher: &IndexSearcher<IRC, SIM>,
  ) -> Result<Explanation>
  where
    IndexSearcher<IRC, SIM>: Sync,
  {
    let min_should_match = self.query.get_minimum_number_should_match();

    let mut subs: Vec<Explanation> = Vec::with_capacity(self.weighted_clauses.len());
    let mut fail = false;
    let mut match_count = 0;
    let mut should_match_count = 0;

    for wc in &self.weighted_clauses {
      let clause = &self.query.clauses()[wc.clause_index];
      let weight = &wc.weight;

      let e = weight.explain(context, doc, searcher)?;

      if e.is_match() {
        if clause.is_scoring() {
          subs.push(e);
        } else if clause.is_required() {
          subs.push(Explanation::match_(
            0.0,
            "match on required clause, product of:",
            vec![
              Explanation::match_(0.0, format!("{} clause", Occur::Filter), vec![]),
              e,
            ],
          ));
        } else if clause.is_prohibited() {
          subs.push(Explanation::no_match(
            format!(
              "match on prohibited clause ({})",
              clause.query.to_string("")?
            ),
            vec![e],
          ));
          fail = true;
        }

        if !clause.is_prohibited() {
          match_count += 1;
        }

        if clause.occur() == &Occur::Should {
          should_match_count += 1;
        }
      } else if clause.is_required() {
        subs.push(Explanation::no_match(
          format!(
            "no match on required clause ({})",
            clause.query.to_string("")?
          ),
          vec![e],
        ));
        fail = true;
      }
    }

    if fail {
      Ok(Explanation::no_match(
        "Failure to meet condition(s) of required/prohibited clause(s)",
        subs,
      ))
    } else if match_count == 0 {
      Ok(Explanation::no_match("No matching clauses", subs))
    } else if should_match_count < min_should_match {
      Ok(Explanation::no_match(
        format!(
          "Failure to match minimum number of optional clauses: {}",
          min_should_match
        ),
        subs,
      ))
    } else {
      // Replicating the same floating-point errors as the scorer does is quite
      // complex (essentially because of how ReqOptSumScorer casts intermediate
      // contributions to the score to floats), so in order to make sure that
      // explanations have the same value as the score, we pull a scorer and
      // use it to compute the score.

      let mut scorer = self
        .scorer(context, searcher)?
        .ok_or_else(|| LuceneError::illegal_state("no scorer available for explanation"))?;

      let advanced = scorer.advance(doc)?;
      debug_assert!(advanced == doc);

      Ok(Explanation::match_(scorer.score()?, "sum of:", subs))
    }
  }

  fn get_query(&self) -> QueryRef<'_> {
    (&self.query).into()
  }

  type ScorerSupplier = BooleanScorerSupplier<IRC, SIM>;

  fn scorer_supplier(
    &self,
    context: &LeafReaderContext<IRCLeafReader<IRC>>,
    searcher: &IndexSearcher<IRC, SIM>,
  ) -> Result<Option<Self::ScorerSupplier>>
  where
    IndexSearcher<IRC, SIM>: Sync,
  {
    let mut min_should_match = self.query.get_minimum_number_should_match();

    let mut must = Vec::new();
    let mut should = Vec::new();
    let mut filter = Vec::new();
    let mut must_not = Vec::new();

    for wc in &self.weighted_clauses {
      let sub_supplier = wc.weight.scorer_supplier(context, searcher)?;
      match sub_supplier {
        None => {
          if self.query.clauses()[wc.clause_index].is_required() {
            return Ok(None);
          }
        },
        Some(sub_scorer) => match self.query.clauses()[wc.clause_index].occur() {
          Occur::Must => must.push(sub_scorer),
          Occur::Should => should.push(sub_scorer),
          Occur::Filter => filter.push(sub_scorer),
          Occur::MustNot => must_not.push(sub_scorer),
        },
      }
    }
    // scorer simplifications:
    if (should.len() as i32) == min_should_match {
      if must.is_empty() {
        must = std::mem::take(&mut should);
      } else {
        must.append(&mut should);
      }
      min_should_match = 0;
    }

    if (filter.is_empty() && must.is_empty() && should.is_empty())
      || (should.len() as i32) < min_should_match
    {
      return Ok(None);
    }

    if !self.score_mode.needs_scores() && min_should_match == 0 && (must.len() + filter.len()) > 0 {
      should.clear();
    }
    let max_doc = context.reader().max_doc()?;
    let mut scores = HashMap::with_capacity(4);
    scores.insert(Occur::Must, must);
    scores.insert(Occur::Should, should);
    scores.insert(Occur::Filter, filter);
    scores.insert(Occur::MustNot, must_not);
    let v = BooleanScorerSupplier::new(scores, self.score_mode, min_should_match, max_doc)?;
    Ok(Some(v))
  }

  fn count(
    &self,
    context: &LeafReaderContext<IRCLeafReader<IRC>>,
    searcher: &IndexSearcher<IRC, SIM>,
  ) -> Result<i32>
  where
    IndexSearcher<IRC, SIM>: Sync,
  {
    let num_docs = context.reader().num_docs()?;

    if self.query.is_pure_disjunction() {
      return self.opt_count(context, Occur::Should, searcher);
    }

    let positive_count = if (!self.query.get_clauses_idx(Filter).is_empty()
      || !self.query.get_clauses_idx(Must).is_empty())
      && self.query.get_minimum_number_should_match() == 0
    {
      self.req_count(context, searcher)?
    } else {
      // The query has a non-zero min-should match. We could handle some cases, e.g.
      // minShouldMatch=N and we can find N SHOULD clauses that match all docs, but are there
      // real-world queries that would benefit from Lucene handling this case?
      -1
    };

    if positive_count == 0 {
      return Ok(0);
    }

    let prohibited_count = self.opt_count(context, Occur::MustNot, searcher)?;

    if prohibited_count == -1 {
      Ok(-1)
    } else if prohibited_count == 0 {
      Ok(positive_count)
    } else if prohibited_count == num_docs {
      Ok(0)
    } else if positive_count == num_docs {
      Ok(num_docs - prohibited_count)
    } else {
      Ok(-1)
    }
  }

  #[cfg(test)]
  fn as_any(&mut self) -> &mut dyn std::any::Any {
    self
  }
}
pub(crate) struct WeightedBooleanClause<
  IRC: IndexReaderContext + 'static,
  SIM = crate::core::search::similarities_impl::bm25_similarity::BM25Similarity,
> where
  SIM: Similarity,
{
  // The immutable parent query owns the clause for the lifetime of this weight.
  pub(crate) clause_index: usize,
  pub(crate) weight: QueryWeight<IRC, SIM>,
}

impl<IRC, SIM> WeightedBooleanClause<IRC, SIM>
where
  SIM: Similarity,
  IRC: IndexReaderContext + 'static,
{
  pub(crate) fn new(clause_index: usize, weight: QueryWeight<IRC, SIM>) -> Self {
    Self {
      clause_index,
      weight,
    }
  }
}