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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*
 * 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::search::field_comparator::{FieldComparator, FieldComparatorEnum};
use crate::core::search::field_value_hit_queue::TopFieldScoreDoc;
use crate::core::search::pruning::Pruning;
use crate::core::search::score_doc::ScoreDocLike;
use crate::core::search::sort::Sort;
use crate::core::search::sort_field::SortFiledBase;
use crate::core::search::top_field_docs::TopFieldDocs;
use crate::core::search::total_hits::{Relation, TotalHits};
use crate::core::util::error::lucene_error::{LuceneError, Result};
use crate::core::util::priority_queue::{Compare, PriorityQueue};
use crate::core::util::{Comparator, ToInt};
use std::borrow::Borrow;
use std::marker::PhantomData;

/// Represents hits returned.
#[derive(Clone)]
pub struct TopDocs<S> {
  /// The total number of hits for the query.
  pub total_hits: TotalHits,

  /// The top hits for the query.
  pub score_docs: Vec<S>,
}
impl<S> TopDocs<S> {
  /// Constructs a new [`TopDocs`].
  pub fn new<I>(total_hits: TotalHits, score_docs: I) -> Self
  where
    I: IntoIterator<Item = S>,
  {
    let score_docs = score_docs.into_iter().collect::<Vec<S>>();
    Self {
      total_hits,
      score_docs,
    }
  }
}

/// Returns a new [`TopFieldDocs`], containing topN results across the provided [`TopFieldDocs`],
/// sorting by the specified [`Sort`]. Each of the [`TopDocs`] must have been sorted by the same
/// [`Sort`], and sort field values must have been filled.
///
/// See also: [`merge_top_field_docs_with_start(Sort, int, int, TopFieldDocs[])`](merge_top_field_docs_with_start)
///
/// lucene.experimental
pub fn merge_top_field_docs<I>(
  sort: &Sort,
  top_n: usize,
  // The reason the type of shard_hits is Vec<TopDocs<TopFieldScoreDoc>> instead of Vec<TopFieldDocs>
  // is that the field property inside TopFieldDocs is currently unused.
  shard_hits: I,
) -> Result<TopFieldDocs>
where
  I: IntoIterator,
  I::Item: Borrow<TopDocs<TopFieldScoreDoc>>,
{
  merge_top_field_docs_with_start(sort, 0, top_n, shard_hits)
}
/// Same as [`merge_top_field_docs(Sort, int, TopFieldDocs[])`](merge_top_field_docs) but also ignores the top `start` top docs.
/// This is typically useful for pagination.
///
/// docIDs are expected to be in consistent pattern, i.e. either all [`ScoreDoc`](crate::core::search::score_doc::ScoreDoc)s
/// have their `shardIndex` set, or all have them as `-1` (signifying that all hits
/// belong to the same searcher).
pub fn merge_top_field_docs_with_start<I>(
  sort: &Sort,
  start: usize,
  top_n: usize,
  shard_hits: I,
) -> Result<TopFieldDocs>
where
  I: IntoIterator,
  I::Item: Borrow<TopDocs<TopFieldScoreDoc>>,
{
  merge_top_field_docs_with_comparator(sort, start, top_n, shard_hits, DefaultTieBreaker::default())
}
/// Pass in a custom tie breaker for ordering results
pub fn merge_top_field_docs_with_comparator<C, I>(
  sort: &Sort,
  start: usize,
  size: usize,
  shard_hits: I,
  tie_breaker: C,
) -> Result<TopFieldDocs>
where
  C: Comparator<TopFieldScoreDoc>,
  I: IntoIterator,
  I::Item: Borrow<TopDocs<TopFieldScoreDoc>>,
{
  let shard_hits = shard_hits.into_iter().collect::<Vec<I::Item>>();
  let len = shard_hits.len();
  let cmp = MergeSortQueueCmp::new(sort, &shard_hits, tie_breaker)?;
  let queue = PriorityQueue::new(len, &cmp)?;
  let (total_hits, hits) = merge_aux(queue, start, size, &shard_hits)?;
  Ok(TopFieldDocs::new(total_hits, hits, sort.fields.clone()))
}
/// Returns a new [`TopDocs`], containing topN results across the provided [`TopDocs`],
/// sorting by score. Each [`TopDocs`] instance must be sorted.
///
/// See also: [`merge_top_docs_with_start`].
pub fn merge_top_docs<S, I>(top_n: usize, shard_hits: I) -> Result<TopDocs<S>>
where
  S: ScoreDocLike,
  I: IntoIterator,
  I::Item: Borrow<TopDocs<S>>,
{
  merge_top_docs_with_start(0, top_n, shard_hits)
}
/// Same as [`merge_top_docs`] but also ignores the first `start` top docs.
/// This is typically useful for pagination.
///
/// docIDs are expected to be in consistent pattern, i.e. either all [`ScoreDoc`](crate::core::search::score_doc::ScoreDoc)s
/// have their `shardIndex` set, or all have them as `-1` (signifying that all hits
/// belong to the same searcher).
pub fn merge_top_docs_with_start<S, I>(
  start: usize,
  top_n: usize,
  shard_hits: I,
) -> Result<TopDocs<S>>
where
  S: ScoreDocLike,
  I: IntoIterator,
  I::Item: Borrow<TopDocs<S>>,
{
  merge_top_docs_with_comparator(start, top_n, shard_hits, DefaultTieBreaker::default())
}
/// Same as above, but accepts the passed in tie breaker.
///
/// docIDs are expected to be in consistent pattern, i.e. either all [`ScoreDoc`](crate::core::search::score_doc::ScoreDoc)s
/// have their `shardIndex` set, or all have them as `-1` (signifying that all hits
/// belong to the same searcher).
pub fn merge_top_docs_with_comparator<C, S, I>(
  start: usize,
  size: usize,
  shard_hits: I,
  tie_breaker: C,
) -> Result<TopDocs<S>>
where
  C: Comparator<S>,
  S: ScoreDocLike,
  I: IntoIterator,
  I::Item: Borrow<TopDocs<S>>,
{
  let shard_hits = shard_hits.into_iter().collect::<Vec<I::Item>>();
  let len = shard_hits.len();
  debug_assert!(len <= i32::MAX as usize);
  let cmp = ScoreMergeSortQueueCmp::<_, S, _>::new(&shard_hits, tie_breaker);
  let queue = PriorityQueue::new(len, &cmp)?;
  let (total_hits, hits) = merge_aux(queue, start, size, &shard_hits)?;
  Ok(TopDocs::new(total_hits, hits))
}

