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
/*
 * 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::geo::geo_encoding_utils::GeoEncodingUtils;
use crate::core::geo::rectangle::Rectangle;
use crate::core::index::point_values::{IntersectVisitor, PointTree, PointValues, Relation};
use crate::core::util::bit_util::BitUtil;
use crate::core::util::bits::Bits;
use crate::core::util::clone::TryClone;
use crate::core::util::error::lucene_error::{LuceneError, Result};
use crate::core::util::{CoreHelper, SloppyMath};
use std::borrow::Cow;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::fmt::{Display, Formatter};

#[allow(dead_code)] // for quick search
pub(crate) struct NearestNeighbor;
/// # Parameters
///
/// - `distance_sort_key`: The closest distance from a point in this cell to the query point,
///   computed as a sort key through [`SloppyMath::haversin_sort_key`]. Note that this is an
///   approximation to the closest distance, and there could be a point in the cell that is
///   closer.
#[derive(Clone)]
pub(crate) struct Cell<PT> {
  index: PT,
  reader_index: usize,
  min_packed: Vec<u8>,
  max_packed: Vec<u8>,
  distance_sort_key: f64,
}

impl<PT> Cell<PT> {
  pub(crate) fn new(
    index: PT,
    reader_index: usize,
    min_packed: Vec<u8>,
    max_packed: Vec<u8>,
    distance_sort_key: f64,
  ) -> Self {
    Self {
      index,
      reader_index,
      min_packed,
      max_packed,
      distance_sort_key,
    }
  }
}

impl<PT> PartialEq for Cell<PT> {
  fn eq(&self, other: &Self) -> bool {
    CoreHelper::compare_f64(self.distance_sort_key, other.distance_sort_key).is_eq()
  }
}

impl<PT> Eq for Cell<PT> {}

impl<PT> PartialOrd for Cell<PT> {
  fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
    Some(self.cmp(other))
  }
}

impl<PT> Ord for Cell<PT> {
  fn cmp(&self, other: &Self) -> std::cmp::Ordering {
    // BinaryHeap pops greatest first. We want closest cells first (smallest distance_sort_key).
    // Reverse comparison so smaller distance_sort_key is "greater" and pops first.
    CoreHelper::compare_f64(other.distance_sort_key, self.distance_sort_key)
  }
}
/// Holds one hit from [`NearestNeighbor::nearest`]
#[derive(Default, Clone)]
pub struct NearestHit {
  pub doc_id: i32,

  /// The distance from the hit to the query point, computed as a sort key through
  /// [`SloppyMath::haversin_sort_key`].
  pub distance_sort_key: f64,
}

impl Display for NearestHit {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    write!(
      f,
      "NearestHit(docID={} distanceSortKey={})",
      self.doc_id, self.distance_sort_key
    )
  }
}
impl PartialEq for NearestHit {
  fn eq(&self, other: &Self) -> bool {
    self.doc_id == other.doc_id
      && CoreHelper::compare_f64(self.distance_sort_key, other.distance_sort_key).is_eq()
  }
}

impl Eq for NearestHit {}

impl PartialOrd for NearestHit {
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl Ord for NearestHit {
  fn cmp(&self, other: &Self) -> Ordering {
    // BinaryHeap pops the greatest item first.
    // We want the heap top to be the current worst hit:
    // larger distance_sort_key is worse; if tied, larger doc_id is worse.
    match CoreHelper::compare_f64(self.distance_sort_key, other.distance_sort_key) {
      Ordering::Equal => self.doc_id.cmp(&other.doc_id),
      cmp => cmp,
    }
  }
}
struct NearestVisitor<'a, B>
where
  B: ?Sized,
{
  cur_doc_base: i32,
  cur_live_docs: Option<&'a B>,
  top_n: usize,
  hit_queue: &'a mut BinaryHeap<NearestHit>,
  point_lat: f64,
  point_lon: f64,
  set_bottom_counter: i32,

  min_lon: f64,
  max_lon: f64,
  min_lat: f64,
  max_lat: f64,

  // second set of longitude ranges to check (for cross-dateline case)
  min_lon2: f64,
}

impl<'a, B> NearestVisitor<'a, B>
where
  B: ?Sized,
{
  fn new(
    hit_queue: &'a mut BinaryHeap<NearestHit>,
    top_n: usize,
    point_lat: f64,
    point_lon: f64,
  ) -> Self {
    Self {
      cur_doc_base: 0,
      cur_live_docs: None,
      top_n,
      hit_queue,
      point_lat,
      point_lon,
      set_bottom_counter: 0,
      min_lon: f64::NEG_INFINITY,
      max_lon: f64::INFINITY,
      min_lat: f64::NEG_INFINITY,
      max_lat: f64::INFINITY,
      min_lon2: f64::INFINITY,
    }
  }

  fn maybe_update_bbox(&mut self) -> Result<()> {
    if self.set_bottom_counter < 1024 || (self.set_bottom_counter & 0x3F) == 0x3F {
      let hit = self
        .hit_queue
        .peek()
        .ok_or_else(|| LuceneError::unsupported_operation("hitQueue is empty"))?;
      let box_ = Rectangle::from_point_distance(
        self.point_lat,
        self.point_lon,
        SloppyMath::haversin_meters_from_sort_key(hit.distance_sort_key),
      )?;

      self.min_lat = box_.min_lat;
      self.max_lat = box_.max_lat;
      if box_.crosses_dateline() {
        // box1
        self.min_lon = f64::NEG_INFINITY;
        self.max_lon = box_.max_lon;
        // box2
        self.min_lon2 = box_.min_lon;
      } else {
        self.min_lon = box_.min_lon;
        self.max_lon = box_.max_lon;
        // disable box2
        self.min_lon2 = f64::INFINITY;
      }
    }

    self.set_bottom_counter += 1;
    Ok(())
  }
}

impl<B> IntersectVisitor for NearestVisitor<'_, B>
where
  B: Bits + ?Sized,
{
  fn visit(&mut self, _doc_id: i32) -> Result<()> {
    Err(LuceneError::unsupported_operation(""))
  }

  fn visit_with_packed_value(&mut self, doc_id: i32, packed_value: &[u8]) -> Result<()> {
    if let Some(live_docs) = self.cur_live_docs
      && !live_docs.get(doc_id as usize)?
    {
      return Ok(());
    }

    let doc_latitude = GeoEncodingUtils::decode_latitude_from_bytes(packed_value, 0);
    let doc_longitude =
      GeoEncodingUtils::decode_longitude_from_bytes(packed_value, BitUtil::INT_BYTES);

    // test bounding box
    if doc_latitude < self.min_lat || doc_latitude > self.max_lat {
      return Ok(());
    }
    if (doc_longitude < self.min_lon || doc_longitude > self.max_lon)
      && doc_longitude < self.min_lon2
    {
      return Ok(());
    }

    // Use the haversin sort key when comparing hits, as it is faster to compute than the true
    // distance.
    let distance_sort_key =
      SloppyMath::haversin_sort_key(self.point_lat, self.point_lon, doc_latitude, doc_longitude);

    let full_doc_id = self.cur_doc_base + doc_id;

    if self.hit_queue.len() == self.top_n {
      // queue already full
      let hit = self
        .hit_queue
        .peek()
        .ok_or_else(|| LuceneError::unsupported_operation("hitQueue is empty"))?;

      // we don't collect docs in order here, so we must also test the tie-break case ourselves:
      if CoreHelper::compare_f64(distance_sort_key, hit.distance_sort_key).is_lt()
        || (CoreHelper::compare_f64(distance_sort_key, hit.distance_sort_key).is_eq()
          && full_doc_id < hit.doc_id)
      {
        let mut hit = self
          .hit_queue
          .pop()
          .ok_or_else(|| LuceneError::unsupported_operation("hitQueue is empty"))?;
        hit.doc_id = full_doc_id;
        hit.distance_sort_key = distance_sort_key;
        self.hit_queue.push(hit);
        self.maybe_update_bbox()?;
      }
    } else {
      let hit = NearestHit {
        doc_id: full_doc_id,
        distance_sort_key,
      };
      self.hit_queue.push(hit);
    }

    Ok(())
  }

  fn compare(&self, min_packed_value: &[u8], max_packed_value: &[u8]) -> Result<Relation> {
    let cell_min_lat = GeoEncodingUtils::decode_latitude_from_bytes(min_packed_value, 0);
    let cell_min_lon =
      GeoEncodingUtils::decode_longitude_from_bytes(min_packed_value, BitUtil::INT_BYTES);
    let cell_max_lat = GeoEncodingUtils::decode_latitude_from_bytes(max_packed_value, 0);
    let cell_max_lon =
      GeoEncodingUtils::decode_longitude_from_bytes(max_packed_value, BitUtil::INT_BYTES);

    if cell_max_lat < self.min_lat
      || self.max_lat < cell_min_lat
      || ((cell_max_lon < self.min_lon || self.max_lon < cell_min_lon)
        && cell_max_lon < self.min_lon2)
    {
      // this cell is outside our search bbox; don't bother exploring any more
      return Ok(Relation::CellOutsideQuery);
    }

    Ok(Relation::CellCrossesQuery)
  }
}
pub fn nearest<PV, B>(
  point_lat: f64,
  point_lon: f64,
  readers: &[PV],
  live_docs: &[Option<B>],
  doc_bases: &[i32],
  n: usize,
) -> Result<Vec<NearestHit>>
where
  PV: PointValues,
  B: Bits,
{
  // Holds all cells, sorted by closest to the point:
  let mut cell_queue = BinaryHeap::with_capacity(readers.len());

  let mut hit_queue = BinaryHeap::new();
  let mut visitor = NearestVisitor::new(&mut hit_queue, n, point_lat, point_lon);

  // Add root cell for each reader into the queue:
  for (i, reader) in readers.iter().enumerate() {
    let min_packed_value = reader
      .get_min_packed_value()?
      .ok_or_else(|| LuceneError::unsupported_operation("no points?"))?
      .into_owned();
    let max_packed_value = reader
      .get_max_packed_value()?
      .ok_or_else(|| LuceneError::unsupported_operation("no points?"))?
      .into_owned();
    let index_tree = reader.get_point_tree()?;
    let distance_sort_key = approx_best_distance_from_packed(
      min_packed_value.as_ref(),
      max_packed_value.as_ref(),
      point_lat,
      point_lon,
    );
    cell_queue.push(Cell::new(
      index_tree,
      i,
      min_packed_value,
      max_packed_value,
      distance_sort_key,
    ));
  }

  while let Some(mut cell) = cell_queue.pop() {
    if visitor.compare(&cell.min_packed, &cell.max_packed)? == Relation::CellOutsideQuery {
      continue;
    }

    if !cell.index.move_to_child()? {
      // Leaf block: visit all points and possibly collect them:
      visitor.cur_doc_base = doc_bases[cell.reader_index];
      visitor.cur_live_docs = live_docs[cell.reader_index].as_ref();
      cell.index.visit_doc_values(&mut visitor)?;
    } else {
      // Non-leaf block: split into two cells and put them back into the queue:

      // we must clone the index so that we can recurse left and right "concurrently":
      let new_index = cell.index.try_clone()?;

      let min_pv = new_index.get_min_packed_value()?.into_owned();
      let max_pv = new_index.get_max_packed_value()?.into_owned();
      let distance_sort_key =
        approx_best_distance_from_packed(min_pv.as_ref(), max_pv.as_ref(), point_lat, point_lon);
      cell_queue.push(Cell::new(
        new_index,
        cell.reader_index,
        min_pv,
        max_pv,
        distance_sort_key,
      ));

      let move_to_sibling = cell.index.move_to_sibling()?;
      if move_to_sibling {
        match cell.index.get_min_packed_value()? {
          Cow::Borrowed(value) => value.clone_into(&mut cell.min_packed),
          Cow::Owned(value) => cell.min_packed = value,
        }
        match cell.index.get_max_packed_value()? {
          Cow::Borrowed(value) => value.clone_into(&mut cell.max_packed),
          Cow::Owned(value) => cell.max_packed = value,
        }
        let min_pv = cell.min_packed;
        let max_pv = cell.max_packed;
        let distance_sort_key =
          approx_best_distance_from_packed(min_pv.as_ref(), max_pv.as_ref(), point_lat, point_lon);
        cell_queue.push(Cell::new(
          cell.index,
          cell.reader_index,
          min_pv,
          max_pv,
          distance_sort_key,
        ));
      }
    }
  }

  let len = hit_queue.len();
  let mut hits = vec![NearestHit::default(); len];

  for i in (0..len).rev() {
    hits[i] = hit_queue
      .pop()
      .ok_or_else(|| LuceneError::unsupported_operation("hitQueue is empty"))?;
  }
  Ok(hits)
}

// NOTE: incoming args never cross the dateline, since they are a BKD cell
fn approx_best_distance_from_packed(
  min_packed_value: &[u8],
  max_packed_value: &[u8],
  point_lat: f64,
  point_lon: f64,
) -> f64 {
  let min_lat = GeoEncodingUtils::decode_latitude_from_bytes(min_packed_value, 0);
  let min_lon = GeoEncodingUtils::decode_longitude_from_bytes(min_packed_value, BitUtil::INT_BYTES);
  let max_lat = GeoEncodingUtils::decode_latitude_from_bytes(max_packed_value, 0);
  let max_lon = GeoEncodingUtils::decode_longitude_from_bytes(max_packed_value, BitUtil::INT_BYTES);
  approx_best_distance(min_lat, max_lat, min_lon, max_lon, point_lat, point_lon)
}
// NOTE: incoming args never cross the dateline, since they are a BKD cell
fn approx_best_distance(
  min_lat: f64,
  max_lat: f64,
  min_lon: f64,
  max_lon: f64,
  point_lat: f64,
  point_lon: f64,
) -> f64 {
  if point_lat >= min_lat && point_lat <= max_lat && point_lon >= min_lon && point_lon <= max_lon {
    // point is inside the cell!
    return 0.0;
  }

  let d1 = SloppyMath::haversin_sort_key(point_lat, point_lon, min_lat, min_lon);
  let d2 = SloppyMath::haversin_sort_key(point_lat, point_lon, min_lat, max_lon);
  let d3 = SloppyMath::haversin_sort_key(point_lat, point_lon, max_lat, max_lon);
  let d4 = SloppyMath::haversin_sort_key(point_lat, point_lon, max_lat, min_lon);
  CoreHelper::min_f64(CoreHelper::min_f64(d1, d2), CoreHelper::min_f64(d3, d4))
}