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
/*
 * 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::analysis::analyzer::Analyzer;
use crate::core::analysis::reader::ReaderEnum;
use crate::core::document::field::FieldDataEnum::Dummy;
use crate::core::document::field::{Field, FieldBase, FieldDataEnum};
use crate::core::document::field_type::FieldType;
use crate::core::document::invertable_field::InvertableType;
use crate::core::document::range_field_query::{QueryType, RangeFieldQuery, RangeFieldQueryBase};
use crate::core::index::BinaryValueEnum;
use crate::core::index::BytesRef;
use crate::core::index::indexable_field::{
  IndexableField, IndexingTokenStream, ReusedIndexingTokenStream,
};
use crate::core::index::indexable_field_type::IndexableFieldType;
use crate::core::util::CoreHelper;
use crate::core::util::error::lucene_error::LuceneError;
use crate::core::util::error::lucene_error::Result;
use crate::core::util::number::Number;
use crate::core::util::numeric_utils::NumericUtils;
use std::borrow::Cow;
use std::fmt;
/// An indexed Double Range field.
///
/// This field indexes dimensional ranges defined as min/max pairs. It supports up to a maximum of
/// 4 dimensions (indexed as 8 numeric values). With 1 dimension representing a single double range,
/// 2 dimensions representing a bounding box, 3 dimensions a bounding cube, and 4 dimensions a
/// tesseract.
///
/// Multiple values for the same field in one document is supported, and open ended ranges can be
/// defined using `f64::NEG_INFINITY` and `f64::INFINITY`.
///
/// This field defines the following static factory methods for common search operations over
/// double ranges:
///
/// - [`Self::new_intersects_query`] matches ranges that intersect the defined search range.
/// - [`Self::new_within_query`] matches ranges that are within the defined search range.
/// - [`Self::new_contains_query`] matches ranges that contain the defined search range.
pub struct DoubleRange {
  parent_field: Field,
}
pub const BYTES: usize = std::mem::size_of::<f64>();

impl DoubleRange {
  /// Lower and upper bounds may independently use arrays, vectors, or slices.
  pub fn new<T, L, U>(name: T, min: L, max: U) -> Result<Self>
  where
    T: Into<Cow<'static, str>>,
    L: AsRef<[f64]>,
    U: AsRef<[f64]>,
  {
    let min = min.as_ref();
    let field_type = Self::get_type(min.len())?;
    let mut parent_field = Field::new(name, Dummy(()), field_type);
    Self::set_range_values_internal(&mut parent_field, min, max.as_ref())?;
    Ok(DoubleRange { parent_field })
  }

  fn get_type(dimensions: usize) -> Result<FieldType> {
    if dimensions > 4 {
      return Err(LuceneError::illegal_argument(
        "DoubleRange does not support greater than 4 dimensions",
      ));
    }
    let mut ft = FieldType::new();
    ft.set_dimensions(dimensions * 2, BYTES)?;
    ft.freeze();
    Ok(ft)
  }

  /// Updates the range using independently supplied arrays, vectors, or slices.
  pub fn set_range_values<L, U>(&mut self, min: L, max: U) -> Result<()>
  where
    L: AsRef<[f64]>,
    U: AsRef<[f64]>,
  {
    Self::set_range_values_internal(&mut self.parent_field, min.as_ref(), max.as_ref())
  }

  fn set_range_values_internal(parent_field: &mut Field, min: &[f64], max: &[f64]) -> Result<()> {
    check_args(min, max)?;

    let dims = parent_field.field_type().point_dimension_count();
    if min.len() * 2 != dims || max.len() * 2 != dims {
      return Err(LuceneError::illegal_argument(format!(
        "field (name={}) uses {} dimensions; cannot change to (incoming) {} dimensions",
        parent_field.name(),
        dims / 2,
        min.len()
      )));
    }

    let bytes = match &mut parent_field.fields_data {
      FieldDataEnum::Binary(b) => &mut b.bytes,
      FieldDataEnum::Dummy(_) => {
        let new_bytes = vec![0u8; BYTES * 2 * min.len()];
        parent_field.fields_data = BytesRef::from_bytes(new_bytes).into();
        match &mut parent_field.fields_data {
          FieldDataEnum::Binary(b) => &mut b.bytes,
          _ => return Err(LuceneError::illegal_state("should not be here")),
        }
      },
      _ => Err(LuceneError::illegal_state(
        "Unsupported FieldDataEnum variant",
      ))?,
    };

    verify_and_encode(min, max, bytes)
  }

  pub fn get_min(&self, dimension: usize) -> Result<f64> {
    CoreHelper::check_index(
      dimension,
      self.parent_field.field_type().point_dimension_count() / 2,
    )?;
    match &self.parent_field.fields_data {
      FieldDataEnum::Binary(b) => Ok(decode_min(&b.bytes, dimension)),
      _ => Err(LuceneError::illegal_argument(
        "Unsupported FieldDataEnum variant",
      )),
    }
  }

  pub fn get_max(&self, dimension: usize) -> Result<f64> {
    CoreHelper::check_index(
      dimension,
      self.parent_field.field_type().point_dimension_count() / 2,
    )?;
    match &self.parent_field.fields_data {
      FieldDataEnum::Binary(b) => Ok(decode_max(&b.bytes, dimension)),
      _ => Err(LuceneError::illegal_argument(
        "Unsupported FieldDataEnum variant",
      )),
    }
  }

  /// Create a query for matching indexed ranges that intersect the defined range.
  ///
  /// # Parameters
  /// - `field`: field name.
  /// - `min`: array of min values. Accepts `f64::NEG_INFINITY`.
  /// - `max`: array of max values. Accepts `f64::INFINITY`.
  ///
  /// # Returns
  /// Query for matching intersecting ranges (overlap, within, or contains).
  ///
  /// # Errors
  /// Returns an error if `min` or `max` is invalid.
  pub fn new_intersects_query<T, L, U>(field: T, min: L, max: U) -> Result<RangeFieldQuery>
  where
    T: Into<String>,
    L: AsRef<[f64]>,
    U: AsRef<[f64]>,
  {
    Self::new_relation_query(field, min, max, QueryType::Intersects)
  }

  /// Create a query for matching indexed ranges that contain the defined range.
  ///
  /// # Parameters
  /// - `field`: field name.
  /// - `min`: array of min values. Accepts `BitUtil::F64_MIN_VALUE`.
  /// - `max`: array of max values. Accepts `f64::MAX`.
  ///
  /// # Returns
  /// Query for matching ranges that contain the defined range.
  ///
  /// # Errors
  /// Returns an error if `min` or `max` is invalid.
  pub fn new_contains_query<T, L, U>(field: T, min: L, max: U) -> Result<RangeFieldQuery>
  where
    T: Into<String>,
    L: AsRef<[f64]>,
    U: AsRef<[f64]>,
  {
    Self::new_relation_query(field, min, max, QueryType::Contains)
  }

  /// Create a query for matching indexed ranges that are within the defined range.
  ///
  /// # Parameters
  /// - `field`: field name.
  /// - `min`: array of min values. Accepts `BitUtil::F64_MIN_VALUE`.
  /// - `max`: array of max values. Accepts `f64::MAX`.
  ///
  /// # Returns
  /// Query for matching ranges within the defined range.
  ///
  /// # Errors
  /// Returns an error if `min` or `max` is invalid.
  pub fn new_within_query<T, L, U>(field: T, min: L, max: U) -> Result<RangeFieldQuery>
  where
    T: Into<String>,
    L: AsRef<[f64]>,
    U: AsRef<[f64]>,
  {
    Self::new_relation_query(field, min, max, QueryType::Within)
  }

  /// Create a query for matching indexed ranges that cross the defined range. A cross relation is
  /// any set of ranges that are not disjoint and not wholly contained by the query. Effectively,
  /// it is the complement of union(WITHIN, DISJOINT).
  ///
  /// # Parameters
  /// - `field`: field name.
  /// - `min`: array of min values. Accepts `BitUtil::F64_MIN_VALUE`.
  /// - `max`: array of max values. Accepts `f64::MAX`.
  ///
  /// # Returns
  /// Query for matching ranges that cross the defined range.
  ///
  /// # Errors
  /// Returns an error if `min` or `max` is invalid.
  pub fn new_crosses_query<T, L, U>(field: T, min: L, max: U) -> Result<RangeFieldQuery>
  where
    T: Into<String>,
    L: AsRef<[f64]>,
    U: AsRef<[f64]>,
  {
    Self::new_relation_query(field, min, max, QueryType::Crosses)
  }

  /// Helper method for creating the desired relational query.
  fn new_relation_query<T, L, U>(
    field: T,
    min: L,
    max: U,
    relation: QueryType,
  ) -> Result<RangeFieldQuery>
  where
    T: Into<String>,
    L: AsRef<[f64]>,
    U: AsRef<[f64]>,
  {
    let min = min.as_ref();
    let max = max.as_ref();
    check_args(min, max)?;
    RangeFieldQuery::new(
      field.into(),
      encode_range(min, max)?,
      min.len(),
      relation,
      DoubleRangeFieldQuery,
    )
  }
}

impl FieldBase for DoubleRange {}

impl IndexableField for DoubleRange {
  fn name(&self) -> &str {
    self.parent_field.name()
  }

  type FieldType<'a>
    = &'a FieldType
  where
    Self: 'a;

  fn field_type(&self) -> Self::FieldType<'_> {
    self.parent_field.field_type()
  }

  fn token_stream<'a, A>(
    &'a mut self,
    analyzer: &'a A,
    reuse_token_stream: &'a mut Option<ReusedIndexingTokenStream>,
  ) -> Result<IndexingTokenStream<'a>>
  where
    A: Analyzer,
  {
    self.parent_field.token_stream(analyzer, reuse_token_stream)
  }

  fn binary_value(&self) -> Result<Option<BinaryValueEnum<'_>>> {
    self.parent_field.binary_value()
  }

  fn take_binary_value(&mut self) -> Result<Option<BytesRef<Vec<u8>>>> {
    self.parent_field.take_binary_value()
  }

  fn string_value(&self) -> Result<Option<Cow<'_, str>>> {
    self.parent_field.string_value()
  }

  fn take_string_value(&mut self) -> Result<Option<String>> {
    self.parent_field.take_string_value()
  }

  fn take_reader_value(&mut self) -> Result<Option<ReaderEnum>> {
    todo!()
  }

  fn numeric_value(&self) -> Result<Option<Number>> {
    Err(LuceneError::illegal_argument(
      "cannot convert DoubleRange to a single numeric value",
    ))
  }

  type StoredValue<'a>
    = &'a FieldDataEnum
  where
    Self: 'a;

  fn stored_value(&self) -> Result<Option<Self::StoredValue<'_>>> {
    self.parent_field.stored_value()
  }

  fn invertable_type(&self) -> &InvertableType {
    self.parent_field.invertable_type()
  }
}

impl fmt::Display for DoubleRange {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "DoubleRange <{}: ", self.parent_field.name())?;

    let dims = self.parent_field.field_type().point_dimension_count() / 2;

    match &self.parent_field.fields_data {
      FieldDataEnum::Binary(bytes) => {
        for dim in 0..dims {
          if dim > 0 {
            write!(f, " ")?;
          }
          let min = decode_min(&bytes.bytes, dim);
          let max = decode_max(&bytes.bytes, dim);
          write!(f, "[{} : {}]", min, max)?;
        }
      },
      _ => {
        write!(f, "Unsupported FieldDataEnum variant")?;
      },
    }

    write!(f, ">")
  }
}

/// Validates the arguments.
fn check_args(min: &[f64], max: &[f64]) -> Result<()> {
  if min.is_empty() || max.is_empty() {
    return Err(LuceneError::illegal_argument(
      "min/max range values cannot be null or empty",
    ));
  }
  if min.len() != max.len() {
    return Err(LuceneError::illegal_argument("min/max ranges must agree"));
  }
  if min.len() > 4 {
    return Err(LuceneError::illegal_argument(
      "DoubleRange does not support greater than 4 dimensions",
    ));
  }
  Ok(())
}

/// Encodes the min, max ranges into a byte array.
pub(crate) fn encode_range(min: &[f64], max: &[f64]) -> Result<Vec<u8>> {
  check_args(min, max)?;
  let mut bytes = vec![0u8; BYTES * 2 * min.len()];
  verify_and_encode(min, max, &mut bytes)?;
  Ok(bytes)
}

/// Encodes the ranges into a sortable byte array (`f64::NAN` not allowed).
///
/// Example for 4 dimensions (8 bytes per dimension value):
/// minD1 ... minD4 | maxD1 ... maxD4
pub fn verify_and_encode(min: &[f64], max: &[f64], bytes: &mut [u8]) -> Result<()> {
  for d in 0..min.len() {
    let i = d * BYTES;
    let j = min.len() * BYTES + d * BYTES;

    if min[d].is_nan() {
      return Err(LuceneError::illegal_argument(
        "invalid min value (NaN) in DoubleRange",
      ));
    }
    if max[d].is_nan() {
      return Err(LuceneError::illegal_argument(
        "invalid max value (NaN) in DoubleRange",
      ));
    }
    if min[d] > max[d] {
      return Err(LuceneError::illegal_argument(format!(
        "min value ({}) is greater than max value ({})",
        min[d], max[d]
      )));
    }

    encode(min[d], bytes, i);
    encode(max[d], bytes, j);
  }

  Ok(())
}

/// Encodes the given value into the byte array at the defined offset.
fn encode(val: f64, bytes: &mut [u8], offset: usize) {
  NumericUtils::long_to_sortable_bytes(NumericUtils::double_to_sortable_long(val), bytes, offset);
}

fn decode_min(bytes: &[u8], dimension: usize) -> f64 {
  let offset = dimension * BYTES;
  NumericUtils::sortable_long_to_double(NumericUtils::sortable_bytes_to_long(bytes, offset))
}

fn decode_max(bytes: &[u8], dimension: usize) -> f64 {
  let offset = bytes.len() / 2 + dimension * BYTES;
  NumericUtils::sortable_long_to_double(NumericUtils::sortable_bytes_to_long(bytes, offset))
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct DoubleRangeFieldQuery;

impl RangeFieldQueryBase for DoubleRangeFieldQuery {
  fn to_string(&self, value: &[u8], dimension: usize) -> Result<String> {
    Ok(to_string(value, dimension))
  }
}

fn to_string(ranges: &[u8], dimension: usize) -> String {
  format!(
    "[{} : {}]",
    decode_min(ranges, dimension),
    decode_max(ranges, dimension)
  )
}