/// Internal comparator with shardIndex
#[derive(Default)]
struct ShardIndexTieBreaker;
impl<S> Comparator<S> for ShardIndexTieBreaker
where
  S: ScoreDocLike,
{
  const TYPE: &'static str = "ShardIndexTieBreaker";

  fn compare(&self, a: &S, b: &S) -> Result<i32> {
    Ok(a.shard_index().cmp(&b.shard_index()).to_int())
  }
}
/// Internal comparator with docID
#[derive(Default)]
struct DocIdTieBreaker;
impl<S> Comparator<S> for DocIdTieBreaker
where
  S: ScoreDocLike,
{
  const TYPE: &'static str = "DocIdTieBreaker";

  fn compare(&self, a: &S, b: &S) -> Result<i32> {
    Ok(a.doc().cmp(&b.doc()).to_int())
  }
}

/// Default comparator
#[derive(Default)]
struct DefaultTieBreaker {
  shard_cmp: ShardIndexTieBreaker,
  doc_cmp: DocIdTieBreaker,
}

impl<S> Comparator<S> for DefaultTieBreaker
where
  S: ScoreDocLike,
{
  const TYPE: &'static str = "DefaultTieBreaker";

  fn compare(&self, a: &S, b: &S) -> Result<i32> {
    let res = self.shard_cmp.compare(a, b)?;
    if res != 0 {
      Ok(res)
    } else {
      self.doc_cmp.compare(a, b)
    }
  }
}
#[derive(Debug, Clone, Default)]
pub(crate) struct ShardRef {
  /// Which shard (index into shardHits[]).
  pub(crate) shard_index: usize,

  /// Which hit within the shard.
  pub(crate) hit_index: usize,
}

impl ShardRef {
  pub fn new(shard_index: usize) -> Self {
    ShardRef {
      shard_index,
      hit_index: 0,
    }
  }
}

