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
/*
 * 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::codecs::doc_values_consumer::DocValuesConsumer;
use crate::core::codecs::doc_values_producer::DocValuesProducer;
use crate::core::codecs::dummy::dummy_binary_doc_values::DummyBinaryDocValues;
use crate::core::codecs::dummy::dummy_doc_values_skipper::DummyDocValuesSkipper;
use crate::core::codecs::dummy::dummy_sorted_doc_values::DummySortedDocValues;
use crate::core::codecs::dummy::dummy_sorted_numeric_doc_values::DummySortedNumericDocValues;
use crate::core::codecs::dummy::dummy_sorted_set_doc_values::DummySortedSetDocValues;
use crate::core::index::doc_values_iterator::DocValuesIterator;
use crate::core::index::doc_values_writer::DocValuesWriter;
use crate::core::index::docs_with_field_set::{DocsWithFieldSet, DocsWithFieldSetDISI};
use crate::core::index::field_info::FieldInfo;
use crate::core::index::numeric_doc_values::NumericDocValues;
use crate::core::index::segment_info::SegmentInfo;
use crate::core::index::segment_write_state::SegmentWriteState;
use crate::core::index::sorter::DocMap;
use crate::core::search::doc_id_set::DocIdSet;
use crate::core::search::doc_id_set_iterator::DocIdSetIterator;
use crate::core::search::doc_id_set_iterator::NO_MORE_DOCS;
use crate::core::store::directory::Directory;
use crate::core::util::accountable::Accountable;
use crate::core::util::bit_set::BitSet;
use crate::core::util::close::CloseableRef;
use crate::core::util::error::lucene_error::LuceneError;
use crate::core::util::error::lucene_error::Result;
use crate::core::util::fixed_bit_set::FixedBitSet;
use crate::core::util::packed::PackedInts;
use crate::core::util::packed::packed_long_values::{
  Builder, PackedLongValues, PackedLongValuesIterator,
};
use crate::core::util::{ByteBlockPool, Counter, SharedCounter};
use std::borrow::Borrow;
use std::cell::Cell;
use std::fmt::{Display, Formatter};
use std::marker::PhantomData;
use std::sync::Arc;

/// Buffers pending `i64` values per document, then writes them during segment flush.
pub(crate) struct NumericDocValuesWriter {
  values: NumericValues,
  iw_bytes_used: SharedCounter,
  bytes_used: i64,
  docs_with_field: DocsWithFieldSet,
  field_info: Arc<FieldInfo>,
  last_doc_id: i32,
}

enum NumericValues {
  Pending(Builder),
  Finished(PackedLongValues),
}

impl NumericDocValuesWriter {
  pub(crate) fn new(field_info: Arc<FieldInfo>, iw_bytes_used: SharedCounter) -> Result<Self> {
    let pending = PackedLongValues::delta_packed_long_values_builder_default(PackedInts::COMPACT)?;
    let docs_with_field = DocsWithFieldSet::new();
    let bytes_used = pending.ram_bytes_used()? + docs_with_field.ram_bytes_used()?;

    iw_bytes_used.add_and_get(bytes_used);

    Ok(Self {
      values: NumericValues::Pending(pending),
      iw_bytes_used,
      bytes_used,
      docs_with_field,
      field_info,
      last_doc_id: -1,
    })
  }

  pub(crate) fn add_value(&mut self, doc_id: i32, value: i64) -> Result<()> {
    if doc_id <= self.last_doc_id {
      return Err(LuceneError::illegal_argument(format!(
        "DocValuesField \"{}\" appears more than once in this document (only one value is allowed per field)",
        self.field_info.name
      )));
    }

    let NumericValues::Pending(pending) = &mut self.values else {
      return Err(LuceneError::illegal_state(
        "DocsWithFieldSet must not be changed after finish() is called",
      ));
    };
    pending.add(value)?;
    self.docs_with_field.add(doc_id)?;
    let new_bytes_used = pending.ram_bytes_used()? + self.docs_with_field.ram_bytes_used()?;
    let delta = new_bytes_used - self.bytes_used;
    if delta != 0 {
      self.iw_bytes_used.add_and_get(delta);
    }
    self.bytes_used = new_bytes_used;
    self.last_doc_id = doc_id;
    Ok(())
  }
}

impl Display for NumericDocValuesWriter {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    write!(f, "{}", std::any::type_name::<Self>())
  }
}

impl DocValuesWriter for NumericDocValuesWriter {
  fn flush<D1, D2, DM, DC>(
    &mut self,
    write_state: &SegmentWriteState<D1>,
    sort_map: Option<&DM>,
    dv_consumer: &mut DC,
    segment_info: &SegmentInfo<D2>,
  ) -> Result<()>
  where
    D1: Directory<IndexOutput = DC::IndexOutput>,
    DM: DocMap,
    DC: DocValuesConsumer,
  {
    if let NumericValues::Pending(pending) = &mut self.values {
      self.values = NumericValues::Finished(std::mem::take(pending).build()?);
    }
    let NumericValues::Finished(final_values) = &self.values else {
      return Err(LuceneError::illegal_state(
        "final numeric values are unavailable after they were built",
      ));
    };
    let sorted = get_sorted_values(final_values, &self.docs_with_field, sort_map)?;
    match sorted.as_ref() {
      Some(sorted) => {
        let producer = DocValuesProducerImpl::new(&self.field_info, || {
          Ok(SortingNumericDocValues::new(sorted))
        });
        dv_consumer.add_numeric_field(write_state, segment_info, &self.field_info, &producer)?;
      },
      None if self.docs_with_field.is_dense() => {
        let producer = DocValuesProducerImpl::new(&self.field_info, || {
          BufferedNumericDocValues::new(final_values, self.docs_with_field.dense_iterator()?)
        });
        dv_consumer.add_numeric_field(write_state, segment_info, &self.field_info, &producer)?;
      },
      None => {
        let producer = DocValuesProducerImpl::new(&self.field_info, || {
          BufferedNumericDocValues::new(final_values, self.docs_with_field.sparse_iterator()?)
        });
        dv_consumer.add_numeric_field(write_state, segment_info, &self.field_info, &producer)?;
      },
    }
    Ok(())
  }

  type DocIdSetIterator = BufferedNumericDocValues;

  fn get_doc_values(&self) -> Result<Self::DocIdSetIterator> {
    let NumericValues::Finished(final_values) = &self.values else {
      return Err(LuceneError::illegal_state(
        "must be finished before getting doc values",
      ));
    };
    let iter = self.docs_with_field.iterator()?;
    BufferedNumericDocValues::new(final_values.clone(), iter)
  }

  fn finish(&mut self, _pool: &Arc<ByteBlockPool>) -> Result<()> {
    self.docs_with_field.finish();
    if let NumericValues::Pending(pending) = &mut self.values {
      self.values = NumericValues::Finished(std::mem::take(pending).build()?);
    }
    Ok(())
  }
}

pub(crate) struct DocValuesProducerImpl<'a, F> {
  writer_field_info: &'a Arc<FieldInfo>,
  make_values: F,
}

impl<F> CloseableRef for DocValuesProducerImpl<'_, F> {
  fn close(&self) -> Result<()> {
    Err(LuceneError::unsupported_operation(""))
  }
}

impl<'a, F> DocValuesProducerImpl<'a, F> {
  pub(crate) fn new(writer_field_info: &'a Arc<FieldInfo>, make_values: F) -> Self {
    Self {
      writer_field_info,
      make_values,
    }
  }
}
impl<F, V> DocValuesProducer for DocValuesProducerImpl<'_, F>
where
  F: Fn() -> Result<V>,
  V: NumericDocValues,
{
  type NumericDocValues = V;

  fn get_numeric(&self, field_info: &Arc<FieldInfo>) -> Result<Self::NumericDocValues> {
    if !Arc::ptr_eq(field_info, self.writer_field_info) {
      return Err(LuceneError::illegal_argument("wrong fieldInfo"));
    }
    (self.make_values)()
  }

  type BinaryDocValues = DummyBinaryDocValues;
  type SortedDocValues = DummySortedDocValues;
  type SortedNumericDocValues = DummySortedNumericDocValues;
  type SortedSetDocValues = DummySortedSetDocValues;
  type DocValuesSkipper = DummyDocValuesSkipper;
}

// iterates over the values we have in ram
pub(crate) struct BufferedNumericDocValues<V = PackedLongValues, D = DocsWithFieldSetDISI> {
  iter: PackedLongValuesIterator<V>,
  doc_with_field: D,
  value: i64,
}
impl<V: Borrow<PackedLongValues>, D: DocIdSetIterator> BufferedNumericDocValues<V, D> {
  pub(crate) fn new(values: V, doc_with_field: D) -> Result<Self> {
    Ok(Self {
      iter: PackedLongValuesIterator::new(values)?,
      doc_with_field,
      value: 0,
    })
  }
}

impl<V: Borrow<PackedLongValues>, D: DocIdSetIterator> DocValuesIterator
  for BufferedNumericDocValues<V, D>
{
  fn advance_exact(&mut self, _target: i32) -> Result<bool> {
    Err(LuceneError::unsupported_operation(""))
  }
}

impl<V: Borrow<PackedLongValues>, D: DocIdSetIterator>
  crate::core::search::doc_id_set_iterator::DocIdSetIteratorExtensions
  for BufferedNumericDocValues<V, D>
{
}
impl<V: Borrow<PackedLongValues>, D: DocIdSetIterator>
  crate::core::search::doc_id_set_iterator::BitSetIteratorAccess
  for BufferedNumericDocValues<V, D>
{
}

impl<V: Borrow<PackedLongValues>, D: DocIdSetIterator> DocIdSetIterator
  for BufferedNumericDocValues<V, D>
{
  fn doc_id(&self) -> i32 {
    self.doc_with_field.doc_id()
  }

  fn next_doc(&mut self) -> Result<i32> {
    let doc_id = self.doc_with_field.next_doc()?;
    if doc_id != NO_MORE_DOCS {
      self.value = self.iter.next_value()?;
    }
    Ok(doc_id)
  }

  fn advance(&mut self, _target: i32) -> Result<i32> {
    Err(LuceneError::unsupported_operation(""))
  }

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

impl<V: Borrow<PackedLongValues>, D: DocIdSetIterator> NumericDocValues
  for BufferedNumericDocValues<V, D>
{
  fn long_value(&mut self) -> Result<i64> {
    Ok(self.value)
  }
}

pub struct SortingNumericDocValues<T, D = Arc<NumericDVs<T>>> {
  dvs: D,
  marker: PhantomData<T>,
  doc_id: i32,
  cost: Cell<i64>,
}

impl<T, D> SortingNumericDocValues<T, D> {
  pub(crate) fn new(dvs: D) -> Self {
    Self {
      dvs,
      marker: PhantomData,
      doc_id: -1,
      cost: Cell::new(-1),
    }
  }
}

impl<T, D> DocValuesIterator for SortingNumericDocValues<T, D>
where
  T: BitSet,
  D: Borrow<NumericDVs<T>>,
{
  fn advance_exact(&mut self, target: i32) -> Result<bool> {
    // needed in IndexSorter#{Long|Int|Double|Float}Sorter
    self.doc_id = target;
    Ok(self.dvs.borrow().advance_exact(target))
  }
}

impl<T, D> crate::core::search::doc_id_set_iterator::DocIdSetIteratorExtensions
  for SortingNumericDocValues<T, D>
where
  T: BitSet,
  D: Borrow<NumericDVs<T>>,
{
}
impl<T, D> crate::core::search::doc_id_set_iterator::BitSetIteratorAccess
  for SortingNumericDocValues<T, D>
where
  T: BitSet,
  D: Borrow<NumericDVs<T>>,
{
}

impl<T, D> DocIdSetIterator for SortingNumericDocValues<T, D>
where
  T: BitSet,
  D: Borrow<NumericDVs<T>>,
{
  fn doc_id(&self) -> i32 {
    self.doc_id
  }

  fn next_doc(&mut self) -> Result<i32> {
    if self.doc_id + 1 == self.dvs.borrow().max_doc() {
      self.doc_id = NO_MORE_DOCS;
    } else {
      self.doc_id = self.dvs.borrow().advance(self.doc_id + 1);
    }
    Ok(self.doc_id)
  }

  fn advance(&mut self, _target: i32) -> Result<i32> {
    Err(LuceneError::unsupported_operation("use nextDoc() instead"))
  }

  fn cost(&self) -> Result<i64> {
    if self.cost.get() == -1 {
      self.cost.set(self.dvs.borrow().cost());
    }
    Ok(self.cost.get())
  }
}

impl<T, D> NumericDocValues for SortingNumericDocValues<T, D>
where
  T: BitSet,
  D: Borrow<NumericDVs<T>>,
{
  fn long_value(&mut self) -> Result<i64> {
    Ok(self.dvs.borrow().values[self.doc_id as usize])
  }
}

pub struct NumericDVs<T> {
  pub values: Vec<i64>,
  pub docs_with_field: Option<T>,
  pub max_doc: i32,
}

impl<T> NumericDVs<T> {
  pub(crate) fn new(values: Vec<i64>, docs_with_field: Option<T>) -> Self {
    debug_assert!(values.len() <= i32::MAX as usize);
    let max_doc = values.len() as i32;
    Self {
      values,
      docs_with_field,
      max_doc,
    }
  }

  pub(crate) fn max_doc(&self) -> i32 {
    self.max_doc
  }
}

impl<T> NumericDVs<T>
where
  T: BitSet,
{
  fn advance_exact(&self, target: i32) -> bool {
    match &self.docs_with_field {
      Some(bits) => bits.get(target as usize).unwrap_or(false),
      None => true,
    }
  }
  pub(crate) fn advance(&self, target: i32) -> i32 {
    if let Some(bits) = &self.docs_with_field {
      bits.next_set_bit(target as usize) as i32
    } else {
      // Only called when target is less than maxDoc
      target
    }
  }
  pub(crate) fn cost(&self) -> i64 {
    match &self.docs_with_field {
      Some(bits) => bits.cardinality() as i64,
      None => self.max_doc as i64,
    }
  }
}

pub(crate) fn sort_doc_values<DV, M>(
  max_doc: i32,
  sort_map: &M,
  old_doc_values: &mut DV,
  dense: bool,
) -> Result<NumericDVs<FixedBitSet>>
where
  DV: NumericDocValues,
  M: DocMap,
{
  let max_doc = max_doc as usize;
  let mut docs_with_field = if !dense {
    Some(FixedBitSet::new(max_doc))
  } else {
    None
  };

  let mut values = vec![0i64; max_doc];

  loop {
    let doc_id = old_doc_values.next_doc()?;
    if doc_id == NO_MORE_DOCS {
      break;
    }

    let new_doc_id = sort_map.old_to_new(doc_id)? as usize;
    if let Some(bits) = &mut docs_with_field {
      bits.set(new_doc_id)?;
    }

    values[new_doc_id] = old_doc_values.long_value()?;
  }
  Ok(NumericDVs::new(values, docs_with_field))
}

pub(crate) fn get_sorted_values<DM>(
  values: &PackedLongValues,
  docs_with_field: &DocsWithFieldSet,
  sort_map: Option<&DM>,
) -> Result<Option<NumericDVs<FixedBitSet>>>
where
  DM: DocMap,
{
  let sorter = if let Some(sort_map) = sort_map {
    let dense = sort_map.size() == docs_with_field.cardinality();
    let iter = docs_with_field.iterator()?;
    let mut old_values = BufferedNumericDocValues::new(values, iter)?;
    let sorted = sort_doc_values(sort_map.size(), sort_map, &mut old_values, dense)?;
    Some(sorted)
  } else {
    None
  };
  Ok(sorter)
}