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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
/*
 * 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::Identity;
use crate::core::index::vector_encoding::VectorEncoding;
use crate::core::search::doc_id_set_iterator::DocIdSetIterator;
use crate::core::search::doc_id_set_iterator::NO_MORE_DOCS;
use crate::core::util::bits::{Bits, BitsEnum2};
use crate::core::util::error::lucene_error::{LuceneError, Result};
use crate::core::util::{HasIdentity, TryIntoInt};

/// This struct abstracts addressing of document vector values indexed as
/// [`KnnFloatVectorField`](crate::core::document::knn_float_vector_field::KnnFloatVectorField) or [`KnnByteVectorField`](crate::core::document::knn_byte_vector_field::KnnByteVectorField).
pub trait KnnVectorValues {
  /// Return the dimension of the vectors
  fn dimension(&self) -> usize;
  /// Return the number of vectors for this field.
  ///
  /// # Returns
  /// The number of vectors returned by this iterator.
  fn size(&self) -> usize;
  /// Return the docid of the document indexed with the given vector ordinal.
  /// This default implementation returns the argument and is appropriate for
  /// dense values implementations where every doc has a single value.
  fn ord_to_doc(&self, ord: usize) -> Result<usize> {
    Ok(ord)
  }
  type KnnVectorValues: KnnVectorValues;
  /// Creates a new copy of this [`KnnVectorValues`]. This is helpful when you
  /// need to access different values at once, to avoid overwriting the
  /// underlying vector returned.
  fn copy(&self) -> Result<Self::KnnVectorValues> {
    Err(LuceneError::unsupported_operation(""))
  }
  /// Returns the vector byte length, defaults to dimension multiplied by
  /// float byte size
  fn get_vector_byte_length(&self) -> usize {
    self.dimension() * self.get_encoding().byte_size()
  }
  /// The vector encoding of these values.
  fn get_encoding(&self) -> VectorEncoding;

  type Bits<'a, B>: Bits
  where
    B: Bits,
    Self: 'a;
  /// Returns a Bits accepting docs accepted by the argument and having a
  /// vector value
  fn get_accept_ords<'a, B>(&'a self, accept_docs: Option<B>) -> Option<Self::Bits<'a, B>>
  where
    B: Bits;
  fn default_get_accept_ords<B>(&self, accept_docs: Option<B>) -> Option<BitsImpl<B, &Self>>
  where
    B: Bits,
    Self: Sized,
  {
    accept_docs.map(|accept_docs| BitsImpl::new(accept_docs, self.size(), self))
  }

  type DocIndexIterator: DocIndexIterator;
  ///  Create an iterator for this instance.
  fn iterator(&self) -> Result<Self::DocIndexIterator> {
    Err(LuceneError::unsupported_operation(""))
  }
}

impl<T> KnnVectorValues for &T
where
  T: KnnVectorValues,
{
  fn dimension(&self) -> usize {
    (**self).dimension()
  }

  fn size(&self) -> usize {
    (**self).size()
  }

  fn ord_to_doc(&self, ord: usize) -> Result<usize> {
    (**self).ord_to_doc(ord)
  }

  type KnnVectorValues = T::KnnVectorValues;

  fn copy(&self) -> Result<Self::KnnVectorValues> {
    (**self).copy()
  }

  fn get_vector_byte_length(&self) -> usize {
    (**self).get_vector_byte_length()
  }

  fn get_encoding(&self) -> VectorEncoding {
    (**self).get_encoding()
  }

  type Bits<'a, B>
    = T::Bits<'a, B>
  where
    B: Bits,
    Self: 'a,
    T: 'a;

  fn get_accept_ords<'a, B>(&'a self, accept_docs: Option<B>) -> Option<Self::Bits<'a, B>>
  where
    B: Bits,
  {
    (**self).get_accept_ords(accept_docs)
  }

  type DocIndexIterator = T::DocIndexIterator;

  fn iterator(&self) -> Result<Self::DocIndexIterator> {
    (**self).iterator()
  }
}
pub struct BitsImpl<B, T> {
  accept_docs: B,
  size: usize,
  map: T,
  id: Identity,
}
impl<B, T> BitsImpl<B, T> {
  pub(crate) fn new(accept_docs: B, size: usize, map: T) -> Self {
    Self {
      accept_docs,
      size,
      map,
      id: Identity::new(),
    }
  }
}

impl<B, T> HasIdentity for BitsImpl<B, T> {
  fn identity(&self) -> &Identity {
    &self.id
  }
}

impl<B, T> Bits for BitsImpl<B, T>
where
  B: Bits,
  T: KnnVectorValues,
{
  fn get(&self, index: usize) -> Result<bool> {
    self.accept_docs.get(self.map.ord_to_doc(index)?)
  }

  fn length(&self) -> usize {
    self.size
  }
}

/// A DocIdSetIterator that also provides an index() method tracking a distinct
/// ordinal for a vector associated with each doc.
pub trait DocIndexIterator: DocIdSetIterator {
  /// return the value index (aka "ordinal" or "ord") corresponding to the
  /// current doc
  fn index(&self) -> Result<i32>;
}

#[macro_export]
macro_rules! either_doc_index_iterator_named {
    ($vis:vis $name:ident { $( $Variant:ident : $T:ident ),+ $(,)? }) => {
        $vis enum $name<$( $T ),+> {
            $( $Variant($T), )+
        }

        impl<$( $T ),+> $crate::core::search::doc_id_set_iterator::DocIdSetIterator for $name<$( $T ),+>
        where
            $( $T: $crate::core::search::doc_id_set_iterator::DocIdSetIterator ),+
        {
            fn doc_id(&self) -> i32 {
                match self {
                    $( Self::$Variant(inner) => inner.doc_id(), )+
                }
            }

            fn next_doc(&mut self) -> Result<i32> {
                match self {
                    $( Self::$Variant(inner) => inner.next_doc(), )+
                }
            }

            fn advance(&mut self, target: i32) -> Result<i32> {
                match self {
                    $( Self::$Variant(inner) => inner.advance(target), )+
                }
            }

            fn slow_advance(&mut self, target: i32) -> Result<i32> {
                match self {
                    $( Self::$Variant(inner) => inner.slow_advance(target), )+
                }
            }

            fn cost(&self) -> Result<i64> {
                match self {
                    $( Self::$Variant(inner) => inner.cost(), )+
                }
            }
        }

        impl<$( $T ),+>
          $crate::core::search::doc_id_set_iterator::DocIdSetIteratorExtensions
          for $name<$( $T ),+>
        where
            $( $T: $crate::core::search::doc_id_set_iterator::DocIdSetIterator ),+
        {}
        impl<$( $T ),+>
          $crate::core::search::doc_id_set_iterator::BitSetIteratorAccess
          for $name<$( $T ),+>
        where
            $( $T: $crate::core::search::doc_id_set_iterator::DocIdSetIterator ),+
        {}


        impl<$( $T ),+> $crate::core::index::knn_vector_values::DocIndexIterator for $name<$( $T ),+>
        where
            $( $T: $crate::core::index::knn_vector_values::DocIndexIterator ),+
        {
            fn index(&self) -> Result<i32> {
                match self {
                    $( Self::$Variant(inner) => inner.index(), )+
                }
            }
        }
    };
}

either_doc_index_iterator_named!(pub DocIndexIteratorEnum2 { A: A, B: B });

pub struct DenseDocIndexIterator {
  doc: i32,
  size: i32,
}
impl DenseDocIndexIterator {
  pub(crate) fn new(size: i32) -> Self {
    Self { doc: -1, size }
  }
}

impl crate::core::search::doc_id_set_iterator::DocIdSetIteratorExtensions
  for DenseDocIndexIterator
{
}
impl crate::core::search::doc_id_set_iterator::BitSetIteratorAccess for DenseDocIndexIterator {}

impl DocIdSetIterator for DenseDocIndexIterator {
  fn doc_id(&self) -> i32 {
    self.doc
  }

  fn next_doc(&mut self) -> Result<i32> {
    if self.doc >= self.size - 1 {
      self.doc = NO_MORE_DOCS;
    } else {
      self.doc += 1;
    }
    Ok(self.doc)
  }

  fn advance(&mut self, target: i32) -> Result<i32> {
    if target >= self.size {
      self.doc = NO_MORE_DOCS;
    } else {
      self.doc = target;
    }
    Ok(self.doc)
  }

  fn cost(&self) -> Result<i64> {
    Ok(self.size as i64)
  }
}

impl DocIndexIterator for DenseDocIndexIterator {
  fn index(&self) -> Result<i32> {
    Ok(self.doc)
  }
}

pub struct DocIndexIteratorImpl2<D> {
  ord: i32,
  docs_with_field: D,
}

impl<D> DocIndexIteratorImpl2<D> {
  pub fn new(docs_with_field: D) -> Self {
    Self {
      ord: -1,
      docs_with_field,
    }
  }
}

impl<D> crate::core::search::doc_id_set_iterator::DocIdSetIteratorExtensions
  for DocIndexIteratorImpl2<D>
where
  D: DocIdSetIterator,
{
}
impl<D> crate::core::search::doc_id_set_iterator::BitSetIteratorAccess for DocIndexIteratorImpl2<D> where
  D: DocIdSetIterator
{
}

impl<D> DocIdSetIterator for DocIndexIteratorImpl2<D>
where
  D: DocIdSetIterator,
{
  fn doc_id(&self) -> i32 {
    self.docs_with_field.doc_id()
  }

  fn next_doc(&mut self) -> Result<i32> {
    if self.doc_id() == NO_MORE_DOCS {
      return Ok(NO_MORE_DOCS);
    }
    self.ord += 1;
    self.docs_with_field.next_doc()
  }

  fn advance(&mut self, target: i32) -> Result<i32> {
    self.docs_with_field.advance(target)
  }

  fn cost(&self) -> Result<i64> {
    self.docs_with_field.cost()
  }
}

impl<D> DocIndexIterator for DocIndexIteratorImpl2<D>
where
  D: DocIdSetIterator,
{
  fn index(&self) -> Result<i32> {
    Ok(self.ord)
  }
}

pub struct SparseDocIndexIterator<T> {
  ord: i32,
  size: usize,
  map: T,
}

impl<T> SparseDocIndexIterator<T> {
  pub fn new(size: usize, ord_to_doc: T) -> Self {
    Self {
      ord: -1,
      size,
      map: ord_to_doc,
    }
  }
}

impl<T> crate::core::search::doc_id_set_iterator::DocIdSetIteratorExtensions
  for SparseDocIndexIterator<T>
where
  T: OrdToDoc,
{
}
impl<T> crate::core::search::doc_id_set_iterator::BitSetIteratorAccess for SparseDocIndexIterator<T> where
  T: OrdToDoc
{
}

impl<T> DocIdSetIterator for SparseDocIndexIterator<T>
where
  T: OrdToDoc,
{
  fn doc_id(&self) -> i32 {
    if self.ord == -1 {
      -1
    } else if self.ord == NO_MORE_DOCS {
      NO_MORE_DOCS
    } else {
      self.map.ord_to_doc(self.ord as usize)
    }
  }

  fn next_doc(&mut self) -> Result<i32> {
    if (self.ord + 1).try_convert()? >= self.size {
      self.ord = NO_MORE_DOCS;
    } else {
      self.ord += 1;
    }
    Ok(self.doc_id())
  }

  fn advance(&mut self, target: i32) -> Result<i32> {
    self.slow_advance(target)
  }

  fn cost(&self) -> Result<i64> {
    Ok(self.size as i64)
  }
}

impl<T> DocIndexIterator for SparseDocIndexIterator<T>
where
  T: OrdToDoc,
{
  fn index(&self) -> Result<i32> {
    Ok(self.ord)
  }
}

pub trait OrdToDoc {
  fn ord_to_doc(&self, ord: usize) -> i32;
}

pub(crate) fn create_dense_iterator(size: i32) -> DenseDocIndexIterator {
  DenseDocIndexIterator::new(size)
}

/// creates an iterator from a docidsetiterator indicating which docs have
/// values, and for which ordinals increase monotonically with docid.
pub fn from_disi<D>(disi: D) -> DocIndexIteratorImpl2<D>
where
  D: DocIdSetIterator,
{
  DocIndexIteratorImpl2::new(disi)
}

///  Creates an iterator from this instance's ordinal-to-docid mapping which
/// must be monotonic (docid increases when ordinal does).
pub fn create_sparse_iterator<T>(size: usize, map: T) -> SparseDocIndexIterator<T>
where
  T: OrdToDoc,
{
  SparseDocIndexIterator::new(size, map)
}
pub enum KnnVectorValuesType<B, F> {
  Byte(B),
  Float(F),
}

#[macro_export]
macro_rules! either_knn_vector_values_named {
    (
        $vis:vis $name:ident {
            iter = $iter_ty:ident,
            bits = $bits_ty:ident;
            $( $Variant:ident : $T:ident ),+ $(,)?
        }
    ) => {
        $vis enum $name<$( $T ),+> {
            $( $Variant($T), )+
        }

        impl<$( $T ),+> $crate::core::index::knn_vector_values::KnnVectorValues for $name<$( $T ),+>
        where
            $( $T: $crate::core::index::knn_vector_values::KnnVectorValues ),+
        {
            #[inline]
            fn dimension(&self) -> usize {
                match self {
                    $( Self::$Variant(inner) => inner.dimension(), )+
                }
            }

            #[inline]
            fn size(&self) -> usize {
                match self {
                    $( Self::$Variant(inner) => inner.size(), )+
                }
            }

            #[inline]
            fn ord_to_doc(&self, ord: usize) -> $crate::core::util::error::lucene_error::Result<usize> {
                match self {
                    $( Self::$Variant(inner) => inner.ord_to_doc(ord), )+
                }
            }

            type KnnVectorValues =
                $name<$( < $T as $crate::core::index::knn_vector_values::KnnVectorValues >::KnnVectorValues ),+>;

            #[inline]
            fn copy(&self) -> $crate::core::util::error::lucene_error::Result<Self::KnnVectorValues> {
                match self {
                    $( Self::$Variant(inner) => inner.copy().map($name::$Variant), )+
                }
            }

            #[inline]
            fn get_vector_byte_length(&self) -> usize {
                match self {
                    $( Self::$Variant(inner) => inner.get_vector_byte_length(), )+
                }
            }

            #[inline]
            fn get_encoding(&self) -> $crate::core::index::vector_encoding::VectorEncoding {
                match self {
                    $( Self::$Variant(inner) => inner.get_encoding(), )+
                }
            }

            type Bits<'a, AcceptDocs> =
                $bits_ty<$( < $T as $crate::core::index::knn_vector_values::KnnVectorValues >::Bits<'a, AcceptDocs> ),+>
            where
                AcceptDocs: $crate::core::util::bits::Bits,
                Self: 'a;

            #[inline]
            fn get_accept_ords<'a, AcceptDocs>(&'a self, accept_docs: Option<AcceptDocs>) -> Option<Self::Bits<'a, AcceptDocs>>
            where
                AcceptDocs: $crate::core::util::bits::Bits,
            {
                match self {
                    $( Self::$Variant(inner) => inner.get_accept_ords(accept_docs).map($bits_ty::$Variant), )+
                }
            }

            type DocIndexIterator =
                $iter_ty<$( < $T as $crate::core::index::knn_vector_values::KnnVectorValues >::DocIndexIterator ),+>;

            #[inline]
            fn iterator(&self) -> $crate::core::util::error::lucene_error::Result<Self::DocIndexIterator> {
                match self {
                    $( Self::$Variant(inner) => inner.iterator().map($iter_ty::$Variant), )+
                }
            }
        }
    };
}

either_knn_vector_values_named!(
    pub KnnVectorValuesEnm2 {
        iter = DocIndexIteratorEnum2,
        bits = BitsEnum2;
        A: A, B: B,
    }
);

/// No separate read-buffer instance is returned by `float_copy` or `byte_copy`.
/// An optional value of this type can only be `None`; explicit `TryClone`
/// snapshots of the original provider remain independent operations.
#[doc(hidden)]
pub type NoVectorValuesCopy = std::convert::Infallible;

impl crate::core::util::clone::TryClone for NoVectorValuesCopy {
  fn try_clone(&self) -> Result<Self> {
    match *self {}
  }
}

impl KnnVectorValues for NoVectorValuesCopy {
  fn dimension(&self) -> usize {
    match *self {}
  }

  fn size(&self) -> usize {
    match *self {}
  }

  type KnnVectorValues = Self;

  fn get_encoding(&self) -> VectorEncoding {
    match *self {}
  }

  type Bits<'a, B>
    = B
  where
    B: Bits,
    Self: 'a;

  fn get_accept_ords<'a, B>(&'a self, _accept_docs: Option<B>) -> Option<Self::Bits<'a, B>>
  where
    B: Bits,
  {
    match *self {}
  }

  type DocIndexIterator =
    crate::core::index::dummy::dummy_doc_index_iterator::DummyDocIndexIterator;
}

impl crate::core::index::float_vector_values::FloatVectorValues for NoVectorValuesCopy {
  type VectorValue<'v>
    = &'v [f32]
  where
    Self: 'v;

  fn vector_value(&self, _ord: usize) -> Result<Self::VectorValue<'_>> {
    match *self {}
  }

  type FloatVectorValues = Self;
  type VectorScorer = crate::core::search::dummy::dummy_vector_scorer::DummyVectorScorer;
}

impl crate::core::index::byte_vector_values::ByteVectorValues for NoVectorValuesCopy {
  type VectorValue<'v>
    = &'v [u8]
  where
    Self: 'v;

  fn vector_value(&self, _ord: usize) -> Result<Self::VectorValue<'_>> {
    match *self {}
  }

  type ByteVectorValues = Self;
  type VectorScorer = crate::core::search::dummy::dummy_vector_scorer::DummyVectorScorer;
}