impl std::fmt::Display for ShardRef {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(
      f,
      "ShardRef(shardIndex={} hitIndex={})",
      self.shard_index, self.hit_index
    )
  }
}
/// Use the tie breaker if provided.
/// If the tie breaker returns `0`, signifying equal values,
/// we use hit indices to tie break intra-shard ties.
pub(crate) fn tie_break_less_than<C, S>(
  first: &ShardRef,
  first_doc: &S,
  second: &ShardRef,
  second_doc: &S,
  tie_breaker: &C,
) -> Result<bool>
where
  C: Comparator<S>,
  S: ScoreDocLike,
{
  let value = tie_breaker.compare(first_doc, second_doc)?;

  if value == 0 {
    // Equal Values
    // Tie break in same shard: resolve however the
    // shard had resolved it:
    debug_assert!(first.hit_index != second.hit_index);
    return Ok(first.hit_index < second.hit_index);
  }

  Ok(value < 0)
}
/// Auxiliary method used by the `merge` implementations.
/// A sort value of `None` indicates that documents should be sorted by score.
fn merge_aux<C, S, B>(
  mut queue: PriorityQueue<ShardRef, C>,
  start: usize,
  size: usize,
  shard_hits: &[B],
) -> Result<(TotalHits, Vec<S>)>
where
  C: Compare<ShardRef>,
  S: ScoreDocLike,
  B: Borrow<TopDocs<S>>,
{
  let mut total_hit_count: i64 = 0;
  let mut total_hits_relation = Relation::EqualTo;
  let mut avail_hit_count = 0;

  for (shard_idx, shard) in shard_hits.iter().enumerate() {
    let shard = shard.borrow();
    total_hit_count = total_hit_count.wrapping_add(shard.total_hits.value as i64);
    if shard.total_hits.relation == Relation::GreaterThanOrEqualTo {
      total_hits_relation = Relation::GreaterThanOrEqualTo;
    }
    if !shard.score_docs.is_empty() {
      avail_hit_count += shard.score_docs.len();
      queue.add(ShardRef::new(shard_idx))?;
    }
  }

  let mut hits: Vec<S>;
  let mut unset_shard_index = false;
  if avail_hit_count <= start {
    hits = Vec::new();
  } else {
    let len = std::cmp::min(size, avail_hit_count - start);
    hits = vec![S::default(); len];

    let requested_result_window = start + size;
    let num_iter_on_hits = std::cmp::min(avail_hit_count, requested_result_window);
    let mut hit_upto = 0;

    while hit_upto < num_iter_on_hits {
      debug_assert!(queue.size() > 0);
      let ref_ = match queue.top_mut() {
        None => return Err(LuceneError::illegal_state("queue is empty")),
        Some(v) => v,
      };

      let shard = shard_hits[ref_.shard_index].borrow();
      let hit = &shard.score_docs[ref_.hit_index];
      ref_.hit_index += 1;

      // Irrespective of whether we use shard indices for tie breaking or not, we check for
      // consistent
      // order in shard indices to defend against potential bugs
      if hit_upto > 0 && unset_shard_index != (hit.shard_index() == -1) {
        return Err(LuceneError::illegal_argument(
          "Inconsistent order of shard indices",
        ));
      }
      unset_shard_index |= hit.shard_index() == -1;

      if hit_upto >= start {
        hits[hit_upto - start] = hit.clone();
      }

      hit_upto += 1;

      if ref_.hit_index < shard.score_docs.len() {
        queue.update_top()?;
      } else {
        queue.pop_unchecked()?;
      }
    }
  }
  if total_hit_count < 0 {
    return Err(LuceneError::illegal_argument(format!(
      "value must be >= 0, got {total_hit_count}"
    )));
  }
  Ok((
    TotalHits::new(total_hit_count as usize, total_hits_relation),
    hits,
  ))
}

pub(crate) struct ScoreMergeSortQueueCmp<'a, C, S, B = TopDocs<S>> {
  shard_hits: &'a [B],
  score_doc: PhantomData<fn() -> S>,
  tie_breaker_comparator: C,
}
impl<'a, C, S, B> ScoreMergeSortQueueCmp<'a, C, S, B> {
  pub fn new(shard_hits: &'a [B], tie_breaker_comparator: C) -> Self {
    Self {
      shard_hits,
      score_doc: PhantomData,
      tie_breaker_comparator,
    }
  }
}

