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
/*
 * 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_doc_values_skipper::DummyDocValuesSkipper;
use crate::core::codecs::dummy::dummy_numeric_doc_values::DummyNumericDocValues;
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::binary_doc_values::BinaryDocValues;
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::segment_info::SegmentInfo;
use crate::core::index::segment_write_state::SegmentWriteState;
use crate::core::index::sorter::DocMap;
use crate::core::index::{BytesRef, BytesRefBuilder, BytesRefValue};
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::store::{DataInput, DataOutput};
use crate::core::util::accountable::Accountable;
use crate::core::util::close::CloseableRef;
use crate::core::util::error::lucene_error::{LuceneError, Result};
use crate::core::util::packed::PackedInts;
use crate::core::util::packed::packed_long_values::{
  Builder, PackedLongValues, PackedLongValuesIterator,
};
use crate::core::util::paged_bytes::{
  PagedBytes, PagedBytesDataInput, PagedBytesDataOutput, get_data_input, get_data_output,
};
use crate::core::util::{
  AtomicCounter, ByteBlockPool, BytesRefArray, Counter, SharedCounter, SortableBytesRefArray,
  TryIntoInt,
};
use std::borrow::Borrow;
use std::fmt::{Display, Formatter};
use std::sync::Arc;

/// Buffers up pending `[u8]` per doc, then flushes when segment flushes.
pub(crate) struct BinaryDocValuesWriter {
  field_info: Arc<FieldInfo>,
  bytes_out: PagedBytesDataOutput,
  iw_bytes_used: SharedCounter,
  lengths: BinaryLengths,
  docs_with_field: DocsWithFieldSet,
  bytes_used: i64,
  last_doc_id: i32,
  max_length: usize,
}

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

impl BinaryDocValuesWriter {
  pub(crate) fn new(field_info: Arc<FieldInfo>, iw_bytes_used: SharedCounter) -> Result<Self> {
    let bytes = PagedBytes::new(BLOCK_BITS);
    let bytes_out = get_data_output(bytes)?;
    let lengths = PackedLongValues::delta_packed_long_values_builder_default(PackedInts::COMPACT)?;
    let docs_with_field = DocsWithFieldSet::new();

    let bytes_used = lengths.ram_bytes_used()? + docs_with_field.ram_bytes_used()?;
    iw_bytes_used.add_and_get(bytes_used);

    Ok(Self {
      field_info,
      bytes_out,
      iw_bytes_used,
      lengths: BinaryLengths::Pending(lengths),
      docs_with_field,
      bytes_used,
      last_doc_id: -1,
      max_length: 0,
    })
  }
  pub(crate) fn add_value(&mut self, doc_id: i32, value: &BytesRef<&[u8]>) -> 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
      )));
    }
    if value.length > MAX_LENGTH {
      return Err(LuceneError::illegal_argument(format!(
        "DocValuesField \"{}\" is too large, must be <= {}",
        self.field_info.name, MAX_LENGTH
      )));
    }

    self.max_length = self.max_length.max(value.length);
    let BinaryLengths::Pending(lengths) = &mut self.lengths else {
      return Err(LuceneError::illegal_state("Cannot be reused after build()"));
    };
    lengths.add(value.length as i64)?;

    self
      .bytes_out
      .write_bytes_range(value.bytes, value.offset, value.length)?;

    self.docs_with_field.add(doc_id)?;
    let lengths_bytes_used = lengths.ram_bytes_used()?;
    self.update_bytes_used(lengths_bytes_used)?;

    self.last_doc_id = doc_id;
    Ok(())
  }

  fn update_bytes_used(&mut self, lengths_bytes_used: i64) -> Result<()> {
    let new_bytes_used = lengths_bytes_used
      + self.bytes_out.paged_bytes.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;
    Ok(())
  }
}

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

impl DocValuesWriter for BinaryDocValuesWriter {
  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,
  {
    self.bytes_out.paged_bytes.freeze(false)?;
    if let BinaryLengths::Pending(lengths) = &mut self.lengths {
      self.lengths = BinaryLengths::Finished(lengths.build()?);
    }
    let BinaryLengths::Finished(final_lengths) = &self.lengths else {
      return Err(LuceneError::illegal_state(
        "final lengths are unavailable after they were built",
      ));
    };
    let sorted = match sort_map {
      Some(sort_map) => {
        let mut buffered_binary_doc_values = BufferedBinaryDocValues::new(
          || final_lengths,
          self.max_length,
          get_data_input(&self.bytes_out.paged_bytes)?,
          self.docs_with_field.iterator()?,
        )?;
        Some(BinaryDVs::new(
          segment_info.max_doc()?.try_convert()?,
          sort_map,
          &mut buffered_binary_doc_values,
        )?)
      },
      None => None,
    };
    match sorted.as_ref() {
      Some(sorted) => {
        let producer =
          DocValuesProducerImpl::new(&self.field_info, || Ok(SortingBinaryDocValues::new(sorted)))?;
        dv_consumer.add_binary_field(write_state, segment_info, &self.field_info, &producer)
      },
      None => {
        let producer = DocValuesProducerImpl::new(&self.field_info, || {
          BufferedBinaryDocValues::new(
            || final_lengths,
            self.max_length,
            get_data_input(&self.bytes_out.paged_bytes)?,
            self.docs_with_field.iterator()?,
          )
        })?;
        dv_consumer.add_binary_field(write_state, segment_info, &self.field_info, &producer)
      },
    }
  }

  type DocIdSetIterator = BufferedBinaryDocValues<DocsWithFieldSetDISI, PagedBytesDataInput>;

  fn get_doc_values(&self) -> Result<Self::DocIdSetIterator> {
    let BinaryLengths::Finished(final_lengths) = &self.lengths else {
      return Err(LuceneError::illegal_state(
        "must be finished before getting doc values".to_string(),
      ));
    };
    BufferedBinaryDocValues::new(
      || final_lengths.clone(),
      self.max_length,
      get_data_input(&self.bytes_out.paged_bytes)?,
      self.docs_with_field.iterator()?,
    )
  }

  fn finish(&mut self, _pool: &Arc<ByteBlockPool>) -> Result<()> {
    self.docs_with_field.finish();
    if let BinaryLengths::Pending(lengths) = &mut self.lengths {
      self.lengths = BinaryLengths::Finished(lengths.build()?);
    }
    Ok(())
  }
}

pub(crate) struct DocValuesProducerImpl<'a, F> {
  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(field_info: &'a Arc<FieldInfo>, make_values: F) -> Result<Self> {
    Ok(Self {
      field_info,
      make_values,
    })
  }
}

impl<F, V> DocValuesProducer for DocValuesProducerImpl<'_, F>
where
  F: Fn() -> Result<V>,
  V: BinaryDocValues,
{
  type NumericDocValues = DummyNumericDocValues;
  type BinaryDocValues = V;

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

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

// iterates over the values we have in ram
pub(crate) struct BufferedBinaryDocValues<D, DI, V = PackedLongValues> {
  value: BytesRefBuilder<Vec<u8>>,
  lengths_iterator: PackedLongValuesIterator<V>,
  docs_with_field: D,
  bytes_iter: DI,
}

impl<D, DI, V: Borrow<PackedLongValues>> BufferedBinaryDocValues<D, DI, V> {
  pub(crate) fn new(
    lengths: impl FnOnce() -> V,
    max_length: usize,
    bytes_iter: DI,
    docs_with_field: D,
  ) -> Result<Self> {
    let mut value = BytesRefBuilder::new();
    value.grow(max_length)?;
    // Acquire owned lengths only after grow succeeds, preserving the original clone order.
    Ok(Self {
      value,
      lengths_iterator: PackedLongValuesIterator::new(lengths())?,
      docs_with_field,
      bytes_iter,
    })
  }
}

impl<D, DI, V: Borrow<PackedLongValues>>
  crate::core::search::doc_id_set_iterator::DocIdSetIteratorExtensions
  for BufferedBinaryDocValues<D, DI, V>
where
  D: DocIdSetIterator,
  DI: DataInput,
{
}
impl<D, DI, V: Borrow<PackedLongValues>>
  crate::core::search::doc_id_set_iterator::BitSetIteratorAccess
  for BufferedBinaryDocValues<D, DI, V>
where
  D: DocIdSetIterator,
  DI: DataInput,
{
}

impl<D, DI, V: Borrow<PackedLongValues>> DocIdSetIterator for BufferedBinaryDocValues<D, DI, V>
where
  D: DocIdSetIterator,
  DI: DataInput,
{
  fn doc_id(&self) -> i32 {
    self.docs_with_field.doc_id()
  }

  fn next_doc(&mut self) -> Result<i32> {
    let doc_id = self.docs_with_field.next_doc()?;
    if doc_id != NO_MORE_DOCS {
      let length = self.lengths_iterator.next_value()?.try_convert()?;
      self.value.set_length(length);
      self
        .bytes_iter
        .read_bytes(&mut self.value.bytes_ref.bytes, 0, length)?;
    }
    Ok(doc_id)
  }

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

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

impl<D, DI, V: Borrow<PackedLongValues>> DocValuesIterator for BufferedBinaryDocValues<D, DI, V>
where
  D: DocIdSetIterator,
  DI: DataInput,
{
  fn advance_exact(&mut self, _target: i32) -> Result<bool> {
    Err(LuceneError::unsupported_operation("use next_doc instead"))
  }
}

impl<D, DI, V: Borrow<PackedLongValues>> BinaryDocValues for BufferedBinaryDocValues<D, DI, V>
where
  D: DocIdSetIterator,
  DI: DataInput,
{
  type Value<'a>
    = &'a BytesRef<Vec<u8>>
  where
    Self: 'a;

  fn binary_value(&self) -> Result<Self::Value<'_>> {
    Ok(self.value.get_bytes_ref())
  }
}

pub struct SortingBinaryDocValues<D = Arc<BinaryDVs>> {
  dvs: D,
  doc_id: i32,
}

impl<D: Borrow<BinaryDVs>> SortingBinaryDocValues<D> {
  pub(crate) fn new(dvs: D) -> Self {
    Self { dvs, doc_id: -1 }
  }
}

impl<D: Borrow<BinaryDVs>> crate::core::search::doc_id_set_iterator::DocIdSetIteratorExtensions
  for SortingBinaryDocValues<D>
{
}
impl<D: Borrow<BinaryDVs>> crate::core::search::doc_id_set_iterator::BitSetIteratorAccess
  for SortingBinaryDocValues<D>
{
}

impl<D: Borrow<BinaryDVs>> DocIdSetIterator for SortingBinaryDocValues<D> {
  fn doc_id(&self) -> i32 {
    self.doc_id
  }

  fn next_doc(&mut self) -> Result<i32> {
    loop {
      self.doc_id += 1;
      let doc_index = self.doc_id as usize;
      if doc_index == self.dvs.borrow().offsets.len() {
        self.doc_id = NO_MORE_DOCS;
        break;
      }
      if self.dvs.borrow().offsets[doc_index] > 0 {
        break;
      }
    }
    Ok(self.doc_id)
  }

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

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

impl<D: Borrow<BinaryDVs>> DocValuesIterator for SortingBinaryDocValues<D> {
  fn advance_exact(&mut self, _target: i32) -> Result<bool> {
    Err(LuceneError::unsupported_operation("use next_doc instead"))
  }
}

impl<D: Borrow<BinaryDVs>> BinaryDocValues for SortingBinaryDocValues<D> {
  type Value<'a>
    = crate::core::index::BytesRefValueEnum<'a>
  where
    Self: 'a;

  fn binary_value(&self) -> Result<Self::Value<'_>> {
    let idx = self.dvs.borrow().offsets[self.doc_id as usize] as usize - 1;
    self.dvs.borrow().values.get(idx)
  }
}

pub struct BinaryDVs {
  pub(crate) offsets: Vec<i32>,
  pub(crate) values: BytesRefArray,
}

impl BinaryDVs {
  pub(crate) fn new<DM, T>(max_doc: usize, sort_map: &DM, old_values: &mut T) -> Result<Self>
  where
    DM: DocMap,
    T: BinaryDocValues,
  {
    let mut offsets = vec![0; max_doc];
    let counter = Arc::new(AtomicCounter::new());
    let mut values = BytesRefArray::new(counter)?;
    let mut offset = 1; // 0 means missing, and there is at most one value per doc.
    let mut doc_id;
    loop {
      doc_id = old_values.next_doc()?;
      if doc_id == NO_MORE_DOCS {
        break;
      }
      let new_doc = sort_map.old_to_new(doc_id)?.try_convert()?;
      let val = old_values.binary_value()?;
      values.append(&val.as_bytes_ref())?;
      offsets[new_doc] = offset;
      offset += 1;
    }
    Ok(BinaryDVs { offsets, values })
  }
}

use crate::core::util::array_util::ArrayUtil;

// 4 kB block sizes for PagedBytes storage:
const BLOCK_BITS: usize = 12;
const MAX_LENGTH: usize = ArrayUtil::MAX_ARRAY_LENGTH;