impl<C, S, B> Compare<ShardRef> for ScoreMergeSortQueueCmp<'_, C, S, B>
where
  C: Comparator<S>,
  S: ScoreDocLike,
  B: Borrow<TopDocs<S>>,
{
  fn less_than(&self, first: &ShardRef, second: &ShardRef) -> Result<bool> {
    let first_shard_hits = self.shard_hits[first.shard_index].borrow();
    let second_shard_hits = self.shard_hits[second.shard_index].borrow();

    let first_scorer_doc = &first_shard_hits.score_docs[first.hit_index];
    let second_scorer_doc = &second_shard_hits.score_docs[second.hit_index];
    let first_scorer_doc_score = first_scorer_doc.score();
    let second_scorer_doc_score = second_scorer_doc.score();
    if first_scorer_doc_score < second_scorer_doc_score {
      Ok(false)
    } else if first_scorer_doc_score > second_scorer_doc_score {
      Ok(true)
    } else {
      tie_break_less_than(
        first,
        first_scorer_doc,
        second,
        second_scorer_doc,
        &self.tie_breaker_comparator,
      )
    }
  }
}

pub(crate) struct MergeSortQueueCmp<'a, C, B = TopDocs<TopFieldScoreDoc>> {
  shard_hits: &'a [B],
  comparators: Vec<FieldComparatorEnum>,
  reverse_mul: Vec<i8>,
  tie_breaker: C,
}

impl<'a, C, B> MergeSortQueueCmp<'a, C, B>
where
  B: Borrow<TopDocs<TopFieldScoreDoc>>,
{
  pub fn new(sort: &Sort, shard_hits: &'a [B], tie_breaker: C) -> Result<Self> {
    for (shard_index, shard) in shard_hits.iter().enumerate() {
      let shard = shard.borrow();
      for score_doc in &shard.score_docs {
        if score_doc.as_field().is_none() {
          return Err(LuceneError::illegal_argument(format!(
            "shard {shard_index} was not sorted by the provided Sort (expected FieldDoc but got ScoreDoc)"
          )));
        }
      }
    }

    let mut comparators = Vec::with_capacity(sort.fields.len());
    let mut reverse_mul = Vec::with_capacity(sort.fields.len());
    for sf in &sort.fields {
      comparators.push(sf.get_comparator(1, Pruning::None)?);
      reverse_mul.push(if sf.get_reverse() { -1 } else { 1 });
    }

    Ok(Self {
      shard_hits,
      comparators,
      reverse_mul,
      tie_breaker,
    })
  }
}

impl<C, B> Compare<ShardRef> for MergeSortQueueCmp<'_, C, B>
where
  C: Comparator<TopFieldScoreDoc>,
  B: Borrow<TopDocs<TopFieldScoreDoc>>,
{
  fn less_than(&self, first: &ShardRef, second: &ShardRef) -> Result<bool> {
    let first_fd = &self.shard_hits[first.shard_index].borrow().score_docs[first.hit_index];
    let second_fd = &self.shard_hits[second.shard_index].borrow().score_docs[second.hit_index];

    let first_fields = first_fd.fields()?;
    let second_fields = second_fd.fields()?;
    for (i, comp) in self.comparators.iter().enumerate() {
      let cmp = i32::from(self.reverse_mul[i])
        * comp.compare_values(Some(&first_fields[i]), Some(&second_fields[i]))?;
      if cmp != 0 {
        return Ok(cmp < 0);
      }
    }
    tie_break_less_than(first, first_fd, second, second_fd, &self.tie_breaker)
  }
}
impl<S> TopDocsLike for TopDocs<S>
where
  S: ScoreDocLike,
{
  fn total_hits(&self) -> &TotalHits {
    &self.total_hits
  }

  type ScoreDocLike = S;

  fn score_docs(&self) -> &[Self::ScoreDocLike] {
    &self.score_docs
  }

  fn score_docs_mut(&mut self) -> &mut [Self::ScoreDocLike] {
    &mut self.score_docs
  }

  fn take_score_docs(&mut self) -> Vec<Self::ScoreDocLike> {
    std::mem::take(&mut self.score_docs)
  }
}

pub trait TopDocsLike {
  fn total_hits(&self) -> &TotalHits;
  type ScoreDocLike: ScoreDocLike;
  fn score_docs(&self) -> &[Self::ScoreDocLike];
  fn score_docs_mut(&mut self) -> &mut [Self::ScoreDocLike];
  fn take_score_docs(&mut self) -> Vec<Self::ScoreDocLike>;
}