mirror of
https://github.com/quickwit-oss/tantivy.git
synced 2026-01-03 07:42:54 +00:00
Compare commits
31 Commits
debug_time
...
simplify
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb6d5acb82 | ||
|
|
4cf911d56a | ||
|
|
0f5cff762f | ||
|
|
6d9a123cf2 | ||
|
|
0f4a47816a | ||
|
|
b062ab2196 | ||
|
|
a9d2f3db23 | ||
|
|
44e03791f9 | ||
|
|
2d23763e9f | ||
|
|
a24ae8d924 | ||
|
|
927dff5262 | ||
|
|
a695edcc95 | ||
|
|
b4b4f3fa73 | ||
|
|
b50e4b7c20 | ||
|
|
f8686ab1ec | ||
|
|
2fe42719d8 | ||
|
|
fadd784a25 | ||
|
|
0e94213af0 | ||
|
|
0da2a2e70d | ||
|
|
0bcdf3cbbf | ||
|
|
8f647b817f | ||
|
|
a86b0df6f4 | ||
|
|
f842da758c | ||
|
|
97ccd6d712 | ||
|
|
cb252a42af | ||
|
|
d9609dd6b6 | ||
|
|
f03667d967 | ||
|
|
10f10a322f | ||
|
|
f757471077 | ||
|
|
21e0adefda | ||
|
|
ea8e6d7b1d |
1
.gitattributes
vendored
1
.gitattributes
vendored
@@ -1 +0,0 @@
|
|||||||
cpp/* linguist-vendored
|
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -9,7 +9,6 @@ target/release
|
|||||||
Cargo.lock
|
Cargo.lock
|
||||||
benchmark
|
benchmark
|
||||||
.DS_Store
|
.DS_Store
|
||||||
cpp/simdcomp/bitpackingbenchmark
|
|
||||||
*.bk
|
*.bk
|
||||||
.idea
|
.idea
|
||||||
trace.dat
|
trace.dat
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ repository = "https://github.com/quickwit-oss/tantivy"
|
|||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
keywords = ["search", "information", "retrieval"]
|
keywords = ["search", "information", "retrieval"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
rust-version = "1.62"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
oneshot = "0.1.3"
|
oneshot = "0.1.3"
|
||||||
@@ -19,11 +20,11 @@ byteorder = "1.4.3"
|
|||||||
crc32fast = "1.3.2"
|
crc32fast = "1.3.2"
|
||||||
once_cell = "1.10.0"
|
once_cell = "1.10.0"
|
||||||
regex = { version = "1.5.5", default-features = false, features = ["std", "unicode"] }
|
regex = { version = "1.5.5", default-features = false, features = ["std", "unicode"] }
|
||||||
tantivy-fst = "0.3.0"
|
tantivy-fst = "0.4.0"
|
||||||
memmap2 = { version = "0.5.3", optional = true }
|
memmap2 = { version = "0.5.3", optional = true }
|
||||||
lz4_flex = { version = "0.9.2", default-features = false, features = ["checked-decode"], optional = true }
|
lz4_flex = { version = "0.9.2", default-features = false, features = ["checked-decode"], optional = true }
|
||||||
brotli = { version = "3.3.4", optional = true }
|
brotli = { version = "3.3.4", optional = true }
|
||||||
zstd = { version = "0.11", optional = true }
|
zstd = { version = "0.11", optional = true, default-features = false }
|
||||||
snap = { version = "1.0.5", optional = true }
|
snap = { version = "1.0.5", optional = true }
|
||||||
tempfile = { version = "3.3.0", optional = true }
|
tempfile = { version = "3.3.0", optional = true }
|
||||||
log = "0.4.16"
|
log = "0.4.16"
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ Distributed search is out of the scope of Tantivy, but if you are looking for th
|
|||||||
|
|
||||||
# Getting started
|
# Getting started
|
||||||
|
|
||||||
Tantivy works on stable Rust (>= 1.27) and supports Linux, macOS, and Windows.
|
Tantivy works on stable Rust and supports Linux, macOS, and Windows.
|
||||||
|
|
||||||
- [Tantivy's simple search example](https://tantivy-search.github.io/examples/basic_search.html)
|
- [Tantivy's simple search example](https://tantivy-search.github.io/examples/basic_search.html)
|
||||||
- [tantivy-cli and its tutorial](https://github.com/quickwit-oss/tantivy-cli) - `tantivy-cli` is an actual command-line interface that makes it easy for you to create a search engine,
|
- [tantivy-cli and its tutorial](https://github.com/quickwit-oss/tantivy-cli) - `tantivy-cli` is an actual command-line interface that makes it easy for you to create a search engine,
|
||||||
@@ -81,9 +81,13 @@ There are many ways to support this project.
|
|||||||
|
|
||||||
We use the GitHub Pull Request workflow: reference a GitHub ticket and/or include a comprehensive commit message when opening a PR.
|
We use the GitHub Pull Request workflow: reference a GitHub ticket and/or include a comprehensive commit message when opening a PR.
|
||||||
|
|
||||||
|
## Minimum supported Rust version
|
||||||
|
|
||||||
|
Tantivy currently requires at least Rust 1.62 or later to compile.
|
||||||
|
|
||||||
## Clone and build locally
|
## Clone and build locally
|
||||||
|
|
||||||
Tantivy compiles on stable Rust but requires `Rust >= 1.27`.
|
Tantivy compiles on stable Rust.
|
||||||
To check out and run tests, you can simply run:
|
To check out and run tests, you can simply run:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -277,7 +277,7 @@ impl BitSet {
|
|||||||
self.tinyset(el / 64u32).contains(el % 64)
|
self.tinyset(el / 64u32).contains(el % 64)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the first non-empty `TinySet` associated to a bucket lower
|
/// Returns the first non-empty `TinySet` associated with a bucket lower
|
||||||
/// or greater than bucket.
|
/// or greater than bucket.
|
||||||
///
|
///
|
||||||
/// Reminder: the tiny set with the bucket `bucket`, represents the
|
/// Reminder: the tiny set with the bucket `bucket`, represents the
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ to get tantivy to fit your use case:
|
|||||||
|
|
||||||
*Example 1* You could for instance use hadoop to build a very large search index in a timely manner, copy all of the resulting segment files in the same directory and edit the `meta.json` to get a functional index.[^2]
|
*Example 1* You could for instance use hadoop to build a very large search index in a timely manner, copy all of the resulting segment files in the same directory and edit the `meta.json` to get a functional index.[^2]
|
||||||
|
|
||||||
*Example 2* You could also disable your merge policy and enforce daily segments. Removing data after one week can then be done very efficiently by just editing the `meta.json` and deleting the files associated to segment `D-7`.
|
*Example 2* You could also disable your merge policy and enforce daily segments. Removing data after one week can then be done very efficiently by just editing the `meta.json` and deleting the files associated with segment `D-7`.
|
||||||
|
|
||||||
## Merging
|
## Merging
|
||||||
|
|
||||||
|
|||||||
@@ -113,7 +113,7 @@ fn main() -> tantivy::Result<()> {
|
|||||||
// on its id.
|
// on its id.
|
||||||
//
|
//
|
||||||
// Note that `tantivy` does nothing to enforce the idea that
|
// Note that `tantivy` does nothing to enforce the idea that
|
||||||
// there is only one document associated to this id.
|
// there is only one document associated with this id.
|
||||||
//
|
//
|
||||||
// Also you might have noticed that we apply the delete before
|
// Also you might have noticed that we apply the delete before
|
||||||
// having committed. This does not matter really...
|
// having committed. This does not matter really...
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ fn main() -> tantivy::Result<()> {
|
|||||||
// A segment contains different data structure.
|
// A segment contains different data structure.
|
||||||
// Inverted index stands for the combination of
|
// Inverted index stands for the combination of
|
||||||
// - the term dictionary
|
// - the term dictionary
|
||||||
// - the inverted lists associated to each terms and their positions
|
// - the inverted lists associated with each terms and their positions
|
||||||
let inverted_index = segment_reader.inverted_index(title)?;
|
let inverted_index = segment_reader.inverted_index(title)?;
|
||||||
|
|
||||||
// A `Term` is a text token associated with a field.
|
// A `Term` is a text token associated with a field.
|
||||||
@@ -105,7 +105,7 @@ fn main() -> tantivy::Result<()> {
|
|||||||
// A segment contains different data structure.
|
// A segment contains different data structure.
|
||||||
// Inverted index stands for the combination of
|
// Inverted index stands for the combination of
|
||||||
// - the term dictionary
|
// - the term dictionary
|
||||||
// - the inverted lists associated to each terms and their positions
|
// - the inverted lists associated with each terms and their positions
|
||||||
let inverted_index = segment_reader.inverted_index(title)?;
|
let inverted_index = segment_reader.inverted_index(title)?;
|
||||||
|
|
||||||
// This segment posting object is like a cursor over the documents matching the term.
|
// This segment posting object is like a cursor over the documents matching the term.
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ rand = {version="0.8.3", optional= true}
|
|||||||
fastdivide = "0.4"
|
fastdivide = "0.4"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
itertools = { version = "0.10.3" }
|
itertools = { version = "0.10.3" }
|
||||||
measure_time = { version="0.8.2" }
|
measure_time = { version="0.8.2", optional=true}
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
more-asserts = "0.3.0"
|
more-asserts = "0.3.0"
|
||||||
@@ -25,7 +25,7 @@ proptest = "1.0.0"
|
|||||||
rand = "0.8.3"
|
rand = "0.8.3"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
bin = ["prettytable-rs", "rand"]
|
bin = ["prettytable-rs", "rand", "measure_time"]
|
||||||
default = ["bin"]
|
default = ["bin"]
|
||||||
unstable = []
|
unstable = []
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use std::ops::RangeInclusive;
|
|||||||
use tantivy_bitpacker::minmax;
|
use tantivy_bitpacker::minmax;
|
||||||
|
|
||||||
pub trait Column<T: PartialOrd = u64>: Send + Sync {
|
pub trait Column<T: PartialOrd = u64>: Send + Sync {
|
||||||
/// Return the value associated to the given idx.
|
/// Return the value associated with the given idx.
|
||||||
///
|
///
|
||||||
/// This accessor should return as fast as possible.
|
/// This accessor should return as fast as possible.
|
||||||
///
|
///
|
||||||
|
|||||||
@@ -312,7 +312,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn estimation_test_bad_interpolation_case_monotonically_increasing() {
|
fn estimation_test_bad_interpolation_case_monotonically_increasing() {
|
||||||
let mut data: Vec<u64> = (200..=20000_u64).collect();
|
let mut data: Vec<u64> = (201..=20000_u64).collect();
|
||||||
data.push(1_000_000);
|
data.push(1_000_000);
|
||||||
let data: VecColumn = data.as_slice().into();
|
let data: VecColumn = data.as_slice().into();
|
||||||
|
|
||||||
|
|||||||
@@ -68,29 +68,37 @@ impl Line {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Same as train, but the intercept is only estimated from provided sample positions
|
// Same as train, but the intercept is only estimated from provided sample positions
|
||||||
pub fn estimate(ys: &dyn Column, sample_positions: &[u64]) -> Self {
|
pub fn estimate(sample_positions_and_values: &[(u64, u64)]) -> Self {
|
||||||
|
let first_val = sample_positions_and_values[0].1;
|
||||||
|
let last_val = sample_positions_and_values[sample_positions_and_values.len() - 1].1;
|
||||||
|
let num_vals = sample_positions_and_values[sample_positions_and_values.len() - 1].0 + 1;
|
||||||
Self::train_from(
|
Self::train_from(
|
||||||
ys,
|
first_val,
|
||||||
sample_positions
|
last_val,
|
||||||
.iter()
|
num_vals,
|
||||||
.cloned()
|
sample_positions_and_values.iter().cloned(),
|
||||||
.map(|pos| (pos, ys.get_val(pos))),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Intercept is only computed from provided positions
|
// Intercept is only computed from provided positions
|
||||||
fn train_from(ys: &dyn Column, positions_and_values: impl Iterator<Item = (u64, u64)>) -> Self {
|
fn train_from(
|
||||||
let num_vals = if let Some(num_vals) = NonZeroU64::new(ys.num_vals() - 1) {
|
first_val: u64,
|
||||||
num_vals
|
last_val: u64,
|
||||||
|
num_vals: u64,
|
||||||
|
positions_and_values: impl Iterator<Item = (u64, u64)>,
|
||||||
|
) -> Self {
|
||||||
|
// TODO replace with let else
|
||||||
|
let idx_last_val = if let Some(idx_last_val) = NonZeroU64::new(num_vals - 1) {
|
||||||
|
idx_last_val
|
||||||
} else {
|
} else {
|
||||||
return Line::default();
|
return Line::default();
|
||||||
};
|
};
|
||||||
|
|
||||||
let y0 = ys.get_val(0);
|
let y0 = first_val;
|
||||||
let y1 = ys.get_val(num_vals.get());
|
let y1 = last_val;
|
||||||
|
|
||||||
// We first independently pick our slope.
|
// We first independently pick our slope.
|
||||||
let slope = compute_slope(y0, y1, num_vals);
|
let slope = compute_slope(y0, y1, idx_last_val);
|
||||||
|
|
||||||
// We picked our slope. Note that it does not have to be perfect.
|
// We picked our slope. Note that it does not have to be perfect.
|
||||||
// Now we need to compute the best intercept.
|
// Now we need to compute the best intercept.
|
||||||
@@ -138,8 +146,12 @@ impl Line {
|
|||||||
/// This function is only invariable by translation if all of the
|
/// This function is only invariable by translation if all of the
|
||||||
/// `ys` are packaged into half of the space. (See heuristic below)
|
/// `ys` are packaged into half of the space. (See heuristic below)
|
||||||
pub fn train(ys: &dyn Column) -> Self {
|
pub fn train(ys: &dyn Column) -> Self {
|
||||||
|
let first_val = ys.iter().next().unwrap();
|
||||||
|
let last_val = ys.iter().nth(ys.num_vals() as usize - 1).unwrap();
|
||||||
Self::train_from(
|
Self::train_from(
|
||||||
ys,
|
first_val,
|
||||||
|
last_val,
|
||||||
|
ys.num_vals(),
|
||||||
ys.iter().enumerate().map(|(pos, val)| (pos as u64, val)),
|
ys.iter().enumerate().map(|(pos, val)| (pos as u64, val)),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -126,18 +126,20 @@ impl FastFieldCodec for LinearCodec {
|
|||||||
return None; // disable compressor for this case
|
return None; // disable compressor for this case
|
||||||
}
|
}
|
||||||
|
|
||||||
// let's sample at 0%, 5%, 10% .. 95%, 100%
|
let limit_num_vals = column.num_vals().min(100_000);
|
||||||
let num_vals = column.num_vals() as f32 / 100.0;
|
|
||||||
let sample_positions = (0..20)
|
|
||||||
.map(|pos| (num_vals * pos as f32 * 5.0) as u64)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
let line = Line::estimate(column, &sample_positions);
|
let num_samples = 100;
|
||||||
|
let step_size = (limit_num_vals / num_samples).max(1); // 20 samples
|
||||||
|
let mut sample_positions_and_values: Vec<_> = Vec::new();
|
||||||
|
for (pos, val) in column.iter().enumerate().step_by(step_size as usize) {
|
||||||
|
sample_positions_and_values.push((pos as u64, val));
|
||||||
|
}
|
||||||
|
|
||||||
let estimated_bit_width = sample_positions
|
let line = Line::estimate(&sample_positions_and_values);
|
||||||
|
|
||||||
|
let estimated_bit_width = sample_positions_and_values
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|pos| {
|
.map(|(pos, actual_value)| {
|
||||||
let actual_value = column.get_val(pos);
|
|
||||||
let interpolated_val = line.eval(pos as u64);
|
let interpolated_val = line.eval(pos as u64);
|
||||||
actual_value.wrapping_sub(interpolated_val)
|
actual_value.wrapping_sub(interpolated_val)
|
||||||
})
|
})
|
||||||
@@ -146,6 +148,7 @@ impl FastFieldCodec for LinearCodec {
|
|||||||
.max()
|
.max()
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
// Extrapolate to whole column
|
||||||
let num_bits = (estimated_bit_width as u64 * column.num_vals() as u64) + 64;
|
let num_bits = (estimated_bit_width as u64 * column.num_vals() as u64) + 64;
|
||||||
let num_bits_uncompressed = 64 * column.num_vals();
|
let num_bits_uncompressed = 64 * column.num_vals();
|
||||||
Some(num_bits as f32 / num_bits_uncompressed as f32)
|
Some(num_bits as f32 / num_bits_uncompressed as f32)
|
||||||
|
|||||||
42
fastfield_codecs/src/monotonic_mapping_u128.rs
Normal file
42
fastfield_codecs/src/monotonic_mapping_u128.rs
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
use std::net::{IpAddr, Ipv6Addr};
|
||||||
|
|
||||||
|
pub trait MonotonicallyMappableToU128: 'static + PartialOrd + Copy + Send + Sync {
|
||||||
|
/// Converts a value to u128.
|
||||||
|
///
|
||||||
|
/// Internally all fast field values are encoded as u64.
|
||||||
|
fn to_u128(self) -> u128;
|
||||||
|
|
||||||
|
/// Converts a value from u128
|
||||||
|
///
|
||||||
|
/// Internally all fast field values are encoded as u64.
|
||||||
|
/// **Note: To be used for converting encoded Term, Posting values.**
|
||||||
|
fn from_u128(val: u128) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonotonicallyMappableToU128 for u128 {
|
||||||
|
fn to_u128(self) -> u128 {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_u128(val: u128) -> Self {
|
||||||
|
val
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonotonicallyMappableToU128 for IpAddr {
|
||||||
|
fn to_u128(self) -> u128 {
|
||||||
|
ip_to_u128(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_u128(val: u128) -> Self {
|
||||||
|
IpAddr::from(val.to_be_bytes())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ip_to_u128(ip_addr: IpAddr) -> u128 {
|
||||||
|
let ip_addr_v6: Ipv6Addr = match ip_addr {
|
||||||
|
IpAddr::V4(v4) => v4.to_ipv6_mapped(),
|
||||||
|
IpAddr::V6(v6) => v6,
|
||||||
|
};
|
||||||
|
u128::from_be_bytes(ip_addr_v6.octets())
|
||||||
|
}
|
||||||
@@ -23,8 +23,7 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
use common::{BinarySerializable, VInt};
|
use common::{BinarySerializable, VInt};
|
||||||
use fastdivide::DividerU64;
|
use fastdivide::DividerU64;
|
||||||
use log::{trace, warn};
|
use log::warn;
|
||||||
use measure_time::trace_time;
|
|
||||||
use ownedbytes::OwnedBytes;
|
use ownedbytes::OwnedBytes;
|
||||||
|
|
||||||
use crate::bitpacked::BitpackedCodec;
|
use crate::bitpacked::BitpackedCodec;
|
||||||
@@ -184,7 +183,6 @@ fn detect_codec(
|
|||||||
) -> Option<FastFieldCodecType> {
|
) -> Option<FastFieldCodecType> {
|
||||||
let mut estimations = Vec::new();
|
let mut estimations = Vec::new();
|
||||||
for &codec in codecs {
|
for &codec in codecs {
|
||||||
trace_time!("estimate time for codec: {:?}", codec);
|
|
||||||
let estimation_opt = match codec {
|
let estimation_opt = match codec {
|
||||||
FastFieldCodecType::Bitpacked => BitpackedCodec::estimate(&column),
|
FastFieldCodecType::Bitpacked => BitpackedCodec::estimate(&column),
|
||||||
FastFieldCodecType::Linear => LinearCodec::estimate(&column),
|
FastFieldCodecType::Linear => LinearCodec::estimate(&column),
|
||||||
@@ -204,7 +202,6 @@ fn detect_codec(
|
|||||||
// codecs
|
// codecs
|
||||||
estimations.retain(|estimation| !estimation.0.is_nan() && estimation.0 != f32::MAX);
|
estimations.retain(|estimation| !estimation.0.is_nan() && estimation.0 != f32::MAX);
|
||||||
estimations.sort_by(|(score_left, _), (score_right, _)| score_left.total_cmp(score_right));
|
estimations.sort_by(|(score_left, _), (score_right, _)| score_left.total_cmp(score_right));
|
||||||
trace!("Chosen Codec {:?}", estimations.first()?.1);
|
|
||||||
Some(estimations.first()?.1)
|
Some(estimations.first()?.1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,12 +210,6 @@ fn serialize_given_codec(
|
|||||||
codec_type: FastFieldCodecType,
|
codec_type: FastFieldCodecType,
|
||||||
output: &mut impl io::Write,
|
output: &mut impl io::Write,
|
||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
trace_time!(
|
|
||||||
"Serialize time for codec: {:?}, num_vals {}",
|
|
||||||
codec_type,
|
|
||||||
column.num_vals()
|
|
||||||
);
|
|
||||||
|
|
||||||
match codec_type {
|
match codec_type {
|
||||||
FastFieldCodecType::Bitpacked => {
|
FastFieldCodecType::Bitpacked => {
|
||||||
BitpackedCodec::serialize(&column, output)?;
|
BitpackedCodec::serialize(&column, output)?;
|
||||||
|
|||||||
@@ -323,8 +323,8 @@ impl SegmentRangeCollector {
|
|||||||
/// Converts the user provided f64 range value to fast field value space.
|
/// Converts the user provided f64 range value to fast field value space.
|
||||||
///
|
///
|
||||||
/// Internally fast field values are always stored as u64.
|
/// Internally fast field values are always stored as u64.
|
||||||
/// If the fast field has u64 [1,2,5], these values are stored as is in the fast field.
|
/// If the fast field has u64 `[1, 2, 5]`, these values are stored as is in the fast field.
|
||||||
/// A fast field with f64 [1.0, 2.0, 5.0] is converted to u64 space, using a
|
/// A fast field with f64 `[1.0, 2.0, 5.0]` is converted to u64 space, using a
|
||||||
/// monotonic mapping function, so the order is preserved.
|
/// monotonic mapping function, so the order is preserved.
|
||||||
///
|
///
|
||||||
/// Consequently, a f64 user range 1.0..3.0 needs to be converted to fast field value space using
|
/// Consequently, a f64 user range 1.0..3.0 needs to be converted to fast field value space using
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ pub trait CustomSegmentScorer<TScore>: 'static {
|
|||||||
pub trait CustomScorer<TScore>: Sync {
|
pub trait CustomScorer<TScore>: Sync {
|
||||||
/// Type of the associated [`CustomSegmentScorer`].
|
/// Type of the associated [`CustomSegmentScorer`].
|
||||||
type Child: CustomSegmentScorer<TScore>;
|
type Child: CustomSegmentScorer<TScore>;
|
||||||
/// Builds a child scorer for a specific segment. The child scorer is associated to
|
/// Builds a child scorer for a specific segment. The child scorer is associated with
|
||||||
/// a specific segment.
|
/// a specific segment.
|
||||||
fn segment_scorer(&self, segment_reader: &SegmentReader) -> crate::Result<Self::Child>;
|
fn segment_scorer(&self, segment_reader: &SegmentReader) -> crate::Result<Self::Child>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -91,7 +91,7 @@ fn facet_depth(facet_bytes: &[u8]) -> usize {
|
|||||||
/// let index = Index::create_in_ram(schema);
|
/// let index = Index::create_in_ram(schema);
|
||||||
/// {
|
/// {
|
||||||
/// let mut index_writer = index.writer(3_000_000)?;
|
/// let mut index_writer = index.writer(3_000_000)?;
|
||||||
/// // a document can be associated to any number of facets
|
/// // a document can be associated with any number of facets
|
||||||
/// index_writer.add_document(doc!(
|
/// index_writer.add_document(doc!(
|
||||||
/// title => "The Name of the Wind",
|
/// title => "The Name of the Wind",
|
||||||
/// facet => Facet::from("/lang/en"),
|
/// facet => Facet::from("/lang/en"),
|
||||||
@@ -338,11 +338,7 @@ impl SegmentCollector for FacetSegmentCollector {
|
|||||||
let mut previous_collapsed_ord: usize = usize::MAX;
|
let mut previous_collapsed_ord: usize = usize::MAX;
|
||||||
for &facet_ord in &self.facet_ords_buf {
|
for &facet_ord in &self.facet_ords_buf {
|
||||||
let collapsed_ord = self.collapse_mapping[facet_ord as usize];
|
let collapsed_ord = self.collapse_mapping[facet_ord as usize];
|
||||||
self.counts[collapsed_ord] += if collapsed_ord == previous_collapsed_ord {
|
self.counts[collapsed_ord] += u64::from(collapsed_ord != previous_collapsed_ord);
|
||||||
0
|
|
||||||
} else {
|
|
||||||
1
|
|
||||||
};
|
|
||||||
previous_collapsed_ord = collapsed_ord;
|
previous_collapsed_ord = collapsed_ord;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ impl HistogramCollector {
|
|||||||
/// The scale/range of the histogram is not dynamic. It is required to
|
/// The scale/range of the histogram is not dynamic. It is required to
|
||||||
/// define it by supplying following parameter:
|
/// define it by supplying following parameter:
|
||||||
/// - `min_value`: the minimum value that can be recorded in the histogram.
|
/// - `min_value`: the minimum value that can be recorded in the histogram.
|
||||||
/// - `bucket_width`: the length of the interval that is associated to each buckets.
|
/// - `bucket_width`: the length of the interval that is associated with each buckets.
|
||||||
/// - `num_buckets`: The overall number of buckets.
|
/// - `num_buckets`: The overall number of buckets.
|
||||||
///
|
///
|
||||||
/// Together, this parameters define a partition of `[min_value, min_value + num_buckets *
|
/// Together, this parameters define a partition of `[min_value, min_value + num_buckets *
|
||||||
|
|||||||
@@ -142,7 +142,7 @@ pub trait Collector: Sync + Send {
|
|||||||
/// e.g. `usize` for the `Count` collector.
|
/// e.g. `usize` for the `Count` collector.
|
||||||
type Fruit: Fruit;
|
type Fruit: Fruit;
|
||||||
|
|
||||||
/// Type of the `SegmentCollector` associated to this collector.
|
/// Type of the `SegmentCollector` associated with this collector.
|
||||||
type Child: SegmentCollector;
|
type Child: SegmentCollector;
|
||||||
|
|
||||||
/// `set_segment` is called before beginning to enumerate
|
/// `set_segment` is called before beginning to enumerate
|
||||||
@@ -156,7 +156,7 @@ pub trait Collector: Sync + Send {
|
|||||||
/// Returns true iff the collector requires to compute scores for documents.
|
/// Returns true iff the collector requires to compute scores for documents.
|
||||||
fn requires_scoring(&self) -> bool;
|
fn requires_scoring(&self) -> bool;
|
||||||
|
|
||||||
/// Combines the fruit associated to the collection of each segments
|
/// Combines the fruit associated with the collection of each segments
|
||||||
/// into one fruit.
|
/// into one fruit.
|
||||||
fn merge_fruits(
|
fn merge_fruits(
|
||||||
&self,
|
&self,
|
||||||
|
|||||||
@@ -693,7 +693,7 @@ impl Collector for TopDocs {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Segment Collector associated to `TopDocs`.
|
/// Segment Collector associated with `TopDocs`.
|
||||||
pub struct TopScoreSegmentCollector(TopSegmentCollector<Score>);
|
pub struct TopScoreSegmentCollector(TopSegmentCollector<Score>);
|
||||||
|
|
||||||
impl SegmentCollector for TopScoreSegmentCollector {
|
impl SegmentCollector for TopScoreSegmentCollector {
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ pub trait ScoreTweaker<TScore>: Sync {
|
|||||||
/// Type of the associated [`ScoreSegmentTweaker`].
|
/// Type of the associated [`ScoreSegmentTweaker`].
|
||||||
type Child: ScoreSegmentTweaker<TScore>;
|
type Child: ScoreSegmentTweaker<TScore>;
|
||||||
|
|
||||||
/// Builds a child tweaker for a specific segment. The child scorer is associated to
|
/// Builds a child tweaker for a specific segment. The child scorer is associated with
|
||||||
/// a specific segment.
|
/// a specific segment.
|
||||||
fn segment_tweaker(&self, segment_reader: &SegmentReader) -> Result<Self::Child>;
|
fn segment_tweaker(&self, segment_reader: &SegmentReader) -> Result<Self::Child>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ use crate::error::{DataCorruption, TantivyError};
|
|||||||
use crate::indexer::index_writer::{MAX_NUM_THREAD, MEMORY_ARENA_NUM_BYTES_MIN};
|
use crate::indexer::index_writer::{MAX_NUM_THREAD, MEMORY_ARENA_NUM_BYTES_MIN};
|
||||||
use crate::indexer::segment_updater::save_metas;
|
use crate::indexer::segment_updater::save_metas;
|
||||||
use crate::reader::{IndexReader, IndexReaderBuilder};
|
use crate::reader::{IndexReader, IndexReaderBuilder};
|
||||||
use crate::schema::{Field, FieldType, Schema};
|
use crate::schema::{Cardinality, Field, FieldType, Schema};
|
||||||
use crate::tokenizer::{TextAnalyzer, TokenizerManager};
|
use crate::tokenizer::{TextAnalyzer, TokenizerManager};
|
||||||
use crate::IndexWriter;
|
use crate::IndexWriter;
|
||||||
|
|
||||||
@@ -152,9 +152,7 @@ impl IndexBuilder {
|
|||||||
/// This should only be used for unit tests.
|
/// This should only be used for unit tests.
|
||||||
pub fn create_in_ram(self) -> Result<Index, TantivyError> {
|
pub fn create_in_ram(self) -> Result<Index, TantivyError> {
|
||||||
let ram_directory = RamDirectory::create();
|
let ram_directory = RamDirectory::create();
|
||||||
Ok(self
|
self.create(ram_directory)
|
||||||
.create(ram_directory)
|
|
||||||
.expect("Creating a RamDirectory should never fail"))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a new index in a given filepath.
|
/// Creates a new index in a given filepath.
|
||||||
@@ -228,10 +226,44 @@ impl IndexBuilder {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn validate(&self) -> crate::Result<()> {
|
||||||
|
if let Some(schema) = self.schema.as_ref() {
|
||||||
|
if let Some(sort_by_field) = self.index_settings.sort_by_field.as_ref() {
|
||||||
|
let schema_field = schema.get_field(&sort_by_field.field).ok_or_else(|| {
|
||||||
|
TantivyError::InvalidArgument(format!(
|
||||||
|
"Field to sort index {} not found in schema",
|
||||||
|
sort_by_field.field
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
let entry = schema.get_field_entry(schema_field);
|
||||||
|
if !entry.is_fast() {
|
||||||
|
return Err(TantivyError::InvalidArgument(format!(
|
||||||
|
"Field {} is no fast field. Field needs to be a single value fast field \
|
||||||
|
to be used to sort an index",
|
||||||
|
sort_by_field.field
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if entry.field_type().fastfield_cardinality() != Some(Cardinality::SingleValue) {
|
||||||
|
return Err(TantivyError::InvalidArgument(format!(
|
||||||
|
"Only single value fast field Cardinality supported for sorting index {}",
|
||||||
|
sort_by_field.field
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(TantivyError::InvalidArgument(
|
||||||
|
"no schema passed".to_string(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Creates a new index given an implementation of the trait `Directory`.
|
/// Creates a new index given an implementation of the trait `Directory`.
|
||||||
///
|
///
|
||||||
/// If a directory previously existed, it will be erased.
|
/// If a directory previously existed, it will be erased.
|
||||||
fn create<T: Into<Box<dyn Directory>>>(self, dir: T) -> crate::Result<Index> {
|
fn create<T: Into<Box<dyn Directory>>>(self, dir: T) -> crate::Result<Index> {
|
||||||
|
self.validate()?;
|
||||||
let dir = dir.into();
|
let dir = dir.into();
|
||||||
let directory = ManagedDirectory::wrap(dir)?;
|
let directory = ManagedDirectory::wrap(dir)?;
|
||||||
save_new_metas(
|
save_new_metas(
|
||||||
|
|||||||
@@ -130,7 +130,7 @@ impl SegmentMeta {
|
|||||||
/// Returns the relative path of a component of our segment.
|
/// Returns the relative path of a component of our segment.
|
||||||
///
|
///
|
||||||
/// It just joins the segment id with the extension
|
/// It just joins the segment id with the extension
|
||||||
/// associated to a segment component.
|
/// associated with a segment component.
|
||||||
pub fn relative_path(&self, component: SegmentComponent) -> PathBuf {
|
pub fn relative_path(&self, component: SegmentComponent) -> PathBuf {
|
||||||
let mut path = self.id().uuid_string();
|
let mut path = self.id().uuid_string();
|
||||||
path.push_str(&*match component {
|
path.push_str(&*match component {
|
||||||
@@ -326,13 +326,13 @@ pub struct IndexMeta {
|
|||||||
/// `IndexSettings` to configure index options.
|
/// `IndexSettings` to configure index options.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub index_settings: IndexSettings,
|
pub index_settings: IndexSettings,
|
||||||
/// List of `SegmentMeta` information associated to each finalized segment of the index.
|
/// List of `SegmentMeta` information associated with each finalized segment of the index.
|
||||||
pub segments: Vec<SegmentMeta>,
|
pub segments: Vec<SegmentMeta>,
|
||||||
/// Index `Schema`
|
/// Index `Schema`
|
||||||
pub schema: Schema,
|
pub schema: Schema,
|
||||||
/// Opstamp associated to the last `commit` operation.
|
/// Opstamp associated with the last `commit` operation.
|
||||||
pub opstamp: Opstamp,
|
pub opstamp: Opstamp,
|
||||||
/// Payload associated to the last commit.
|
/// Payload associated with the last commit.
|
||||||
///
|
///
|
||||||
/// Upon commit, clients can optionally add a small `String` payload to their commit
|
/// Upon commit, clients can optionally add a small `String` payload to their commit
|
||||||
/// to help identify this commit.
|
/// to help identify this commit.
|
||||||
|
|||||||
@@ -9,11 +9,11 @@ use crate::schema::{IndexRecordOption, Term};
|
|||||||
use crate::termdict::TermDictionary;
|
use crate::termdict::TermDictionary;
|
||||||
|
|
||||||
/// The inverted index reader is in charge of accessing
|
/// The inverted index reader is in charge of accessing
|
||||||
/// the inverted index associated to a specific field.
|
/// the inverted index associated with a specific field.
|
||||||
///
|
///
|
||||||
/// # Note
|
/// # Note
|
||||||
///
|
///
|
||||||
/// It is safe to delete the segment associated to
|
/// It is safe to delete the segment associated with
|
||||||
/// an `InvertedIndexReader`. As long as it is open,
|
/// an `InvertedIndexReader`. As long as it is open,
|
||||||
/// the `FileSlice` it is relying on should
|
/// the `FileSlice` it is relying on should
|
||||||
/// stay available.
|
/// stay available.
|
||||||
@@ -30,7 +30,7 @@ pub struct InvertedIndexReader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl InvertedIndexReader {
|
impl InvertedIndexReader {
|
||||||
#[cfg_attr(feature = "cargo-clippy", allow(clippy::needless_pass_by_value))] // for symmetry
|
#[allow(clippy::needless_pass_by_value)] // for symmetry
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
termdict: TermDictionary,
|
termdict: TermDictionary,
|
||||||
postings_file_slice: FileSlice,
|
postings_file_slice: FileSlice,
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ pub struct Searcher {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Searcher {
|
impl Searcher {
|
||||||
/// Returns the `Index` associated to the `Searcher`
|
/// Returns the `Index` associated with the `Searcher`
|
||||||
pub fn index(&self) -> &Index {
|
pub fn index(&self) -> &Index {
|
||||||
&self.inner.index
|
&self.inner.index
|
||||||
}
|
}
|
||||||
@@ -108,7 +108,7 @@ impl Searcher {
|
|||||||
store_reader.get_async(doc_address.doc_id).await
|
store_reader.get_async(doc_address.doc_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Access the schema associated to the index of this searcher.
|
/// Access the schema associated with the index of this searcher.
|
||||||
pub fn schema(&self) -> &Schema {
|
pub fn schema(&self) -> &Schema {
|
||||||
&self.inner.schema
|
&self.inner.schema
|
||||||
}
|
}
|
||||||
@@ -161,11 +161,11 @@ impl Searcher {
|
|||||||
///
|
///
|
||||||
/// Search works as follows :
|
/// Search works as follows :
|
||||||
///
|
///
|
||||||
/// First the weight object associated to the query is created.
|
/// First the weight object associated with the query is created.
|
||||||
///
|
///
|
||||||
/// Then, the query loops over the segments and for each segment :
|
/// Then, the query loops over the segments and for each segment :
|
||||||
/// - setup the collector and informs it that the segment being processed has changed.
|
/// - setup the collector and informs it that the segment being processed has changed.
|
||||||
/// - creates a SegmentCollector for collecting documents associated to the segment
|
/// - creates a SegmentCollector for collecting documents associated with the segment
|
||||||
/// - creates a `Scorer` object associated for this segment
|
/// - creates a `Scorer` object associated for this segment
|
||||||
/// - iterate through the matched documents and push them to the segment collector.
|
/// - iterate through the matched documents and push them to the segment collector.
|
||||||
///
|
///
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ impl Segment {
|
|||||||
/// Returns the relative path of a component of our segment.
|
/// Returns the relative path of a component of our segment.
|
||||||
///
|
///
|
||||||
/// It just joins the segment id with the extension
|
/// It just joins the segment id with the extension
|
||||||
/// associated to a segment component.
|
/// associated with a segment component.
|
||||||
pub fn relative_path(&self, component: SegmentComponent) -> PathBuf {
|
pub fn relative_path(&self, component: SegmentComponent) -> PathBuf {
|
||||||
self.meta.relative_path(component)
|
self.meta.relative_path(component)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use std::slice;
|
|||||||
/// except the delete component that takes an `segment_uuid`.`delete_opstamp`.`component_extension`
|
/// except the delete component that takes an `segment_uuid`.`delete_opstamp`.`component_extension`
|
||||||
#[derive(Copy, Clone, Eq, PartialEq)]
|
#[derive(Copy, Clone, Eq, PartialEq)]
|
||||||
pub enum SegmentComponent {
|
pub enum SegmentComponent {
|
||||||
/// Postings (or inverted list). Sorted lists of document ids, associated to terms
|
/// Postings (or inverted list). Sorted lists of document ids, associated with terms
|
||||||
Postings,
|
Postings,
|
||||||
/// Positions of terms in each document.
|
/// Positions of terms in each document.
|
||||||
Positions,
|
Positions,
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ impl SegmentReader {
|
|||||||
&self.fast_fields_readers
|
&self.fast_fields_readers
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Accessor to the `FacetReader` associated to a given `Field`.
|
/// Accessor to the `FacetReader` associated with a given `Field`.
|
||||||
pub fn facet_reader(&self, field: Field) -> crate::Result<FacetReader> {
|
pub fn facet_reader(&self, field: Field) -> crate::Result<FacetReader> {
|
||||||
let field_entry = self.schema.get_field_entry(field);
|
let field_entry = self.schema.get_field_entry(field);
|
||||||
|
|
||||||
@@ -208,13 +208,13 @@ impl SegmentReader {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a field reader associated to the field given in argument.
|
/// Returns a field reader associated with the field given in argument.
|
||||||
/// If the field was not present in the index during indexing time,
|
/// If the field was not present in the index during indexing time,
|
||||||
/// the InvertedIndexReader is empty.
|
/// the InvertedIndexReader is empty.
|
||||||
///
|
///
|
||||||
/// The field reader is in charge of iterating through the
|
/// The field reader is in charge of iterating through the
|
||||||
/// term dictionary associated to a specific field,
|
/// term dictionary associated with a specific field,
|
||||||
/// and opening the posting list associated to any term.
|
/// and opening the posting list associated with any term.
|
||||||
///
|
///
|
||||||
/// If the field is not marked as index, a warn is logged and an empty `InvertedIndexReader`
|
/// If the field is not marked as index, a warn is logged and an empty `InvertedIndexReader`
|
||||||
/// is returned.
|
/// is returned.
|
||||||
@@ -241,7 +241,7 @@ impl SegmentReader {
|
|||||||
|
|
||||||
if postings_file_opt.is_none() || record_option_opt.is_none() {
|
if postings_file_opt.is_none() || record_option_opt.is_none() {
|
||||||
// no documents in the segment contained this field.
|
// no documents in the segment contained this field.
|
||||||
// As a result, no data is associated to the inverted index.
|
// As a result, no data is associated with the inverted index.
|
||||||
//
|
//
|
||||||
// Returns an empty inverted index.
|
// Returns an empty inverted index.
|
||||||
let record_option = record_option_opt.unwrap_or(IndexRecordOption::Basic);
|
let record_option = record_option_opt.unwrap_or(IndexRecordOption::Basic);
|
||||||
|
|||||||
@@ -154,14 +154,14 @@ impl CompositeFile {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the `FileSlice` associated
|
/// Returns the `FileSlice` associated with
|
||||||
/// to a given `Field` and stored in a `CompositeFile`.
|
/// a given `Field` and stored in a `CompositeFile`.
|
||||||
pub fn open_read(&self, field: Field) -> Option<FileSlice> {
|
pub fn open_read(&self, field: Field) -> Option<FileSlice> {
|
||||||
self.open_read_with_idx(field, 0)
|
self.open_read_with_idx(field, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the `FileSlice` associated
|
/// Returns the `FileSlice` associated with
|
||||||
/// to a given `Field` and stored in a `CompositeFile`.
|
/// a given `Field` and stored in a `CompositeFile`.
|
||||||
pub fn open_read_with_idx(&self, field: Field, idx: usize) -> Option<FileSlice> {
|
pub fn open_read_with_idx(&self, field: Field, idx: usize) -> Option<FileSlice> {
|
||||||
self.offsets_index
|
self.offsets_index
|
||||||
.get(&FileAddr { field, idx })
|
.get(&FileAddr { field, idx })
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ impl RetryPolicy {
|
|||||||
|
|
||||||
/// The `DirectoryLock` is an object that represents a file lock.
|
/// The `DirectoryLock` is an object that represents a file lock.
|
||||||
///
|
///
|
||||||
/// It is associated to a lock file, that gets deleted on `Drop.`
|
/// It is associated with a lock file, that gets deleted on `Drop.`
|
||||||
pub struct DirectoryLock(Box<dyn Send + Sync + 'static>);
|
pub struct DirectoryLock(Box<dyn Send + Sync + 'static>);
|
||||||
|
|
||||||
struct DirectoryLockGuard {
|
struct DirectoryLockGuard {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use std::ops::{Deref, Range};
|
use std::ops::{Deref, Range};
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::Arc;
|
||||||
use std::{fmt, io};
|
use std::{fmt, io};
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
@@ -8,9 +8,6 @@ use stable_deref_trait::StableDeref;
|
|||||||
|
|
||||||
use crate::directory::OwnedBytes;
|
use crate::directory::OwnedBytes;
|
||||||
|
|
||||||
pub type ArcBytes = Arc<dyn Deref<Target = [u8]> + Send + Sync + 'static>;
|
|
||||||
pub type WeakArcBytes = Weak<dyn Deref<Target = [u8]> + Send + Sync + 'static>;
|
|
||||||
|
|
||||||
/// Objects that represents files sections in tantivy.
|
/// Objects that represents files sections in tantivy.
|
||||||
///
|
///
|
||||||
/// By contract, whatever happens to the directory file, as long as a FileHandle
|
/// By contract, whatever happens to the directory file, as long as a FileHandle
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use crc32fast::Hasher;
|
|||||||
|
|
||||||
use crate::directory::{WatchCallback, WatchCallbackList, WatchHandle};
|
use crate::directory::{WatchCallback, WatchCallbackList, WatchHandle};
|
||||||
|
|
||||||
pub const POLLING_INTERVAL: Duration = Duration::from_millis(if cfg!(test) { 1 } else { 500 });
|
const POLLING_INTERVAL: Duration = Duration::from_millis(if cfg!(test) { 1 } else { 500 });
|
||||||
|
|
||||||
// Watches a file and executes registered callbacks when the file is modified.
|
// Watches a file and executes registered callbacks when the file is modified.
|
||||||
pub struct FileWatcher {
|
pub struct FileWatcher {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use std::fs::{self, File, OpenOptions};
|
|||||||
use std::io::{self, BufWriter, Read, Seek, Write};
|
use std::io::{self, BufWriter, Read, Seek, Write};
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::{Arc, RwLock};
|
use std::sync::{Arc, RwLock, Weak};
|
||||||
use std::{fmt, result};
|
use std::{fmt, result};
|
||||||
|
|
||||||
use fs2::FileExt;
|
use fs2::FileExt;
|
||||||
@@ -18,10 +18,13 @@ use crate::directory::error::{
|
|||||||
};
|
};
|
||||||
use crate::directory::file_watcher::FileWatcher;
|
use crate::directory::file_watcher::FileWatcher;
|
||||||
use crate::directory::{
|
use crate::directory::{
|
||||||
AntiCallToken, ArcBytes, Directory, DirectoryLock, FileHandle, Lock, OwnedBytes,
|
AntiCallToken, Directory, DirectoryLock, FileHandle, Lock, OwnedBytes, TerminatingWrite,
|
||||||
TerminatingWrite, WatchCallback, WatchHandle, WeakArcBytes, WritePtr,
|
WatchCallback, WatchHandle, WritePtr,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
pub type ArcBytes = Arc<dyn Deref<Target = [u8]> + Send + Sync + 'static>;
|
||||||
|
pub type WeakArcBytes = Weak<dyn Deref<Target = [u8]> + Send + Sync + 'static>;
|
||||||
|
|
||||||
/// Create a default io error given a string.
|
/// Create a default io error given a string.
|
||||||
pub(crate) fn make_io_err(msg: String) -> io::Error {
|
pub(crate) fn make_io_err(msg: String) -> io::Error {
|
||||||
io::Error::new(io::ErrorKind::Other, msg)
|
io::Error::new(io::ErrorKind::Other, msg)
|
||||||
@@ -301,7 +304,7 @@ pub(crate) fn atomic_write(path: &Path, content: &[u8]) -> io::Result<()> {
|
|||||||
"Path {:?} does not have parent directory.",
|
"Path {:?} does not have parent directory.",
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let mut tempfile = tempfile::Builder::new().tempfile_in(&parent_path)?;
|
let mut tempfile = tempfile::Builder::new().tempfile_in(parent_path)?;
|
||||||
tempfile.write_all(content)?;
|
tempfile.write_all(content)?;
|
||||||
tempfile.flush()?;
|
tempfile.flush()?;
|
||||||
tempfile.as_file_mut().sync_data()?;
|
tempfile.as_file_mut().sync_data()?;
|
||||||
@@ -334,7 +337,7 @@ impl Directory for MmapDirectory {
|
|||||||
Ok(Arc::new(owned_bytes))
|
Ok(Arc::new(owned_bytes))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Any entry associated to the path in the mmap will be
|
/// Any entry associated with the path in the mmap will be
|
||||||
/// removed before the file is deleted.
|
/// removed before the file is deleted.
|
||||||
fn delete(&self, path: &Path) -> result::Result<(), DeleteError> {
|
fn delete(&self, path: &Path) -> result::Result<(), DeleteError> {
|
||||||
let full_path = self.resolve_path(path);
|
let full_path = self.resolve_path(path);
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ pub use ownedbytes::OwnedBytes;
|
|||||||
pub(crate) use self::composite_file::{CompositeFile, CompositeWrite};
|
pub(crate) use self::composite_file::{CompositeFile, CompositeWrite};
|
||||||
pub use self::directory::{Directory, DirectoryClone, DirectoryLock};
|
pub use self::directory::{Directory, DirectoryClone, DirectoryLock};
|
||||||
pub use self::directory_lock::{Lock, INDEX_WRITER_LOCK, META_LOCK};
|
pub use self::directory_lock::{Lock, INDEX_WRITER_LOCK, META_LOCK};
|
||||||
pub(crate) use self::file_slice::{ArcBytes, WeakArcBytes};
|
|
||||||
pub use self::file_slice::{FileHandle, FileSlice};
|
pub use self::file_slice::{FileHandle, FileSlice};
|
||||||
pub use self::ram_directory::RamDirectory;
|
pub use self::ram_directory::RamDirectory;
|
||||||
pub use self::watch_event_router::{WatchCallback, WatchCallbackList, WatchHandle};
|
pub use self::watch_event_router::{WatchCallback, WatchCallbackList, WatchHandle};
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use std::ops::Range;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use fastfield_codecs::Column;
|
use fastfield_codecs::Column;
|
||||||
@@ -31,36 +32,39 @@ impl BytesFastFieldReader {
|
|||||||
Ok(BytesFastFieldReader { idx_reader, values })
|
Ok(BytesFastFieldReader { idx_reader, values })
|
||||||
}
|
}
|
||||||
|
|
||||||
fn range(&self, doc: DocId) -> (usize, usize) {
|
fn range(&self, doc: DocId) -> Range<u64> {
|
||||||
let idx = doc as u64;
|
let idx = doc as u64;
|
||||||
let start = self.idx_reader.get_val(idx) as usize;
|
let start = self.idx_reader.get_val(idx);
|
||||||
let stop = self.idx_reader.get_val(idx + 1) as usize;
|
let end = self.idx_reader.get_val(idx + 1);
|
||||||
(start, stop)
|
start..end
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the bytes associated to the given `doc`
|
/// Returns the bytes associated with the given `doc`
|
||||||
pub fn get_bytes(&self, doc: DocId) -> &[u8] {
|
pub fn get_bytes(&self, doc: DocId) -> &[u8] {
|
||||||
let (start, stop) = self.range(doc);
|
let range = self.range(doc);
|
||||||
&self.values.as_slice()[start..stop]
|
&self.values.as_slice()[range.start as usize..range.end as usize]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the length of the bytes associated to the given `doc`
|
/// Returns the length of the bytes associated with the given `doc`
|
||||||
pub fn num_bytes(&self, doc: DocId) -> usize {
|
pub fn num_bytes(&self, doc: DocId) -> u64 {
|
||||||
let (start, stop) = self.range(doc);
|
let range = self.range(doc);
|
||||||
stop - start
|
range.end - range.start
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the overall number of bytes in this bytes fast field.
|
/// Returns the overall number of bytes in this bytes fast field.
|
||||||
pub fn total_num_bytes(&self) -> usize {
|
pub fn total_num_bytes(&self) -> u64 {
|
||||||
self.values.len()
|
self.values.len() as u64
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MultiValueLength for BytesFastFieldReader {
|
impl MultiValueLength for BytesFastFieldReader {
|
||||||
|
fn get_range(&self, doc_id: DocId) -> std::ops::Range<u64> {
|
||||||
|
self.range(doc_id)
|
||||||
|
}
|
||||||
fn get_len(&self, doc_id: DocId) -> u64 {
|
fn get_len(&self, doc_id: DocId) -> u64 {
|
||||||
self.num_bytes(doc_id) as u64
|
self.num_bytes(doc_id)
|
||||||
}
|
}
|
||||||
fn get_total_len(&self) -> u64 {
|
fn get_total_len(&self) -> u64 {
|
||||||
self.total_num_bytes() as u64
|
self.total_num_bytes()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ use crate::DocId;
|
|||||||
///
|
///
|
||||||
/// Once acquired, writing is done by calling
|
/// Once acquired, writing is done by calling
|
||||||
/// [`.add_document_val(&[u8])`](BytesFastFieldWriter::add_document_val)
|
/// [`.add_document_val(&[u8])`](BytesFastFieldWriter::add_document_val)
|
||||||
/// once per document, even if there are no bytes associated to it.
|
/// once per document, even if there are no bytes associated with it.
|
||||||
pub struct BytesFastFieldWriter {
|
pub struct BytesFastFieldWriter {
|
||||||
field: Field,
|
field: Field,
|
||||||
vals: Vec<u8>,
|
vals: Vec<u8>,
|
||||||
@@ -45,7 +45,7 @@ impl BytesFastFieldWriter {
|
|||||||
pub fn mem_usage(&self) -> usize {
|
pub fn mem_usage(&self) -> usize {
|
||||||
self.vals.capacity() + self.doc_index.capacity() * std::mem::size_of::<u64>()
|
self.vals.capacity() + self.doc_index.capacity() * std::mem::size_of::<u64>()
|
||||||
}
|
}
|
||||||
/// Access the field associated to the `BytesFastFieldWriter`
|
/// Access the field associated with the `BytesFastFieldWriter`
|
||||||
pub fn field(&self) -> Field {
|
pub fn field(&self) -> Field {
|
||||||
self.field
|
self.field
|
||||||
}
|
}
|
||||||
@@ -67,7 +67,7 @@ impl BytesFastFieldWriter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register the bytes associated to a document.
|
/// Register the bytes associated with a document.
|
||||||
///
|
///
|
||||||
/// The method returns the `DocId` of the document that was
|
/// The method returns the `DocId` of the document that was
|
||||||
/// just written.
|
/// just written.
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use crate::termdict::{TermDictionary, TermOrdinal};
|
|||||||
use crate::DocId;
|
use crate::DocId;
|
||||||
|
|
||||||
/// The facet reader makes it possible to access the list of
|
/// The facet reader makes it possible to access the list of
|
||||||
/// facets associated to a given document in a specific
|
/// facets associated with a given document in a specific
|
||||||
/// segment.
|
/// segment.
|
||||||
///
|
///
|
||||||
/// Rather than manipulating `Facet` object directly, the API
|
/// Rather than manipulating `Facet` object directly, the API
|
||||||
@@ -58,7 +58,7 @@ impl FacetReader {
|
|||||||
&self.term_dict
|
&self.term_dict
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Given a term ordinal returns the term associated to it.
|
/// Given a term ordinal returns the term associated with it.
|
||||||
pub fn facet_from_ord(
|
pub fn facet_from_ord(
|
||||||
&mut self,
|
&mut self,
|
||||||
facet_ord: TermOrdinal,
|
facet_ord: TermOrdinal,
|
||||||
@@ -74,7 +74,7 @@ impl FacetReader {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return the list of facet ordinals associated to a document.
|
/// Return the list of facet ordinals associated with a document.
|
||||||
pub fn facet_ords(&self, doc: DocId, output: &mut Vec<u64>) {
|
pub fn facet_ords(&self, doc: DocId, output: &mut Vec<u64>) {
|
||||||
self.term_ords.get_vals(doc, output);
|
self.term_ords.get_vals(doc, output);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,7 +47,9 @@ mod writer;
|
|||||||
/// Trait for `BytesFastFieldReader` and `MultiValuedFastFieldReader` to return the length of data
|
/// Trait for `BytesFastFieldReader` and `MultiValuedFastFieldReader` to return the length of data
|
||||||
/// for a doc_id
|
/// for a doc_id
|
||||||
pub trait MultiValueLength {
|
pub trait MultiValueLength {
|
||||||
/// returns the num of values associated to a doc_id
|
/// returns the positions for a docid
|
||||||
|
fn get_range(&self, doc_id: DocId) -> std::ops::Range<u64>;
|
||||||
|
/// returns the num of values associated with a doc_id
|
||||||
fn get_len(&self, doc_id: DocId) -> u64;
|
fn get_len(&self, doc_id: DocId) -> u64;
|
||||||
/// returns the sum of num values for all doc_ids
|
/// returns the sum of num values for all doc_ids
|
||||||
fn get_total_len(&self) -> u64;
|
fn get_total_len(&self) -> u64;
|
||||||
|
|||||||
@@ -30,8 +30,8 @@ impl<Item: FastValue> MultiValuedFastFieldReader<Item> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns `[start, end)`, such that the values associated
|
/// Returns `[start, end)`, such that the values associated with
|
||||||
/// to the given document are `start..end`.
|
/// the given document are `start..end`.
|
||||||
#[inline]
|
#[inline]
|
||||||
fn range(&self, doc: DocId) -> Range<u64> {
|
fn range(&self, doc: DocId) -> Range<u64> {
|
||||||
let idx = doc as u64;
|
let idx = doc as u64;
|
||||||
@@ -40,7 +40,7 @@ impl<Item: FastValue> MultiValuedFastFieldReader<Item> {
|
|||||||
start..end
|
start..end
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the array of values associated to the given `doc`.
|
/// Returns the array of values associated with the given `doc`.
|
||||||
#[inline]
|
#[inline]
|
||||||
fn get_vals_for_range(&self, range: Range<u64>, vals: &mut Vec<Item>) {
|
fn get_vals_for_range(&self, range: Range<u64>, vals: &mut Vec<Item>) {
|
||||||
let len = (range.end - range.start) as usize;
|
let len = (range.end - range.start) as usize;
|
||||||
@@ -48,7 +48,7 @@ impl<Item: FastValue> MultiValuedFastFieldReader<Item> {
|
|||||||
self.vals_reader.get_range(range.start, &mut vals[..]);
|
self.vals_reader.get_range(range.start, &mut vals[..]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the array of values associated to the given `doc`.
|
/// Returns the array of values associated with the given `doc`.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn get_vals(&self, doc: DocId, vals: &mut Vec<Item>) {
|
pub fn get_vals(&self, doc: DocId, vals: &mut Vec<Item>) {
|
||||||
let range = self.range(doc);
|
let range = self.range(doc);
|
||||||
@@ -88,6 +88,9 @@ impl<Item: FastValue> MultiValuedFastFieldReader<Item> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<Item: FastValue> MultiValueLength for MultiValuedFastFieldReader<Item> {
|
impl<Item: FastValue> MultiValueLength for MultiValuedFastFieldReader<Item> {
|
||||||
|
fn get_range(&self, doc_id: DocId) -> Range<u64> {
|
||||||
|
self.range(doc_id)
|
||||||
|
}
|
||||||
fn get_len(&self, doc_id: DocId) -> u64 {
|
fn get_len(&self, doc_id: DocId) -> u64 {
|
||||||
self.num_vals(doc_id) as u64
|
self.num_vals(doc_id) as u64
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
use std::io;
|
use std::io;
|
||||||
use std::sync::Mutex;
|
|
||||||
|
|
||||||
use fastfield_codecs::{Column, MonotonicallyMappableToU64, VecColumn};
|
use fastfield_codecs::{Column, MonotonicallyMappableToU64, VecColumn};
|
||||||
use fnv::FnvHashMap;
|
use fnv::FnvHashMap;
|
||||||
use measure_time::{debug_time, trace_time};
|
|
||||||
|
|
||||||
use crate::fastfield::{value_to_u64, CompositeFastFieldSerializer, FastFieldType};
|
use crate::fastfield::{value_to_u64, CompositeFastFieldSerializer, FastFieldType};
|
||||||
use crate::indexer::doc_id_mapping::DocIdMapping;
|
use crate::indexer::doc_id_mapping::DocIdMapping;
|
||||||
@@ -63,7 +61,7 @@ impl MultiValuedFastFieldWriter {
|
|||||||
+ self.doc_index.capacity() * std::mem::size_of::<u64>()
|
+ self.doc_index.capacity() * std::mem::size_of::<u64>()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Access the field associated to the `MultiValuedFastFieldWriter`
|
/// Access the field associated with the `MultiValuedFastFieldWriter`
|
||||||
pub fn field(&self) -> Field {
|
pub fn field(&self) -> Field {
|
||||||
self.field
|
self.field
|
||||||
}
|
}
|
||||||
@@ -147,13 +145,6 @@ impl MultiValuedFastFieldWriter {
|
|||||||
{
|
{
|
||||||
self.doc_index.push(self.vals.len() as u64);
|
self.doc_index.push(self.vals.len() as u64);
|
||||||
let col = VecColumn::from(&self.doc_index[..]);
|
let col = VecColumn::from(&self.doc_index[..]);
|
||||||
|
|
||||||
trace_time!(
|
|
||||||
"segment-serialize-multi-fast-field-idx, num_vals {}, field_id {:?}",
|
|
||||||
col.num_vals(),
|
|
||||||
self.field()
|
|
||||||
);
|
|
||||||
|
|
||||||
if let Some(doc_id_map) = doc_id_map {
|
if let Some(doc_id_map) = doc_id_map {
|
||||||
let multi_value_start_index = MultivalueStartIndex::new(&col, doc_id_map);
|
let multi_value_start_index = MultivalueStartIndex::new(&col, doc_id_map);
|
||||||
serializer.create_auto_detect_u64_fast_field_with_idx(
|
serializer.create_auto_detect_u64_fast_field_with_idx(
|
||||||
@@ -166,12 +157,6 @@ impl MultiValuedFastFieldWriter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
trace_time!(
|
|
||||||
"segment-serialize-multi-fast-field-values, num_vals {}, field_id {:?}",
|
|
||||||
self.vals.len(),
|
|
||||||
self.field()
|
|
||||||
);
|
|
||||||
|
|
||||||
// Writing the values themselves.
|
// Writing the values themselves.
|
||||||
// TODO FIXME: Use less memory.
|
// TODO FIXME: Use less memory.
|
||||||
let mut values: Vec<u64> = Vec::new();
|
let mut values: Vec<u64> = Vec::new();
|
||||||
@@ -218,112 +203,63 @@ impl MultiValuedFastFieldWriter {
|
|||||||
pub(crate) struct MultivalueStartIndex<'a, C: Column> {
|
pub(crate) struct MultivalueStartIndex<'a, C: Column> {
|
||||||
column: &'a C,
|
column: &'a C,
|
||||||
doc_id_map: &'a DocIdMapping,
|
doc_id_map: &'a DocIdMapping,
|
||||||
min_max_opt: Mutex<Option<(u64, u64)>>,
|
min: u64,
|
||||||
random_seeker: Mutex<MultivalueStartIndexRandomSeeker<'a, C>>,
|
max: u64,
|
||||||
}
|
|
||||||
|
|
||||||
struct MultivalueStartIndexRandomSeeker<'a, C: Column> {
|
|
||||||
seek_head: MultivalueStartIndexIter<'a, C>,
|
|
||||||
seek_next_id: u64,
|
|
||||||
}
|
|
||||||
impl<'a, C: Column> MultivalueStartIndexRandomSeeker<'a, C> {
|
|
||||||
fn new(column: &'a C, doc_id_map: &'a DocIdMapping) -> Self {
|
|
||||||
Self {
|
|
||||||
seek_head: MultivalueStartIndexIter {
|
|
||||||
column,
|
|
||||||
doc_id_map,
|
|
||||||
new_doc_id: 0,
|
|
||||||
offset: 0u64,
|
|
||||||
},
|
|
||||||
seek_next_id: 0u64,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, C: Column> MultivalueStartIndex<'a, C> {
|
impl<'a, C: Column> MultivalueStartIndex<'a, C> {
|
||||||
pub fn new(column: &'a C, doc_id_map: &'a DocIdMapping) -> Self {
|
pub fn new(column: &'a C, doc_id_map: &'a DocIdMapping) -> Self {
|
||||||
assert_eq!(column.num_vals(), doc_id_map.num_old_doc_ids() as u64 + 1);
|
assert_eq!(column.num_vals(), doc_id_map.num_old_doc_ids() as u64 + 1);
|
||||||
|
let (min, max) =
|
||||||
|
tantivy_bitpacker::minmax(iter_remapped_multivalue_index(doc_id_map, column))
|
||||||
|
.unwrap_or((0u64, 0u64));
|
||||||
MultivalueStartIndex {
|
MultivalueStartIndex {
|
||||||
column,
|
column,
|
||||||
doc_id_map,
|
doc_id_map,
|
||||||
min_max_opt: Mutex::default(),
|
min,
|
||||||
random_seeker: Mutex::new(MultivalueStartIndexRandomSeeker::new(column, doc_id_map)),
|
max,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn minmax(&self) -> (u64, u64) {
|
|
||||||
if let Some((min, max)) = *self.min_max_opt.lock().unwrap() {
|
|
||||||
return (min, max);
|
|
||||||
}
|
|
||||||
let (min, max) = tantivy_bitpacker::minmax(self.iter()).unwrap_or((0u64, 0u64));
|
|
||||||
*self.min_max_opt.lock().unwrap() = Some((min, max));
|
|
||||||
(min, max)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
impl<'a, C: Column> Column for MultivalueStartIndex<'a, C> {
|
impl<'a, C: Column> Column for MultivalueStartIndex<'a, C> {
|
||||||
fn get_val(&self, idx: u64) -> u64 {
|
fn get_val(&self, _idx: u64) -> u64 {
|
||||||
let mut random_seeker_lock = self.random_seeker.lock().unwrap();
|
unimplemented!()
|
||||||
if random_seeker_lock.seek_next_id > idx {
|
|
||||||
*random_seeker_lock =
|
|
||||||
MultivalueStartIndexRandomSeeker::new(self.column, self.doc_id_map);
|
|
||||||
}
|
|
||||||
let to_skip = idx - random_seeker_lock.seek_next_id;
|
|
||||||
random_seeker_lock.seek_next_id = idx + 1;
|
|
||||||
random_seeker_lock.seek_head.nth(to_skip as usize).unwrap()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn min_value(&self) -> u64 {
|
fn min_value(&self) -> u64 {
|
||||||
self.minmax().0
|
self.min
|
||||||
}
|
}
|
||||||
|
|
||||||
fn max_value(&self) -> u64 {
|
fn max_value(&self) -> u64 {
|
||||||
self.minmax().1
|
self.max
|
||||||
}
|
}
|
||||||
|
|
||||||
fn num_vals(&self) -> u64 {
|
fn num_vals(&self) -> u64 {
|
||||||
(self.doc_id_map.num_new_doc_ids() + 1) as u64
|
(self.doc_id_map.num_new_doc_ids() + 1) as u64
|
||||||
}
|
}
|
||||||
|
|
||||||
fn iter<'b>(&'b self) -> Box<dyn Iterator<Item = u64> + 'b> {
|
fn iter(&self) -> Box<dyn Iterator<Item = u64> + '_> {
|
||||||
Box::new(MultivalueStartIndexIter::new(self.column, self.doc_id_map))
|
Box::new(iter_remapped_multivalue_index(
|
||||||
|
self.doc_id_map,
|
||||||
|
&self.column,
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct MultivalueStartIndexIter<'a, C: Column> {
|
fn iter_remapped_multivalue_index<'a, C: Column>(
|
||||||
pub column: &'a C,
|
doc_id_map: &'a DocIdMapping,
|
||||||
pub doc_id_map: &'a DocIdMapping,
|
column: &'a C,
|
||||||
pub new_doc_id: usize,
|
) -> impl Iterator<Item = u64> + 'a {
|
||||||
pub offset: u64,
|
let mut offset = 0;
|
||||||
}
|
let offsets = doc_id_map
|
||||||
|
.iter_old_doc_ids()
|
||||||
impl<'a, C: Column> MultivalueStartIndexIter<'a, C> {
|
.map(move |old_doc| {
|
||||||
fn new(column: &'a C, doc_id_map: &'a DocIdMapping) -> Self {
|
let num_vals_for_doc =
|
||||||
Self {
|
column.get_val(old_doc as u64 + 1) - column.get_val(old_doc as u64);
|
||||||
column,
|
offset += num_vals_for_doc;
|
||||||
doc_id_map,
|
offset
|
||||||
new_doc_id: 0,
|
});
|
||||||
offset: 0,
|
std::iter::once(0u64).chain(offsets)
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, C: Column> Iterator for MultivalueStartIndexIter<'a, C> {
|
|
||||||
type Item = u64;
|
|
||||||
|
|
||||||
fn next(&mut self) -> Option<Self::Item> {
|
|
||||||
if self.new_doc_id > self.doc_id_map.num_new_doc_ids() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let new_doc_id = self.new_doc_id;
|
|
||||||
self.new_doc_id += 1;
|
|
||||||
let start_offset = self.offset;
|
|
||||||
if new_doc_id < self.doc_id_map.num_new_doc_ids() {
|
|
||||||
let old_doc = self.doc_id_map.get_old_doc_id(new_doc_id as u32) as u64;
|
|
||||||
let num_vals_for_doc = self.column.get_val(old_doc + 1) - self.column.get_val(old_doc);
|
|
||||||
self.offset += num_vals_for_doc;
|
|
||||||
}
|
|
||||||
Some(start_offset)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -358,11 +294,5 @@ mod tests {
|
|||||||
vec![0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
|
vec![0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
|
||||||
);
|
);
|
||||||
assert_eq!(multivalue_start_index.num_vals(), 11);
|
assert_eq!(multivalue_start_index.num_vals(), 11);
|
||||||
assert_eq!(multivalue_start_index.get_val(3), 2);
|
|
||||||
assert_eq!(multivalue_start_index.get_val(5), 5);
|
|
||||||
assert_eq!(multivalue_start_index.get_val(8), 21);
|
|
||||||
assert_eq!(multivalue_start_index.get_val(4), 3);
|
|
||||||
assert_eq!(multivalue_start_index.get_val(0), 0);
|
|
||||||
assert_eq!(multivalue_start_index.get_val(10), 55);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -135,7 +135,7 @@ impl FastFieldReaders {
|
|||||||
Ok(MultiValuedFastFieldReader::open(idx_reader, vals_reader))
|
Ok(MultiValuedFastFieldReader::open(idx_reader, vals_reader))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the `u64` fast field reader reader associated to `field`.
|
/// Returns the `u64` fast field reader reader associated with `field`.
|
||||||
///
|
///
|
||||||
/// If `field` is not a u64 fast field, this method returns an Error.
|
/// If `field` is not a u64 fast field, this method returns an Error.
|
||||||
pub fn u64(&self, field: Field) -> crate::Result<Arc<dyn Column<u64>>> {
|
pub fn u64(&self, field: Field) -> crate::Result<Arc<dyn Column<u64>>> {
|
||||||
@@ -143,16 +143,16 @@ impl FastFieldReaders {
|
|||||||
self.typed_fast_field_reader(field)
|
self.typed_fast_field_reader(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the `u64` fast field reader reader associated to `field`, regardless of whether the
|
/// Returns the `u64` fast field reader reader associated with `field`, regardless of whether
|
||||||
/// given field is effectively of type `u64` or not.
|
/// the given field is effectively of type `u64` or not.
|
||||||
///
|
///
|
||||||
/// If not, the fastfield reader will returns the u64-value associated to the original
|
/// If not, the fastfield reader will returns the u64-value associated with the original
|
||||||
/// FastValue.
|
/// FastValue.
|
||||||
pub fn u64_lenient(&self, field: Field) -> crate::Result<Arc<dyn Column<u64>>> {
|
pub fn u64_lenient(&self, field: Field) -> crate::Result<Arc<dyn Column<u64>>> {
|
||||||
self.typed_fast_field_reader(field)
|
self.typed_fast_field_reader(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the `i64` fast field reader reader associated to `field`.
|
/// Returns the `i64` fast field reader reader associated with `field`.
|
||||||
///
|
///
|
||||||
/// If `field` is not a i64 fast field, this method returns an Error.
|
/// If `field` is not a i64 fast field, this method returns an Error.
|
||||||
pub fn i64(&self, field: Field) -> crate::Result<Arc<dyn Column<i64>>> {
|
pub fn i64(&self, field: Field) -> crate::Result<Arc<dyn Column<i64>>> {
|
||||||
@@ -160,7 +160,7 @@ impl FastFieldReaders {
|
|||||||
self.typed_fast_field_reader(field)
|
self.typed_fast_field_reader(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the `date` fast field reader reader associated to `field`.
|
/// Returns the `date` fast field reader reader associated with `field`.
|
||||||
///
|
///
|
||||||
/// If `field` is not a date fast field, this method returns an Error.
|
/// If `field` is not a date fast field, this method returns an Error.
|
||||||
pub fn date(&self, field: Field) -> crate::Result<Arc<dyn Column<DateTime>>> {
|
pub fn date(&self, field: Field) -> crate::Result<Arc<dyn Column<DateTime>>> {
|
||||||
@@ -168,7 +168,7 @@ impl FastFieldReaders {
|
|||||||
self.typed_fast_field_reader(field)
|
self.typed_fast_field_reader(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the `f64` fast field reader reader associated to `field`.
|
/// Returns the `f64` fast field reader reader associated with `field`.
|
||||||
///
|
///
|
||||||
/// If `field` is not a f64 fast field, this method returns an Error.
|
/// If `field` is not a f64 fast field, this method returns an Error.
|
||||||
pub fn f64(&self, field: Field) -> crate::Result<Arc<dyn Column<f64>>> {
|
pub fn f64(&self, field: Field) -> crate::Result<Arc<dyn Column<f64>>> {
|
||||||
@@ -176,7 +176,7 @@ impl FastFieldReaders {
|
|||||||
self.typed_fast_field_reader(field)
|
self.typed_fast_field_reader(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the `bool` fast field reader reader associated to `field`.
|
/// Returns the `bool` fast field reader reader associated with `field`.
|
||||||
///
|
///
|
||||||
/// If `field` is not a bool fast field, this method returns an Error.
|
/// If `field` is not a bool fast field, this method returns an Error.
|
||||||
pub fn bool(&self, field: Field) -> crate::Result<Arc<dyn Column<bool>>> {
|
pub fn bool(&self, field: Field) -> crate::Result<Arc<dyn Column<bool>>> {
|
||||||
@@ -184,7 +184,7 @@ impl FastFieldReaders {
|
|||||||
self.typed_fast_field_reader(field)
|
self.typed_fast_field_reader(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a `u64s` multi-valued fast field reader reader associated to `field`.
|
/// Returns a `u64s` multi-valued fast field reader reader associated with `field`.
|
||||||
///
|
///
|
||||||
/// If `field` is not a u64 multi-valued fast field, this method returns an Error.
|
/// If `field` is not a u64 multi-valued fast field, this method returns an Error.
|
||||||
pub fn u64s(&self, field: Field) -> crate::Result<MultiValuedFastFieldReader<u64>> {
|
pub fn u64s(&self, field: Field) -> crate::Result<MultiValuedFastFieldReader<u64>> {
|
||||||
@@ -192,15 +192,15 @@ impl FastFieldReaders {
|
|||||||
self.typed_fast_field_multi_reader(field)
|
self.typed_fast_field_multi_reader(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a `u64s` multi-valued fast field reader reader associated to `field`, regardless of
|
/// Returns a `u64s` multi-valued fast field reader reader associated with `field`, regardless
|
||||||
/// whether the given field is effectively of type `u64` or not.
|
/// of whether the given field is effectively of type `u64` or not.
|
||||||
///
|
///
|
||||||
/// If `field` is not a u64 multi-valued fast field, this method returns an Error.
|
/// If `field` is not a u64 multi-valued fast field, this method returns an Error.
|
||||||
pub fn u64s_lenient(&self, field: Field) -> crate::Result<MultiValuedFastFieldReader<u64>> {
|
pub fn u64s_lenient(&self, field: Field) -> crate::Result<MultiValuedFastFieldReader<u64>> {
|
||||||
self.typed_fast_field_multi_reader(field)
|
self.typed_fast_field_multi_reader(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a `i64s` multi-valued fast field reader reader associated to `field`.
|
/// Returns a `i64s` multi-valued fast field reader reader associated with `field`.
|
||||||
///
|
///
|
||||||
/// If `field` is not a i64 multi-valued fast field, this method returns an Error.
|
/// If `field` is not a i64 multi-valued fast field, this method returns an Error.
|
||||||
pub fn i64s(&self, field: Field) -> crate::Result<MultiValuedFastFieldReader<i64>> {
|
pub fn i64s(&self, field: Field) -> crate::Result<MultiValuedFastFieldReader<i64>> {
|
||||||
@@ -208,7 +208,7 @@ impl FastFieldReaders {
|
|||||||
self.typed_fast_field_multi_reader(field)
|
self.typed_fast_field_multi_reader(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a `f64s` multi-valued fast field reader reader associated to `field`.
|
/// Returns a `f64s` multi-valued fast field reader reader associated with `field`.
|
||||||
///
|
///
|
||||||
/// If `field` is not a f64 multi-valued fast field, this method returns an Error.
|
/// If `field` is not a f64 multi-valued fast field, this method returns an Error.
|
||||||
pub fn f64s(&self, field: Field) -> crate::Result<MultiValuedFastFieldReader<f64>> {
|
pub fn f64s(&self, field: Field) -> crate::Result<MultiValuedFastFieldReader<f64>> {
|
||||||
@@ -216,7 +216,7 @@ impl FastFieldReaders {
|
|||||||
self.typed_fast_field_multi_reader(field)
|
self.typed_fast_field_multi_reader(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a `bools` multi-valued fast field reader reader associated to `field`.
|
/// Returns a `bools` multi-valued fast field reader reader associated with `field`.
|
||||||
///
|
///
|
||||||
/// If `field` is not a bool multi-valued fast field, this method returns an Error.
|
/// If `field` is not a bool multi-valued fast field, this method returns an Error.
|
||||||
pub fn bools(&self, field: Field) -> crate::Result<MultiValuedFastFieldReader<bool>> {
|
pub fn bools(&self, field: Field) -> crate::Result<MultiValuedFastFieldReader<bool>> {
|
||||||
@@ -224,7 +224,7 @@ impl FastFieldReaders {
|
|||||||
self.typed_fast_field_multi_reader(field)
|
self.typed_fast_field_multi_reader(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a `time::OffsetDateTime` multi-valued fast field reader reader associated to
|
/// Returns a `time::OffsetDateTime` multi-valued fast field reader reader associated with
|
||||||
/// `field`.
|
/// `field`.
|
||||||
///
|
///
|
||||||
/// If `field` is not a `time::OffsetDateTime` multi-valued fast field, this method returns an
|
/// If `field` is not a `time::OffsetDateTime` multi-valued fast field, this method returns an
|
||||||
@@ -234,7 +234,7 @@ impl FastFieldReaders {
|
|||||||
self.typed_fast_field_multi_reader(field)
|
self.typed_fast_field_multi_reader(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the `bytes` fast field reader associated to `field`.
|
/// Returns the `bytes` fast field reader associated with `field`.
|
||||||
///
|
///
|
||||||
/// If `field` is not a bytes fast field, returns an Error.
|
/// If `field` is not a bytes fast field, returns an Error.
|
||||||
pub fn bytes(&self, field: Field) -> crate::Result<BytesFastFieldReader> {
|
pub fn bytes(&self, field: Field) -> crate::Result<BytesFastFieldReader> {
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ use std::io;
|
|||||||
use common;
|
use common;
|
||||||
use fastfield_codecs::{Column, MonotonicallyMappableToU64};
|
use fastfield_codecs::{Column, MonotonicallyMappableToU64};
|
||||||
use fnv::FnvHashMap;
|
use fnv::FnvHashMap;
|
||||||
use measure_time::{debug_time, trace_time};
|
|
||||||
use tantivy_bitpacker::BlockedBitpacker;
|
use tantivy_bitpacker::BlockedBitpacker;
|
||||||
|
|
||||||
use super::multivalued::MultiValuedFastFieldWriter;
|
use super::multivalued::MultiValuedFastFieldWriter;
|
||||||
@@ -132,7 +131,7 @@ impl FastFieldsWriter {
|
|||||||
.sum::<usize>()
|
.sum::<usize>()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the `FastFieldWriter` associated to a field.
|
/// Get the `FastFieldWriter` associated with a field.
|
||||||
pub fn get_term_id_writer(&self, field: Field) -> Option<&MultiValuedFastFieldWriter> {
|
pub fn get_term_id_writer(&self, field: Field) -> Option<&MultiValuedFastFieldWriter> {
|
||||||
// TODO optimize
|
// TODO optimize
|
||||||
self.term_id_writers
|
self.term_id_writers
|
||||||
@@ -140,7 +139,7 @@ impl FastFieldsWriter {
|
|||||||
.find(|field_writer| field_writer.field() == field)
|
.find(|field_writer| field_writer.field() == field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the `FastFieldWriter` associated to a field.
|
/// Get the `FastFieldWriter` associated with a field.
|
||||||
pub fn get_field_writer(&self, field: Field) -> Option<&IntFastFieldWriter> {
|
pub fn get_field_writer(&self, field: Field) -> Option<&IntFastFieldWriter> {
|
||||||
// TODO optimize
|
// TODO optimize
|
||||||
self.single_value_writers
|
self.single_value_writers
|
||||||
@@ -148,7 +147,7 @@ impl FastFieldsWriter {
|
|||||||
.find(|field_writer| field_writer.field() == field)
|
.find(|field_writer| field_writer.field() == field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the `FastFieldWriter` associated to a field.
|
/// Get the `FastFieldWriter` associated with a field.
|
||||||
pub fn get_field_writer_mut(&mut self, field: Field) -> Option<&mut IntFastFieldWriter> {
|
pub fn get_field_writer_mut(&mut self, field: Field) -> Option<&mut IntFastFieldWriter> {
|
||||||
// TODO optimize
|
// TODO optimize
|
||||||
self.single_value_writers
|
self.single_value_writers
|
||||||
@@ -156,7 +155,7 @@ impl FastFieldsWriter {
|
|||||||
.find(|field_writer| field_writer.field() == field)
|
.find(|field_writer| field_writer.field() == field)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the `FastFieldWriter` associated to a field.
|
/// Get the `FastFieldWriter` associated with a field.
|
||||||
pub fn get_term_id_writer_mut(
|
pub fn get_term_id_writer_mut(
|
||||||
&mut self,
|
&mut self,
|
||||||
field: Field,
|
field: Field,
|
||||||
@@ -216,7 +215,6 @@ impl FastFieldsWriter {
|
|||||||
mapping: &HashMap<Field, FnvHashMap<UnorderedTermId, TermOrdinal>>,
|
mapping: &HashMap<Field, FnvHashMap<UnorderedTermId, TermOrdinal>>,
|
||||||
doc_id_map: Option<&DocIdMapping>,
|
doc_id_map: Option<&DocIdMapping>,
|
||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
debug_time!("segment-serialize-all-fast-fields",);
|
|
||||||
for field_writer in self.term_id_writers {
|
for field_writer in self.term_id_writers {
|
||||||
let field = field_writer.field();
|
let field = field_writer.field();
|
||||||
field_writer.serialize(serializer, mapping.get(&field), doc_id_map)?;
|
field_writer.serialize(serializer, mapping.get(&field), doc_id_map)?;
|
||||||
@@ -296,7 +294,7 @@ impl IntFastFieldWriter {
|
|||||||
/// Records a new value.
|
/// Records a new value.
|
||||||
///
|
///
|
||||||
/// The n-th value being recorded is implicitly
|
/// The n-th value being recorded is implicitly
|
||||||
/// associated to the document with the `DocId` n.
|
/// associated with the document with the `DocId` n.
|
||||||
/// (Well, `n-1` actually because of 0-indexing)
|
/// (Well, `n-1` actually because of 0-indexing)
|
||||||
pub fn add_val(&mut self, val: u64) {
|
pub fn add_val(&mut self, val: u64) {
|
||||||
self.vals.add(val);
|
self.vals.add(val);
|
||||||
@@ -315,7 +313,7 @@ impl IntFastFieldWriter {
|
|||||||
/// (or use the default value) and records it.
|
/// (or use the default value) and records it.
|
||||||
///
|
///
|
||||||
///
|
///
|
||||||
/// Extract the value associated to the fast field for
|
/// Extract the value associated with the fast field for
|
||||||
/// this document.
|
/// this document.
|
||||||
///
|
///
|
||||||
/// i64 and f64 are remapped to u64 using the logic
|
/// i64 and f64 are remapped to u64 using the logic
|
||||||
@@ -369,11 +367,6 @@ impl IntFastFieldWriter {
|
|||||||
num_vals: self.val_count as u64,
|
num_vals: self.val_count as u64,
|
||||||
};
|
};
|
||||||
|
|
||||||
trace_time!(
|
|
||||||
"segment-serialize-single-value-field, field_id {:?}",
|
|
||||||
self.field()
|
|
||||||
);
|
|
||||||
|
|
||||||
serializer.create_auto_detect_u64_fast_field(self.field, fastfield_accessor)?;
|
serializer.create_auto_detect_u64_fast_field(self.field, fastfield_accessor)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -390,7 +383,7 @@ struct WriterFastFieldAccessProvider<'map, 'bitp> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'map, 'bitp> Column for WriterFastFieldAccessProvider<'map, 'bitp> {
|
impl<'map, 'bitp> Column for WriterFastFieldAccessProvider<'map, 'bitp> {
|
||||||
/// Return the value associated to the given doc.
|
/// Return the value associated with the given doc.
|
||||||
///
|
///
|
||||||
/// Whenever possible use the Iterator passed to the fastfield creation instead, for performance
|
/// Whenever possible use the Iterator passed to the fastfield creation instead, for performance
|
||||||
/// reasons.
|
/// reasons.
|
||||||
@@ -398,15 +391,8 @@ impl<'map, 'bitp> Column for WriterFastFieldAccessProvider<'map, 'bitp> {
|
|||||||
/// # Panics
|
/// # Panics
|
||||||
///
|
///
|
||||||
/// May panic if `doc` is greater than the index.
|
/// May panic if `doc` is greater than the index.
|
||||||
fn get_val(&self, doc: u64) -> u64 {
|
fn get_val(&self, _doc: u64) -> u64 {
|
||||||
if let Some(doc_id_map) = self.doc_id_map {
|
unimplemented!()
|
||||||
self.vals
|
|
||||||
.get(doc_id_map.get_old_doc_id(doc as u32) as usize) // consider extra
|
|
||||||
// FastFieldReader wrapper for
|
|
||||||
// non doc_id_map
|
|
||||||
} else {
|
|
||||||
self.vals.get(doc as usize)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn iter(&self) -> Box<dyn Iterator<Item = u64> + '_> {
|
fn iter(&self) -> Box<dyn Iterator<Item = u64> + '_> {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! The fieldnorm represents the length associated to
|
//! The fieldnorm represents the length associated with
|
||||||
//! a given Field of a given document.
|
//! a given Field of a given document.
|
||||||
//!
|
//!
|
||||||
//! This metric is important to compute the score of a
|
//! This metric is important to compute the score of a
|
||||||
|
|||||||
@@ -47,9 +47,9 @@ impl FieldNormReaders {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads the fieldnorm associated to a document.
|
/// Reads the fieldnorm associated with a document.
|
||||||
///
|
///
|
||||||
/// The [fieldnorm](FieldNormReader::fieldnorm) represents the length associated to
|
/// The [fieldnorm](FieldNormReader::fieldnorm) represents the length associated with
|
||||||
/// a given Field of a given document.
|
/// a given Field of a given document.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct FieldNormReader(ReaderImplEnum);
|
pub struct FieldNormReader(ReaderImplEnum);
|
||||||
@@ -104,7 +104,7 @@ impl FieldNormReader {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the `fieldnorm` associated to a doc id.
|
/// Returns the `fieldnorm` associated with a doc id.
|
||||||
/// The fieldnorm is a value approximating the number
|
/// The fieldnorm is a value approximating the number
|
||||||
/// of tokens in a given field of the `doc_id`.
|
/// of tokens in a given field of the `doc_id`.
|
||||||
///
|
///
|
||||||
@@ -123,7 +123,7 @@ impl FieldNormReader {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the `fieldnorm_id` associated to a document.
|
/// Returns the `fieldnorm_id` associated with a document.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn fieldnorm_id(&self, doc_id: DocId) -> u8 {
|
pub fn fieldnorm_id(&self, doc_id: DocId) -> u8 {
|
||||||
match &self.0 {
|
match &self.0 {
|
||||||
|
|||||||
@@ -188,7 +188,7 @@ impl DeleteCursor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(feature = "cargo-clippy", allow(clippy::wrong_self_convention))]
|
#[allow(clippy::wrong_self_convention)]
|
||||||
fn is_behind_opstamp(&mut self, target_opstamp: Opstamp) -> bool {
|
fn is_behind_opstamp(&mut self, target_opstamp: Opstamp) -> bool {
|
||||||
self.get()
|
self.get()
|
||||||
.map(|operation| operation.opstamp < target_opstamp)
|
.map(|operation| operation.opstamp < target_opstamp)
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ impl SegmentDocIdMapping {
|
|||||||
|
|
||||||
/// Returns an iterator over the old document addresses, ordered by the new document ids.
|
/// Returns an iterator over the old document addresses, ordered by the new document ids.
|
||||||
///
|
///
|
||||||
/// In the returned `DocAddress`, the `segment_ord` is the ordinal of targetted segment
|
/// In the returned `DocAddress`, the `segment_ord` is the ordinal of targeted segment
|
||||||
/// in the list of merged segments.
|
/// in the list of merged segments.
|
||||||
pub(crate) fn iter_old_doc_addrs(&self) -> impl Iterator<Item = DocAddress> + '_ {
|
pub(crate) fn iter_old_doc_addrs(&self) -> impl Iterator<Item = DocAddress> + '_ {
|
||||||
self.new_doc_id_to_old_doc_addr.iter().copied()
|
self.new_doc_id_to_old_doc_addr.iter().copied()
|
||||||
@@ -34,10 +34,6 @@ impl SegmentDocIdMapping {
|
|||||||
self.new_doc_id_to_old_doc_addr.len()
|
self.new_doc_id_to_old_doc_addr.len()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn get_old_doc_addr(&self, new_doc_id: DocId) -> DocAddress {
|
|
||||||
self.new_doc_id_to_old_doc_addr[new_doc_id as usize]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This flags means the segments are simply stacked in the order of their ordinal.
|
/// This flags means the segments are simply stacked in the order of their ordinal.
|
||||||
/// e.g. [(0, 1), .. (n, 1), (0, 2)..., (m, 2)]
|
/// e.g. [(0, 1), .. (n, 1), (0, 2)..., (m, 2)]
|
||||||
///
|
///
|
||||||
|
|||||||
@@ -370,9 +370,9 @@ impl IndexWriter {
|
|||||||
/// This method is useful only for users trying to do complex
|
/// This method is useful only for users trying to do complex
|
||||||
/// operations, like converting an index format to another.
|
/// operations, like converting an index format to another.
|
||||||
///
|
///
|
||||||
/// It is safe to start writing file associated to the new `Segment`.
|
/// It is safe to start writing file associated with the new `Segment`.
|
||||||
/// These will not be garbage collected as long as an instance object of
|
/// These will not be garbage collected as long as an instance object of
|
||||||
/// `SegmentMeta` object associated to the new `Segment` is "alive".
|
/// `SegmentMeta` object associated with the new `Segment` is "alive".
|
||||||
pub fn new_segment(&self) -> Segment {
|
pub fn new_segment(&self) -> Segment {
|
||||||
self.index.new_segment()
|
self.index.new_segment()
|
||||||
}
|
}
|
||||||
@@ -1395,6 +1395,35 @@ mod tests {
|
|||||||
assert!(commit_again.is_ok());
|
assert!(commit_again.is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_sort_by_multivalue_field_error() -> crate::Result<()> {
|
||||||
|
let mut schema_builder = schema::Schema::builder();
|
||||||
|
let options = NumericOptions::default().set_fast(Cardinality::MultiValues);
|
||||||
|
schema_builder.add_u64_field("id", options);
|
||||||
|
let schema = schema_builder.build();
|
||||||
|
|
||||||
|
let settings = IndexSettings {
|
||||||
|
sort_by_field: Some(IndexSortByField {
|
||||||
|
field: "id".to_string(),
|
||||||
|
order: Order::Desc,
|
||||||
|
}),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let err = Index::builder()
|
||||||
|
.schema(schema)
|
||||||
|
.settings(settings)
|
||||||
|
.create_in_ram()
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
err.to_string(),
|
||||||
|
"An invalid argument was passed: 'Only single value fast field Cardinality supported \
|
||||||
|
for sorting index id'"
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_delete_with_sort_by_field() -> crate::Result<()> {
|
fn test_delete_with_sort_by_field() -> crate::Result<()> {
|
||||||
let mut schema_builder = schema::Schema::builder();
|
let mut schema_builder = schema::Schema::builder();
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
use fastfield_codecs::VecColumn;
|
use fastfield_codecs::VecColumn;
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use measure_time::{debug_time, trace_time};
|
use measure_time::debug_time;
|
||||||
|
|
||||||
use crate::core::{Segment, SegmentReader};
|
use crate::core::{Segment, SegmentReader};
|
||||||
use crate::docset::{DocSet, TERMINATED};
|
use crate::docset::{DocSet, TERMINATED};
|
||||||
@@ -14,8 +14,8 @@ use crate::fastfield::{
|
|||||||
};
|
};
|
||||||
use crate::fieldnorm::{FieldNormReader, FieldNormReaders, FieldNormsSerializer, FieldNormsWriter};
|
use crate::fieldnorm::{FieldNormReader, FieldNormReaders, FieldNormsSerializer, FieldNormsWriter};
|
||||||
use crate::indexer::doc_id_mapping::{expect_field_id_for_sort_field, SegmentDocIdMapping};
|
use crate::indexer::doc_id_mapping::{expect_field_id_for_sort_field, SegmentDocIdMapping};
|
||||||
use crate::indexer::sorted_doc_id_column::SortedDocIdColumn;
|
use crate::indexer::sorted_doc_id_column::RemappedDocIdColumn;
|
||||||
use crate::indexer::sorted_doc_id_multivalue_column::SortedDocIdMultiValueColumn;
|
use crate::indexer::sorted_doc_id_multivalue_column::RemappedDocIdMultiValueColumn;
|
||||||
use crate::indexer::SegmentSerializer;
|
use crate::indexer::SegmentSerializer;
|
||||||
use crate::postings::{InvertedIndexSerializer, Postings, SegmentPostings};
|
use crate::postings::{InvertedIndexSerializer, Postings, SegmentPostings};
|
||||||
use crate::schema::{Cardinality, Field, FieldType, Schema};
|
use crate::schema::{Cardinality, Field, FieldType, Schema};
|
||||||
@@ -250,11 +250,7 @@ impl IndexMerger {
|
|||||||
mut term_ord_mappings: HashMap<Field, TermOrdinalMapping>,
|
mut term_ord_mappings: HashMap<Field, TermOrdinalMapping>,
|
||||||
doc_id_mapping: &SegmentDocIdMapping,
|
doc_id_mapping: &SegmentDocIdMapping,
|
||||||
) -> crate::Result<()> {
|
) -> crate::Result<()> {
|
||||||
debug_time!(
|
debug_time!("write-fast-fields");
|
||||||
"merge-all-fast-fields, num_segments {}, num docs new segment {}",
|
|
||||||
self.readers.len(),
|
|
||||||
doc_id_mapping.len()
|
|
||||||
);
|
|
||||||
|
|
||||||
for (field, field_entry) in self.schema.fields() {
|
for (field, field_entry) in self.schema.fields() {
|
||||||
let field_type = field_entry.field_type();
|
let field_type = field_entry.field_type();
|
||||||
@@ -314,13 +310,7 @@ impl IndexMerger {
|
|||||||
fast_field_serializer: &mut CompositeFastFieldSerializer,
|
fast_field_serializer: &mut CompositeFastFieldSerializer,
|
||||||
doc_id_mapping: &SegmentDocIdMapping,
|
doc_id_mapping: &SegmentDocIdMapping,
|
||||||
) -> crate::Result<()> {
|
) -> crate::Result<()> {
|
||||||
let fast_field_accessor = SortedDocIdColumn::new(&self.readers, doc_id_mapping, field);
|
let fast_field_accessor = RemappedDocIdColumn::new(&self.readers, doc_id_mapping, field);
|
||||||
trace_time!(
|
|
||||||
"merge-single-fast-field, num_vals {}, num_segments {}, field_id {:?}",
|
|
||||||
fast_field_accessor.num_vals(),
|
|
||||||
self.readers.len(),
|
|
||||||
field
|
|
||||||
);
|
|
||||||
fast_field_serializer.create_auto_detect_u64_fast_field(field, fast_field_accessor)?;
|
fast_field_serializer.create_auto_detect_u64_fast_field(field, fast_field_accessor)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -438,14 +428,8 @@ impl IndexMerger {
|
|||||||
fast_field_serializer: &mut CompositeFastFieldSerializer,
|
fast_field_serializer: &mut CompositeFastFieldSerializer,
|
||||||
doc_id_mapping: &SegmentDocIdMapping,
|
doc_id_mapping: &SegmentDocIdMapping,
|
||||||
reader_and_field_accessors: &[(&SegmentReader, T)],
|
reader_and_field_accessors: &[(&SegmentReader, T)],
|
||||||
) -> crate::Result<Vec<u64>> {
|
) -> crate::Result<()> {
|
||||||
// We can now create our `idx` serializer, and in a second pass,
|
// TODO Use `Column` implementation instead
|
||||||
// can effectively push the different indexes.
|
|
||||||
|
|
||||||
// copying into a temp vec is not ideal, but the fast field codec api requires random
|
|
||||||
// access, which is used in the estimation. It's possible to 1. calculate random
|
|
||||||
// access on the fly or 2. change the codec api to make random access optional, but
|
|
||||||
// they both have also major drawbacks.
|
|
||||||
|
|
||||||
let mut offsets = Vec::with_capacity(doc_id_mapping.len());
|
let mut offsets = Vec::with_capacity(doc_id_mapping.len());
|
||||||
let mut offset = 0;
|
let mut offset = 0;
|
||||||
@@ -459,7 +443,7 @@ impl IndexMerger {
|
|||||||
let fastfield_accessor = VecColumn::from(&offsets[..]);
|
let fastfield_accessor = VecColumn::from(&offsets[..]);
|
||||||
|
|
||||||
fast_field_serializer.create_auto_detect_u64_fast_field(field, fastfield_accessor)?;
|
fast_field_serializer.create_auto_detect_u64_fast_field(field, fastfield_accessor)?;
|
||||||
Ok(offsets)
|
Ok(())
|
||||||
}
|
}
|
||||||
/// Returns the fastfield index (index for the data, not the data).
|
/// Returns the fastfield index (index for the data, not the data).
|
||||||
fn write_multi_value_fast_field_idx(
|
fn write_multi_value_fast_field_idx(
|
||||||
@@ -467,13 +451,7 @@ impl IndexMerger {
|
|||||||
field: Field,
|
field: Field,
|
||||||
fast_field_serializer: &mut CompositeFastFieldSerializer,
|
fast_field_serializer: &mut CompositeFastFieldSerializer,
|
||||||
doc_id_mapping: &SegmentDocIdMapping,
|
doc_id_mapping: &SegmentDocIdMapping,
|
||||||
) -> crate::Result<Vec<u64>> {
|
) -> crate::Result<()> {
|
||||||
trace_time!(
|
|
||||||
"merge-multi-fast-field-idx, num_segments {}, field_id {:?}",
|
|
||||||
self.readers.len(),
|
|
||||||
field
|
|
||||||
);
|
|
||||||
|
|
||||||
let reader_ordinal_and_field_accessors = self
|
let reader_ordinal_and_field_accessors = self
|
||||||
.readers
|
.readers
|
||||||
.iter()
|
.iter()
|
||||||
@@ -504,7 +482,7 @@ impl IndexMerger {
|
|||||||
fast_field_serializer: &mut CompositeFastFieldSerializer,
|
fast_field_serializer: &mut CompositeFastFieldSerializer,
|
||||||
doc_id_mapping: &SegmentDocIdMapping,
|
doc_id_mapping: &SegmentDocIdMapping,
|
||||||
) -> crate::Result<()> {
|
) -> crate::Result<()> {
|
||||||
trace_time!("write-term-id-fast-field");
|
debug_time!("write-term-id-fast-field");
|
||||||
|
|
||||||
// Multifastfield consists of 2 fastfields.
|
// Multifastfield consists of 2 fastfields.
|
||||||
// The first serves as an index into the second one and is strictly increasing.
|
// The first serves as an index into the second one and is strictly increasing.
|
||||||
@@ -577,23 +555,16 @@ impl IndexMerger {
|
|||||||
fast_field_serializer: &mut CompositeFastFieldSerializer,
|
fast_field_serializer: &mut CompositeFastFieldSerializer,
|
||||||
doc_id_mapping: &SegmentDocIdMapping,
|
doc_id_mapping: &SegmentDocIdMapping,
|
||||||
) -> crate::Result<()> {
|
) -> crate::Result<()> {
|
||||||
// Multifastfield consists in 2 fastfields.
|
// Multifastfield consists of 2 fastfields.
|
||||||
// The first serves as an index into the second one and is strictly increasing.
|
// The first serves as an index into the second one and is strictly increasing.
|
||||||
// The second contains the actual values.
|
// The second contains the actual values.
|
||||||
|
|
||||||
// First we merge the idx fast field.
|
// First we merge the idx fast field.
|
||||||
let offsets =
|
|
||||||
self.write_multi_value_fast_field_idx(field, fast_field_serializer, doc_id_mapping)?;
|
self.write_multi_value_fast_field_idx(field, fast_field_serializer, doc_id_mapping)?;
|
||||||
|
|
||||||
let fastfield_accessor =
|
let fastfield_accessor =
|
||||||
SortedDocIdMultiValueColumn::new(&self.readers, doc_id_mapping, &offsets, field);
|
RemappedDocIdMultiValueColumn::new(&self.readers, doc_id_mapping, field);
|
||||||
trace_time!(
|
|
||||||
"merge-multi-fast-field-values, num_vals {}, num_segments {}, field_id {:?}",
|
|
||||||
fastfield_accessor.num_vals(),
|
|
||||||
self.readers.len(),
|
|
||||||
field
|
|
||||||
);
|
|
||||||
|
|
||||||
fast_field_serializer.create_auto_detect_u64_fast_field_with_idx(
|
fast_field_serializer.create_auto_detect_u64_fast_field_with_idx(
|
||||||
field,
|
field,
|
||||||
fastfield_accessor,
|
fastfield_accessor,
|
||||||
@@ -647,7 +618,7 @@ impl IndexMerger {
|
|||||||
fieldnorm_reader: Option<FieldNormReader>,
|
fieldnorm_reader: Option<FieldNormReader>,
|
||||||
doc_id_mapping: &SegmentDocIdMapping,
|
doc_id_mapping: &SegmentDocIdMapping,
|
||||||
) -> crate::Result<Option<TermOrdinalMapping>> {
|
) -> crate::Result<Option<TermOrdinalMapping>> {
|
||||||
debug_time!("write-postings-for-field {:?}", indexed_field);
|
debug_time!("write-postings-for-field");
|
||||||
let mut positions_buffer: Vec<u32> = Vec::with_capacity(1_000);
|
let mut positions_buffer: Vec<u32> = Vec::with_capacity(1_000);
|
||||||
let mut delta_computer = DeltaComputer::new();
|
let mut delta_computer = DeltaComputer::new();
|
||||||
|
|
||||||
@@ -850,7 +821,7 @@ impl IndexMerger {
|
|||||||
debug!("write-storable-field");
|
debug!("write-storable-field");
|
||||||
|
|
||||||
if !doc_id_mapping.is_trivial() {
|
if !doc_id_mapping.is_trivial() {
|
||||||
debug!("non-trivial-doc-id-mapping (index is sorted)");
|
debug!("non-trivial-doc-id-mapping");
|
||||||
|
|
||||||
let store_readers: Vec<_> = self
|
let store_readers: Vec<_> = self
|
||||||
.readers
|
.readers
|
||||||
@@ -878,7 +849,7 @@ impl IndexMerger {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
debug!("trivial-doc-id-mapping (index is not sorted)");
|
debug!("trivial-doc-id-mapping");
|
||||||
for reader in &self.readers {
|
for reader in &self.readers {
|
||||||
let store_reader = reader.get_store_reader(1)?;
|
let store_reader = reader.get_store_reader(1)?;
|
||||||
if reader.has_deletes()
|
if reader.has_deletes()
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ impl<'a> PreparedCommit<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the opstamp associated to the prepared commit.
|
/// Returns the opstamp associated with the prepared commit.
|
||||||
pub fn opstamp(&self) -> Opstamp {
|
pub fn opstamp(&self) -> Opstamp {
|
||||||
self.opstamp
|
self.opstamp
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,12 +24,25 @@ impl SegmentSerializer {
|
|||||||
// In the merge case this is not necessary because we can kmerge the already sorted
|
// In the merge case this is not necessary because we can kmerge the already sorted
|
||||||
// segments
|
// segments
|
||||||
let remapping_required = segment.index().settings().sort_by_field.is_some() && !is_in_merge;
|
let remapping_required = segment.index().settings().sort_by_field.is_some() && !is_in_merge;
|
||||||
let store_component = if remapping_required {
|
let settings = segment.index().settings().clone();
|
||||||
SegmentComponent::TempStore
|
let store_writer = if remapping_required {
|
||||||
|
let store_write = segment.open_write(SegmentComponent::TempStore)?;
|
||||||
|
StoreWriter::new(
|
||||||
|
store_write,
|
||||||
|
crate::store::Compressor::None,
|
||||||
|
0, // we want random access on the docs, so we choose a minimal block size. Every
|
||||||
|
// doc will get its own block.
|
||||||
|
settings.docstore_compress_dedicated_thread,
|
||||||
|
)?
|
||||||
} else {
|
} else {
|
||||||
SegmentComponent::Store
|
let store_write = segment.open_write(SegmentComponent::Store)?;
|
||||||
|
StoreWriter::new(
|
||||||
|
store_write,
|
||||||
|
settings.docstore_compression,
|
||||||
|
settings.docstore_blocksize,
|
||||||
|
settings.docstore_compress_dedicated_thread,
|
||||||
|
)?
|
||||||
};
|
};
|
||||||
let store_write = segment.open_write(store_component)?;
|
|
||||||
|
|
||||||
let fast_field_write = segment.open_write(SegmentComponent::FastFields)?;
|
let fast_field_write = segment.open_write(SegmentComponent::FastFields)?;
|
||||||
let fast_field_serializer = CompositeFastFieldSerializer::from_write(fast_field_write)?;
|
let fast_field_serializer = CompositeFastFieldSerializer::from_write(fast_field_write)?;
|
||||||
@@ -38,13 +51,6 @@ impl SegmentSerializer {
|
|||||||
let fieldnorms_serializer = FieldNormsSerializer::from_write(fieldnorms_write)?;
|
let fieldnorms_serializer = FieldNormsSerializer::from_write(fieldnorms_write)?;
|
||||||
|
|
||||||
let postings_serializer = InvertedIndexSerializer::open(&mut segment)?;
|
let postings_serializer = InvertedIndexSerializer::open(&mut segment)?;
|
||||||
let settings = segment.index().settings();
|
|
||||||
let store_writer = StoreWriter::new(
|
|
||||||
store_write,
|
|
||||||
settings.docstore_compression,
|
|
||||||
settings.docstore_blocksize,
|
|
||||||
settings.docstore_compress_dedicated_thread,
|
|
||||||
)?;
|
|
||||||
Ok(SegmentSerializer {
|
Ok(SegmentSerializer {
|
||||||
segment,
|
segment,
|
||||||
store_writer,
|
store_writer,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use fastfield_codecs::MonotonicallyMappableToU64;
|
use fastfield_codecs::MonotonicallyMappableToU64;
|
||||||
|
use itertools::Itertools;
|
||||||
|
|
||||||
use super::doc_id_mapping::{get_doc_id_mapping_from_field, DocIdMapping};
|
use super::doc_id_mapping::{get_doc_id_mapping_from_field, DocIdMapping};
|
||||||
use super::operation::AddOperation;
|
use super::operation::AddOperation;
|
||||||
@@ -157,7 +158,13 @@ impl SegmentWriter {
|
|||||||
|
|
||||||
fn index_document(&mut self, doc: &Document) -> crate::Result<()> {
|
fn index_document(&mut self, doc: &Document) -> crate::Result<()> {
|
||||||
let doc_id = self.max_doc;
|
let doc_id = self.max_doc;
|
||||||
for (field, values) in doc.get_sorted_field_values() {
|
let vals_grouped_by_field = doc
|
||||||
|
.field_values()
|
||||||
|
.iter()
|
||||||
|
.sorted_by_key(|el| el.field())
|
||||||
|
.group_by(|el| el.field());
|
||||||
|
for (field, field_values) in &vals_grouped_by_field {
|
||||||
|
let values = field_values.map(|field_value| field_value.value());
|
||||||
let field_entry = self.schema.get_field_entry(field);
|
let field_entry = self.schema.get_field_entry(field);
|
||||||
let make_schema_error = || {
|
let make_schema_error = || {
|
||||||
crate::TantivyError::SchemaError(format!(
|
crate::TantivyError::SchemaError(format!(
|
||||||
@@ -198,24 +205,16 @@ impl SegmentWriter {
|
|||||||
}
|
}
|
||||||
FieldType::Str(_) => {
|
FieldType::Str(_) => {
|
||||||
let mut token_streams: Vec<BoxTokenStream> = vec![];
|
let mut token_streams: Vec<BoxTokenStream> = vec![];
|
||||||
let mut offsets = vec![];
|
|
||||||
let mut total_offset = 0;
|
|
||||||
|
|
||||||
for value in values {
|
for value in values {
|
||||||
match value {
|
match value {
|
||||||
Value::PreTokStr(tok_str) => {
|
Value::PreTokStr(tok_str) => {
|
||||||
offsets.push(total_offset);
|
|
||||||
if let Some(last_token) = tok_str.tokens.last() {
|
|
||||||
total_offset += last_token.offset_to;
|
|
||||||
}
|
|
||||||
token_streams
|
token_streams
|
||||||
.push(PreTokenizedStream::from(tok_str.clone()).into());
|
.push(PreTokenizedStream::from(tok_str.clone()).into());
|
||||||
}
|
}
|
||||||
Value::Str(ref text) => {
|
Value::Str(ref text) => {
|
||||||
let text_analyzer =
|
let text_analyzer =
|
||||||
&self.per_field_text_analyzers[field.field_id() as usize];
|
&self.per_field_text_analyzers[field.field_id() as usize];
|
||||||
offsets.push(total_offset);
|
|
||||||
total_offset += text.len();
|
|
||||||
token_streams.push(text_analyzer.token_stream(text));
|
token_streams.push(text_analyzer.token_stream(text));
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
@@ -284,9 +283,8 @@ impl SegmentWriter {
|
|||||||
}
|
}
|
||||||
FieldType::JsonObject(_) => {
|
FieldType::JsonObject(_) => {
|
||||||
let text_analyzer = &self.per_field_text_analyzers[field.field_id() as usize];
|
let text_analyzer = &self.per_field_text_analyzers[field.field_id() as usize];
|
||||||
let json_values_it = values
|
let json_values_it =
|
||||||
.iter()
|
values.map(|value| value.as_json().ok_or_else(make_schema_error));
|
||||||
.map(|value| value.as_json().ok_or_else(make_schema_error));
|
|
||||||
index_json_values(
|
index_json_values(
|
||||||
doc_id,
|
doc_id,
|
||||||
json_values_it,
|
json_values_it,
|
||||||
@@ -374,9 +372,9 @@ fn remap_and_write(
|
|||||||
doc_id_map,
|
doc_id_map,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
debug!("resort-docstore");
|
|
||||||
// finalize temp docstore and create version, which reflects the doc_id_map
|
// finalize temp docstore and create version, which reflects the doc_id_map
|
||||||
if let Some(doc_id_map) = doc_id_map {
|
if let Some(doc_id_map) = doc_id_map {
|
||||||
|
debug!("resort-docstore");
|
||||||
let store_write = serializer
|
let store_write = serializer
|
||||||
.segment_mut()
|
.segment_mut()
|
||||||
.open_write(SegmentComponent::Store)?;
|
.open_write(SegmentComponent::Store)?;
|
||||||
@@ -393,7 +391,8 @@ fn remap_and_write(
|
|||||||
serializer
|
serializer
|
||||||
.segment()
|
.segment()
|
||||||
.open_read(SegmentComponent::TempStore)?,
|
.open_read(SegmentComponent::TempStore)?,
|
||||||
50,
|
1, /* The docstore is configured to have one doc per block, and each doc is accessed
|
||||||
|
* only once: we don't need caching. */
|
||||||
)?;
|
)?;
|
||||||
for old_doc_id in doc_id_map.iter_old_doc_ids() {
|
for old_doc_id in doc_id_map.iter_old_doc_ids() {
|
||||||
let doc_bytes = store_read.get_document_bytes(old_doc_id)?;
|
let doc_bytes = store_read.get_document_bytes(old_doc_id)?;
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ use itertools::Itertools;
|
|||||||
|
|
||||||
use crate::indexer::doc_id_mapping::SegmentDocIdMapping;
|
use crate::indexer::doc_id_mapping::SegmentDocIdMapping;
|
||||||
use crate::schema::Field;
|
use crate::schema::Field;
|
||||||
use crate::{DocAddress, SegmentReader};
|
use crate::SegmentReader;
|
||||||
|
|
||||||
pub(crate) struct SortedDocIdColumn<'a> {
|
pub(crate) struct RemappedDocIdColumn<'a> {
|
||||||
doc_id_mapping: &'a SegmentDocIdMapping,
|
doc_id_mapping: &'a SegmentDocIdMapping,
|
||||||
fast_field_readers: Vec<Arc<dyn Column<u64>>>,
|
fast_field_readers: Vec<Arc<dyn Column<u64>>>,
|
||||||
min_value: u64,
|
min_value: u64,
|
||||||
@@ -37,7 +37,7 @@ fn compute_min_max_val(
|
|||||||
.into_option()
|
.into_option()
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> SortedDocIdColumn<'a> {
|
impl<'a> RemappedDocIdColumn<'a> {
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
readers: &'a [SegmentReader],
|
readers: &'a [SegmentReader],
|
||||||
doc_id_mapping: &'a SegmentDocIdMapping,
|
doc_id_mapping: &'a SegmentDocIdMapping,
|
||||||
@@ -68,7 +68,7 @@ impl<'a> SortedDocIdColumn<'a> {
|
|||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
SortedDocIdColumn {
|
RemappedDocIdColumn {
|
||||||
doc_id_mapping,
|
doc_id_mapping,
|
||||||
fast_field_readers,
|
fast_field_readers,
|
||||||
min_value,
|
min_value,
|
||||||
@@ -78,13 +78,9 @@ impl<'a> SortedDocIdColumn<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> Column for SortedDocIdColumn<'a> {
|
impl<'a> Column for RemappedDocIdColumn<'a> {
|
||||||
fn get_val(&self, doc: u64) -> u64 {
|
fn get_val(&self, _doc: u64) -> u64 {
|
||||||
let DocAddress {
|
unimplemented!()
|
||||||
doc_id,
|
|
||||||
segment_ord,
|
|
||||||
} = self.doc_id_mapping.get_old_doc_addr(doc as u32);
|
|
||||||
self.fast_field_readers[segment_ord as usize].get_val(doc_id as u64)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn iter(&self) -> Box<dyn Iterator<Item = u64> + '_> {
|
fn iter(&self) -> Box<dyn Iterator<Item = u64> + '_> {
|
||||||
|
|||||||
@@ -2,26 +2,23 @@ use std::cmp;
|
|||||||
|
|
||||||
use fastfield_codecs::Column;
|
use fastfield_codecs::Column;
|
||||||
|
|
||||||
use crate::fastfield::{MultiValueLength, MultiValuedFastFieldReader};
|
use crate::fastfield::MultiValuedFastFieldReader;
|
||||||
use crate::indexer::doc_id_mapping::SegmentDocIdMapping;
|
use crate::indexer::doc_id_mapping::SegmentDocIdMapping;
|
||||||
use crate::schema::Field;
|
use crate::schema::Field;
|
||||||
use crate::{DocId, SegmentReader};
|
use crate::SegmentReader;
|
||||||
|
|
||||||
// We can now initialize our serializer, and push it the different values
|
pub(crate) struct RemappedDocIdMultiValueColumn<'a> {
|
||||||
pub(crate) struct SortedDocIdMultiValueColumn<'a> {
|
|
||||||
doc_id_mapping: &'a SegmentDocIdMapping,
|
doc_id_mapping: &'a SegmentDocIdMapping,
|
||||||
fast_field_readers: Vec<MultiValuedFastFieldReader<u64>>,
|
fast_field_readers: Vec<MultiValuedFastFieldReader<u64>>,
|
||||||
offsets: &'a [u64],
|
|
||||||
min_value: u64,
|
min_value: u64,
|
||||||
max_value: u64,
|
max_value: u64,
|
||||||
num_vals: u64,
|
num_vals: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> SortedDocIdMultiValueColumn<'a> {
|
impl<'a> RemappedDocIdMultiValueColumn<'a> {
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
readers: &'a [SegmentReader],
|
readers: &'a [SegmentReader],
|
||||||
doc_id_mapping: &'a SegmentDocIdMapping,
|
doc_id_mapping: &'a SegmentDocIdMapping,
|
||||||
offsets: &'a [u64],
|
|
||||||
field: Field,
|
field: Field,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
// Our values are bitpacked and we need to know what should be
|
// Our values are bitpacked and we need to know what should be
|
||||||
@@ -58,10 +55,9 @@ impl<'a> SortedDocIdMultiValueColumn<'a> {
|
|||||||
min_value = 0;
|
min_value = 0;
|
||||||
max_value = 0;
|
max_value = 0;
|
||||||
}
|
}
|
||||||
SortedDocIdMultiValueColumn {
|
RemappedDocIdMultiValueColumn {
|
||||||
doc_id_mapping,
|
doc_id_mapping,
|
||||||
fast_field_readers,
|
fast_field_readers,
|
||||||
offsets,
|
|
||||||
min_value,
|
min_value,
|
||||||
max_value,
|
max_value,
|
||||||
num_vals: num_vals as u64,
|
num_vals: num_vals as u64,
|
||||||
@@ -69,30 +65,9 @@ impl<'a> SortedDocIdMultiValueColumn<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> Column for SortedDocIdMultiValueColumn<'a> {
|
impl<'a> Column for RemappedDocIdMultiValueColumn<'a> {
|
||||||
fn get_val(&self, pos: u64) -> u64 {
|
fn get_val(&self, _pos: u64) -> u64 {
|
||||||
// use the offsets index to find the doc_id which will contain the position.
|
unimplemented!()
|
||||||
// the offsets are strictly increasing so we can do a simple search on it.
|
|
||||||
let new_doc_id: DocId = self
|
|
||||||
.offsets
|
|
||||||
.iter()
|
|
||||||
.position(|&offset| offset > pos)
|
|
||||||
.expect("pos is out of bounds") as DocId
|
|
||||||
- 1u32;
|
|
||||||
|
|
||||||
// now we need to find the position of `pos` in the multivalued bucket
|
|
||||||
let num_pos_covered_until_now = self.offsets[new_doc_id as usize];
|
|
||||||
let pos_in_values = pos - num_pos_covered_until_now;
|
|
||||||
|
|
||||||
let old_doc_addr = self.doc_id_mapping.get_old_doc_addr(new_doc_id);
|
|
||||||
let num_vals =
|
|
||||||
self.fast_field_readers[old_doc_addr.segment_ord as usize].get_len(old_doc_addr.doc_id);
|
|
||||||
assert!(num_vals >= pos_in_values);
|
|
||||||
let mut vals = Vec::new();
|
|
||||||
self.fast_field_readers[old_doc_addr.segment_ord as usize]
|
|
||||||
.get_vals(old_doc_addr.doc_id, &mut vals);
|
|
||||||
|
|
||||||
vals[pos_in_values as usize]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn iter(&self) -> Box<dyn Iterator<Item = u64> + '_> {
|
fn iter(&self) -> Box<dyn Iterator<Item = u64> + '_> {
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ impl BlockDecoder {
|
|||||||
|
|
||||||
pub trait VIntEncoder {
|
pub trait VIntEncoder {
|
||||||
/// Compresses an array of `u32` integers,
|
/// Compresses an array of `u32` integers,
|
||||||
/// using [delta-encoding](https://en.wikipedia.org/wiki/Delta_ encoding)
|
/// using [delta-encoding](https://en.wikipedia.org/wiki/Delta_encoding)
|
||||||
/// and variable bytes encoding.
|
/// and variable bytes encoding.
|
||||||
///
|
///
|
||||||
/// The method takes an array of ints to compress, and returns
|
/// The method takes an array of ints to compress, and returns
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ pub use self::term_info::TermInfo;
|
|||||||
|
|
||||||
pub(crate) type UnorderedTermId = u64;
|
pub(crate) type UnorderedTermId = u64;
|
||||||
|
|
||||||
#[cfg_attr(feature = "cargo-clippy", allow(clippy::enum_variant_names))]
|
#[allow(clippy::enum_variant_names)]
|
||||||
#[derive(Debug, PartialEq, Clone, Copy, Eq)]
|
#[derive(Debug, PartialEq, Clone, Copy, Eq)]
|
||||||
pub(crate) enum FreqReadingOption {
|
pub(crate) enum FreqReadingOption {
|
||||||
NoFreq,
|
NoFreq,
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ impl<'a> Iterator for VInt32Reader<'a> {
|
|||||||
/// Recorder is in charge of recording relevant information about
|
/// Recorder is in charge of recording relevant information about
|
||||||
/// the presence of a term in a document.
|
/// the presence of a term in a document.
|
||||||
///
|
///
|
||||||
/// Depending on the `TextIndexingOptions` associated to the
|
/// Depending on the `TextIndexingOptions` associated with the
|
||||||
/// field, the recorder may records
|
/// field, the recorder may records
|
||||||
/// * the document frequency
|
/// * the document frequency
|
||||||
/// * the document id
|
/// * the document id
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use crate::postings::compression::COMPRESSION_BLOCK_SIZE;
|
|||||||
use crate::postings::{branchless_binary_search, BlockSegmentPostings, Postings};
|
use crate::postings::{branchless_binary_search, BlockSegmentPostings, Postings};
|
||||||
use crate::{DocId, TERMINATED};
|
use crate::{DocId, TERMINATED};
|
||||||
|
|
||||||
/// `SegmentPostings` represents the inverted list or postings associated to
|
/// `SegmentPostings` represents the inverted list or postings associated with
|
||||||
/// a term in a `Segment`.
|
/// a term in a `Segment`.
|
||||||
///
|
///
|
||||||
/// As we iterate through the `SegmentPostings`, the frequencies are optionally decoded.
|
/// As we iterate through the `SegmentPostings`, the frequencies are optionally decoded.
|
||||||
@@ -216,7 +216,7 @@ impl HasLen for SegmentPostings {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Postings for SegmentPostings {
|
impl Postings for SegmentPostings {
|
||||||
/// Returns the frequency associated to the current document.
|
/// Returns the frequency associated with the current document.
|
||||||
/// If the schema is set up so that no frequency have been encoded,
|
/// If the schema is set up so that no frequency have been encoded,
|
||||||
/// this method should always return 1.
|
/// this method should always return 1.
|
||||||
///
|
///
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use std::ops::Range;
|
|||||||
|
|
||||||
use common::{BinarySerializable, FixedSize};
|
use common::{BinarySerializable, FixedSize};
|
||||||
|
|
||||||
/// `TermInfo` wraps the metadata associated to a Term.
|
/// `TermInfo` wraps the metadata associated with a Term.
|
||||||
/// It is segment-local.
|
/// It is segment-local.
|
||||||
#[derive(Debug, Default, Eq, PartialEq, Clone)]
|
#[derive(Debug, Default, Eq, PartialEq, Clone)]
|
||||||
pub struct TermInfo {
|
pub struct TermInfo {
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ impl Query for AllQuery {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Weight associated to the `AllQuery` query.
|
/// Weight associated with the `AllQuery` query.
|
||||||
pub struct AllWeight;
|
pub struct AllWeight;
|
||||||
|
|
||||||
impl Weight for AllWeight {
|
impl Weight for AllWeight {
|
||||||
@@ -37,7 +37,7 @@ impl Weight for AllWeight {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Scorer associated to the `AllQuery` query.
|
/// Scorer associated with the `AllQuery` query.
|
||||||
pub struct AllScorer {
|
pub struct AllScorer {
|
||||||
doc: DocId,
|
doc: DocId,
|
||||||
max_doc: DocId,
|
max_doc: DocId,
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ use crate::DocId;
|
|||||||
/// when the bitset is sparse
|
/// when the bitset is sparse
|
||||||
pub struct BitSetDocSet {
|
pub struct BitSetDocSet {
|
||||||
docs: BitSet,
|
docs: BitSet,
|
||||||
cursor_bucket: u32, //< index associated to the current tiny bitset
|
cursor_bucket: u32, //< index associated with the current tiny bitset
|
||||||
cursor_tinybitset: TinySet,
|
cursor_tinybitset: TinySet,
|
||||||
doc: u32,
|
doc: u32,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ fn advance_all_scorers_on_pivot(term_scorers: &mut Vec<TermScorerWithMaxScore>,
|
|||||||
|
|
||||||
/// Implements the WAND (Weak AND) algorithm for dynamic pruning
|
/// Implements the WAND (Weak AND) algorithm for dynamic pruning
|
||||||
/// described in the paper "Faster Top-k Document Retrieval Using Block-Max Indexes".
|
/// described in the paper "Faster Top-k Document Retrieval Using Block-Max Indexes".
|
||||||
/// Link: http://engineering.nyu.edu/~suel/papers/bmw.pdf
|
/// Link: <http://engineering.nyu.edu/~suel/papers/bmw.pdf>
|
||||||
pub fn block_wand(
|
pub fn block_wand(
|
||||||
mut scorers: Vec<TermScorer>,
|
mut scorers: Vec<TermScorer>,
|
||||||
mut threshold: Score,
|
mut threshold: Score,
|
||||||
|
|||||||
@@ -174,9 +174,9 @@ impl<TScoreCombiner: ScoreCombiner + Sync> Weight for BooleanWeight<TScoreCombin
|
|||||||
into_box_scorer(specialized_scorer, &self.score_combiner_fn)
|
into_box_scorer(specialized_scorer, &self.score_combiner_fn)
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
self.complex_scorer(reader, boost, &DoNothingCombiner::default)
|
self.complex_scorer(reader, boost, DoNothingCombiner::default)
|
||||||
.map(|specialized_scorer| {
|
.map(|specialized_scorer| {
|
||||||
into_box_scorer(specialized_scorer, &DoNothingCombiner::default)
|
into_box_scorer(specialized_scorer, DoNothingCombiner::default)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ impl Explanation {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the value associated to the current node.
|
/// Returns the value associated with the current node.
|
||||||
pub fn value(&self) -> Score {
|
pub fn value(&self) -> Score {
|
||||||
self.value
|
self.value
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use crate::{DocId, Score};
|
|||||||
|
|
||||||
/// Returns the intersection scorer.
|
/// Returns the intersection scorer.
|
||||||
///
|
///
|
||||||
/// The score associated to the documents is the sum of the
|
/// The score associated with the documents is the sum of the
|
||||||
/// score of the `Scorer`s given in argument.
|
/// score of the `Scorer`s given in argument.
|
||||||
///
|
///
|
||||||
/// For better performance, the function uses a
|
/// For better performance, the function uses a
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ mod range_query;
|
|||||||
mod regex_query;
|
mod regex_query;
|
||||||
mod reqopt_scorer;
|
mod reqopt_scorer;
|
||||||
mod scorer;
|
mod scorer;
|
||||||
|
mod set_query;
|
||||||
mod term_query;
|
mod term_query;
|
||||||
mod union;
|
mod union;
|
||||||
mod weight;
|
mod weight;
|
||||||
@@ -58,6 +59,7 @@ pub use self::score_combiner::{
|
|||||||
DisjunctionMaxCombiner, ScoreCombiner, SumCombiner, SumWithCoordsCombiner,
|
DisjunctionMaxCombiner, ScoreCombiner, SumCombiner, SumWithCoordsCombiner,
|
||||||
};
|
};
|
||||||
pub use self::scorer::Scorer;
|
pub use self::scorer::Scorer;
|
||||||
|
pub use self::set_query::TermSetQuery;
|
||||||
pub use self::term_query::TermQuery;
|
pub use self::term_query::TermQuery;
|
||||||
pub use self::union::Union;
|
pub use self::union::Union;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -33,9 +33,9 @@ impl Ord for ScoreTerm {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A struct used as helper to build [`MoreLikeThisQuery`]
|
/// A struct used as helper to build [`MoreLikeThisQuery`](crate::query::MoreLikeThisQuery)
|
||||||
/// This more-like-this implementation is inspired by the Appache Lucene
|
/// This more-like-this implementation is inspired by the Apache Lucene
|
||||||
/// amd closely follows the same implementation with adaptabtion to Tantivy vocabulary and API.
|
/// and closely follows the same implementation with adaptation to Tantivy vocabulary and API.
|
||||||
///
|
///
|
||||||
/// [MoreLikeThis](https://github.com/apache/lucene/blob/main/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThis.java#L147)
|
/// [MoreLikeThis](https://github.com/apache/lucene/blob/main/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThis.java#L147)
|
||||||
/// [MoreLikeThisQuery](https://github.com/apache/lucene/blob/main/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThisQuery.java#L36)
|
/// [MoreLikeThisQuery](https://github.com/apache/lucene/blob/main/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThisQuery.java#L36)
|
||||||
|
|||||||
@@ -119,7 +119,7 @@ impl PhraseQuery {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Query for PhraseQuery {
|
impl Query for PhraseQuery {
|
||||||
/// Create the weight associated to a query.
|
/// Create the weight associated with a query.
|
||||||
///
|
///
|
||||||
/// See [`Weight`].
|
/// See [`Weight`].
|
||||||
fn weight(&self, searcher: &Searcher, scoring_enabled: bool) -> crate::Result<Box<dyn Weight>> {
|
fn weight(&self, searcher: &Searcher, scoring_enabled: bool) -> crate::Result<Box<dyn Weight>> {
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ use crate::{DocAddress, Term};
|
|||||||
/// [`Scorer`]: crate::query::Scorer
|
/// [`Scorer`]: crate::query::Scorer
|
||||||
/// [`SegmentReader`]: crate::SegmentReader
|
/// [`SegmentReader`]: crate::SegmentReader
|
||||||
pub trait Query: QueryClone + Send + Sync + downcast_rs::Downcast + fmt::Debug {
|
pub trait Query: QueryClone + Send + Sync + downcast_rs::Downcast + fmt::Debug {
|
||||||
/// Create the weight associated to a query.
|
/// Create the weight associated with a query.
|
||||||
///
|
///
|
||||||
/// If scoring is not required, setting `scoring_enabled` to `false`
|
/// If scoring is not required, setting `scoring_enabled` to `false`
|
||||||
/// can increase performances.
|
/// can increase performances.
|
||||||
@@ -67,7 +67,7 @@ pub trait Query: QueryClone + Send + Sync + downcast_rs::Downcast + fmt::Debug {
|
|||||||
Ok(result)
|
Ok(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Extract all of the terms associated to the query and pass them to the
|
/// Extract all of the terms associated with the query and pass them to the
|
||||||
/// given closure.
|
/// given closure.
|
||||||
///
|
///
|
||||||
/// Each term is associated with a boolean indicating whether
|
/// Each term is associated with a boolean indicating whether
|
||||||
|
|||||||
@@ -610,7 +610,7 @@ impl QueryParser {
|
|||||||
if let Some((field, path)) = self.split_full_path(full_path) {
|
if let Some((field, path)) = self.split_full_path(full_path) {
|
||||||
return Ok(vec![(field, path, literal.phrase.as_str())]);
|
return Ok(vec![(field, path, literal.phrase.as_str())]);
|
||||||
}
|
}
|
||||||
// We need to add terms associated to json default fields.
|
// We need to add terms associated with json default fields.
|
||||||
let triplets: Vec<(Field, &str, &str)> = self
|
let triplets: Vec<(Field, &str, &str)> = self
|
||||||
.default_indexed_json_fields()
|
.default_indexed_json_fields()
|
||||||
.map(|json_field| (json_field, full_path.as_str(), literal.phrase.as_str()))
|
.map(|json_field| (json_field, full_path.as_str(), literal.phrase.as_str()))
|
||||||
|
|||||||
222
src/query/set_query.rs
Normal file
222
src/query/set_query.rs
Normal file
@@ -0,0 +1,222 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use tantivy_fst::raw::CompiledAddr;
|
||||||
|
use tantivy_fst::{Automaton, Map};
|
||||||
|
|
||||||
|
use crate::query::score_combiner::DoNothingCombiner;
|
||||||
|
use crate::query::{AutomatonWeight, BooleanWeight, Occur, Query, Weight};
|
||||||
|
use crate::schema::Field;
|
||||||
|
use crate::{Searcher, Term};
|
||||||
|
|
||||||
|
/// A Term Set Query matches all of the documents containing any of the Term provided
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct TermSetQuery {
|
||||||
|
terms_map: HashMap<Field, Vec<Term>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TermSetQuery {
|
||||||
|
/// Create a Term Set Query
|
||||||
|
pub fn new<T: IntoIterator<Item = Term>>(terms: T) -> Self {
|
||||||
|
let mut terms_map: HashMap<_, Vec<_>> = HashMap::new();
|
||||||
|
for term in terms {
|
||||||
|
terms_map.entry(term.field()).or_default().push(term);
|
||||||
|
}
|
||||||
|
|
||||||
|
for terms in terms_map.values_mut() {
|
||||||
|
terms.sort_unstable();
|
||||||
|
terms.dedup();
|
||||||
|
}
|
||||||
|
|
||||||
|
TermSetQuery { terms_map }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn specialized_weight(
|
||||||
|
&self,
|
||||||
|
searcher: &Searcher,
|
||||||
|
) -> crate::Result<BooleanWeight<DoNothingCombiner>> {
|
||||||
|
let mut sub_queries: Vec<(_, Box<dyn Weight>)> = Vec::with_capacity(self.terms_map.len());
|
||||||
|
|
||||||
|
for (&field, sorted_terms) in self.terms_map.iter() {
|
||||||
|
let field_entry = searcher.schema().get_field_entry(field);
|
||||||
|
let field_type = field_entry.field_type();
|
||||||
|
if !field_type.is_indexed() {
|
||||||
|
let error_msg = format!("Field {:?} is not indexed.", field_entry.name());
|
||||||
|
return Err(crate::TantivyError::SchemaError(error_msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
// In practice this won't fail because:
|
||||||
|
// - we are writing to memory, so no IoError
|
||||||
|
// - Terms are ordered
|
||||||
|
let map = Map::from_iter(sorted_terms.iter().map(|key| (key.value_bytes(), 0)))
|
||||||
|
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
|
||||||
|
|
||||||
|
sub_queries.push((
|
||||||
|
Occur::Should,
|
||||||
|
Box::new(AutomatonWeight::new(field, SetDfaWrapper(map))),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(BooleanWeight::new(
|
||||||
|
sub_queries,
|
||||||
|
false,
|
||||||
|
Box::new(|| DoNothingCombiner),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Query for TermSetQuery {
|
||||||
|
fn weight(
|
||||||
|
&self,
|
||||||
|
searcher: &Searcher,
|
||||||
|
_scoring_enabled: bool,
|
||||||
|
) -> crate::Result<Box<dyn Weight>> {
|
||||||
|
Ok(Box::new(self.specialized_weight(searcher)?))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SetDfaWrapper(Map<Vec<u8>>);
|
||||||
|
|
||||||
|
impl Automaton for SetDfaWrapper {
|
||||||
|
type State = Option<CompiledAddr>;
|
||||||
|
|
||||||
|
fn start(&self) -> Option<CompiledAddr> {
|
||||||
|
Some(self.0.as_ref().root().addr())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_match(&self, state_opt: &Option<CompiledAddr>) -> bool {
|
||||||
|
if let Some(state) = state_opt {
|
||||||
|
self.0.as_ref().node(*state).is_final()
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn accept(&self, state_opt: &Option<CompiledAddr>, byte: u8) -> Option<CompiledAddr> {
|
||||||
|
let state = state_opt.as_ref()?;
|
||||||
|
let node = self.0.as_ref().node(*state);
|
||||||
|
let transition = node.find_input(byte)?;
|
||||||
|
Some(node.transition_addr(transition))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn can_match(&self, state: &Self::State) -> bool {
|
||||||
|
state.is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
|
||||||
|
use crate::collector::TopDocs;
|
||||||
|
use crate::query::TermSetQuery;
|
||||||
|
use crate::schema::{Schema, TEXT};
|
||||||
|
use crate::{assert_nearly_equals, Index, Term};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
pub fn test_term_set_query() -> crate::Result<()> {
|
||||||
|
let mut schema_builder = Schema::builder();
|
||||||
|
let field1 = schema_builder.add_text_field("field1", TEXT);
|
||||||
|
let field2 = schema_builder.add_text_field("field1", TEXT);
|
||||||
|
let schema = schema_builder.build();
|
||||||
|
let index = Index::create_in_ram(schema);
|
||||||
|
{
|
||||||
|
let mut index_writer = index.writer_for_tests()?;
|
||||||
|
index_writer.add_document(doc!(
|
||||||
|
field1 => "doc1",
|
||||||
|
field2 => "val1",
|
||||||
|
))?;
|
||||||
|
index_writer.add_document(doc!(
|
||||||
|
field1 => "doc2",
|
||||||
|
field2 => "val2",
|
||||||
|
))?;
|
||||||
|
index_writer.add_document(doc!(
|
||||||
|
field1 => "doc3",
|
||||||
|
field2 => "val3",
|
||||||
|
))?;
|
||||||
|
index_writer.add_document(doc!(
|
||||||
|
field1 => "val3",
|
||||||
|
field2 => "doc3",
|
||||||
|
))?;
|
||||||
|
index_writer.commit()?;
|
||||||
|
}
|
||||||
|
let reader = index.reader()?;
|
||||||
|
let searcher = reader.searcher();
|
||||||
|
|
||||||
|
{
|
||||||
|
// single element
|
||||||
|
let terms = vec![Term::from_field_text(field1, "doc1")];
|
||||||
|
|
||||||
|
let term_set_query = TermSetQuery::new(terms);
|
||||||
|
let top_docs = searcher.search(&term_set_query, &TopDocs::with_limit(2))?;
|
||||||
|
assert_eq!(top_docs.len(), 1, "Expected 1 document");
|
||||||
|
let (score, _) = top_docs[0];
|
||||||
|
assert_nearly_equals!(1.0, score);
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// single element, absent
|
||||||
|
let terms = vec![Term::from_field_text(field1, "doc4")];
|
||||||
|
|
||||||
|
let term_set_query = TermSetQuery::new(terms);
|
||||||
|
let top_docs = searcher.search(&term_set_query, &TopDocs::with_limit(1))?;
|
||||||
|
assert!(top_docs.is_empty(), "Expected 0 document");
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// multiple elements
|
||||||
|
let terms = vec![
|
||||||
|
Term::from_field_text(field1, "doc1"),
|
||||||
|
Term::from_field_text(field1, "doc2"),
|
||||||
|
];
|
||||||
|
|
||||||
|
let term_set_query = TermSetQuery::new(terms);
|
||||||
|
let top_docs = searcher.search(&term_set_query, &TopDocs::with_limit(2))?;
|
||||||
|
assert_eq!(top_docs.len(), 2, "Expected 2 documents");
|
||||||
|
for (score, _) in top_docs {
|
||||||
|
assert_nearly_equals!(1.0, score);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// multiple elements, mixed fields
|
||||||
|
let terms = vec![
|
||||||
|
Term::from_field_text(field1, "doc1"),
|
||||||
|
Term::from_field_text(field1, "doc1"),
|
||||||
|
Term::from_field_text(field2, "val2"),
|
||||||
|
];
|
||||||
|
|
||||||
|
let term_set_query = TermSetQuery::new(terms);
|
||||||
|
let top_docs = searcher.search(&term_set_query, &TopDocs::with_limit(3))?;
|
||||||
|
|
||||||
|
assert_eq!(top_docs.len(), 2, "Expected 2 document");
|
||||||
|
for (score, _) in top_docs {
|
||||||
|
assert_nearly_equals!(1.0, score);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// no field crosstalk
|
||||||
|
let terms = vec![Term::from_field_text(field1, "doc3")];
|
||||||
|
|
||||||
|
let term_set_query = TermSetQuery::new(terms);
|
||||||
|
let top_docs = searcher.search(&term_set_query, &TopDocs::with_limit(3))?;
|
||||||
|
assert_eq!(top_docs.len(), 1, "Expected 1 document");
|
||||||
|
|
||||||
|
let terms = vec![Term::from_field_text(field2, "doc3")];
|
||||||
|
|
||||||
|
let term_set_query = TermSetQuery::new(terms);
|
||||||
|
let top_docs = searcher.search(&term_set_query, &TopDocs::with_limit(3))?;
|
||||||
|
assert_eq!(top_docs.len(), 1, "Expected 1 document");
|
||||||
|
|
||||||
|
let terms = vec![
|
||||||
|
Term::from_field_text(field1, "doc3"),
|
||||||
|
Term::from_field_text(field2, "doc3"),
|
||||||
|
];
|
||||||
|
|
||||||
|
let term_set_query = TermSetQuery::new(terms);
|
||||||
|
let top_docs = searcher.search(&term_set_query, &TopDocs::with_limit(3))?;
|
||||||
|
assert_eq!(top_docs.len(), 2, "Expected 2 document");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -83,7 +83,7 @@ impl BytesOptions {
|
|||||||
///
|
///
|
||||||
/// Fast fields are designed for random access.
|
/// Fast fields are designed for random access.
|
||||||
/// Access time are similar to a random lookup in an array.
|
/// Access time are similar to a random lookup in an array.
|
||||||
/// If more than one value is associated to a fast field, only the last one is
|
/// If more than one value is associated with a fast field, only the last one is
|
||||||
/// kept.
|
/// kept.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn set_fast(mut self) -> BytesOptions {
|
pub fn set_fast(mut self) -> BytesOptions {
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ impl DateOptions {
|
|||||||
///
|
///
|
||||||
/// Fast fields are designed for random access.
|
/// Fast fields are designed for random access.
|
||||||
/// Access time are similar to a random lookup in an array.
|
/// Access time are similar to a random lookup in an array.
|
||||||
/// If more than one value is associated to a fast field, only the last one is
|
/// If more than one value is associated with a fast field, only the last one is
|
||||||
/// kept.
|
/// kept.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn set_fast(mut self, cardinality: Cardinality) -> DateOptions {
|
pub fn set_fast(mut self, cardinality: Cardinality) -> DateOptions {
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ pub enum FacetParseError {
|
|||||||
/// For instance, an e-commerce website could
|
/// For instance, an e-commerce website could
|
||||||
/// have a `Facet` for `/electronics/tv_and_video/led_tv`.
|
/// have a `Facet` for `/electronics/tv_and_video/led_tv`.
|
||||||
///
|
///
|
||||||
/// A document can be associated to any number of facets.
|
/// A document can be associated with any number of facets.
|
||||||
/// The hierarchy implicitly imply that a document
|
/// The hierarchy implicitly imply that a document
|
||||||
/// belonging to a facet also belongs to the ancestor of
|
/// belonging to a facet also belongs to the ancestor of
|
||||||
/// its facet. In the example above, `/electronics/tv_and_video/`
|
/// its facet. In the example above, `/electronics/tv_and_video/`
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use serde::{Deserialize, Serialize};
|
|||||||
use serde_json::Value as JsonValue;
|
use serde_json::Value as JsonValue;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
|
use super::Cardinality;
|
||||||
use crate::schema::bytes_options::BytesOptions;
|
use crate::schema::bytes_options::BytesOptions;
|
||||||
use crate::schema::facet_options::FacetOptions;
|
use crate::schema::facet_options::FacetOptions;
|
||||||
use crate::schema::{
|
use crate::schema::{
|
||||||
@@ -214,6 +215,26 @@ impl FieldType {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// returns true if the field is fast.
|
||||||
|
pub fn fastfield_cardinality(&self) -> Option<Cardinality> {
|
||||||
|
match *self {
|
||||||
|
FieldType::Bytes(ref bytes_options) if bytes_options.is_fast() => {
|
||||||
|
Some(Cardinality::SingleValue)
|
||||||
|
}
|
||||||
|
FieldType::Str(ref text_options) if text_options.is_fast() => {
|
||||||
|
Some(Cardinality::MultiValues)
|
||||||
|
}
|
||||||
|
FieldType::U64(ref int_options)
|
||||||
|
| FieldType::I64(ref int_options)
|
||||||
|
| FieldType::F64(ref int_options)
|
||||||
|
| FieldType::Bool(ref int_options) => int_options.get_fastfield_cardinality(),
|
||||||
|
FieldType::Date(ref date_options) => date_options.get_fastfield_cardinality(),
|
||||||
|
FieldType::Facet(_) => Some(Cardinality::MultiValues),
|
||||||
|
FieldType::JsonObject(_) => None,
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// returns true if the field is normed (see [fieldnorms](crate::fieldnorm)).
|
/// returns true if the field is normed (see [fieldnorms](crate::fieldnorm)).
|
||||||
pub fn has_fieldnorms(&self) -> bool {
|
pub fn has_fieldnorms(&self) -> bool {
|
||||||
match *self {
|
match *self {
|
||||||
|
|||||||
109
src/schema/ip_options.rs
Normal file
109
src/schema/ip_options.rs
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
use std::ops::BitOr;
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use super::flags::{FastFlag, IndexedFlag, SchemaFlagList, StoredFlag};
|
||||||
|
use super::Cardinality;
|
||||||
|
|
||||||
|
/// Define how an ip field should be handled by tantivy.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||||
|
pub struct IpOptions {
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
fast: Option<Cardinality>,
|
||||||
|
stored: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IpOptions {
|
||||||
|
/// Returns true iff the value is a fast field.
|
||||||
|
pub fn is_fast(&self) -> bool {
|
||||||
|
self.fast.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns `true` if the json object should be stored.
|
||||||
|
pub fn is_stored(&self) -> bool {
|
||||||
|
self.stored
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the cardinality of the fastfield.
|
||||||
|
///
|
||||||
|
/// If the field has not been declared as a fastfield, then
|
||||||
|
/// the method returns None.
|
||||||
|
pub fn get_fastfield_cardinality(&self) -> Option<Cardinality> {
|
||||||
|
self.fast
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the field as stored
|
||||||
|
#[must_use]
|
||||||
|
pub fn set_stored(mut self) -> Self {
|
||||||
|
self.stored = true;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the field as a fast field.
|
||||||
|
///
|
||||||
|
/// Fast fields are designed for random access.
|
||||||
|
/// Access time are similar to a random lookup in an array.
|
||||||
|
/// If more than one value is associated with a fast field, only the last one is
|
||||||
|
/// kept.
|
||||||
|
#[must_use]
|
||||||
|
pub fn set_fast(mut self, cardinality: Cardinality) -> Self {
|
||||||
|
self.fast = Some(cardinality);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<()> for IpOptions {
|
||||||
|
fn from(_: ()) -> IpOptions {
|
||||||
|
IpOptions::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<FastFlag> for IpOptions {
|
||||||
|
fn from(_: FastFlag) -> Self {
|
||||||
|
IpOptions {
|
||||||
|
stored: false,
|
||||||
|
fast: Some(Cardinality::SingleValue),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<StoredFlag> for IpOptions {
|
||||||
|
fn from(_: StoredFlag) -> Self {
|
||||||
|
IpOptions {
|
||||||
|
stored: true,
|
||||||
|
fast: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<IndexedFlag> for IpOptions {
|
||||||
|
fn from(_: IndexedFlag) -> Self {
|
||||||
|
IpOptions {
|
||||||
|
stored: false,
|
||||||
|
fast: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Into<IpOptions>> BitOr<T> for IpOptions {
|
||||||
|
type Output = IpOptions;
|
||||||
|
|
||||||
|
fn bitor(self, other: T) -> IpOptions {
|
||||||
|
let other = other.into();
|
||||||
|
IpOptions {
|
||||||
|
stored: self.stored | other.stored,
|
||||||
|
fast: self.fast.or(other.fast),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Head, Tail> From<SchemaFlagList<Head, Tail>> for IpOptions
|
||||||
|
where
|
||||||
|
Head: Clone,
|
||||||
|
Tail: Clone,
|
||||||
|
Self: BitOr<Output = Self> + From<Head> + From<Tail>,
|
||||||
|
{
|
||||||
|
fn from(head_tail: SchemaFlagList<Head, Tail>) -> Self {
|
||||||
|
Self::from(head_tail.head) | Self::from(head_tail.tail)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -120,6 +120,7 @@ mod date_time_options;
|
|||||||
mod field;
|
mod field;
|
||||||
mod flags;
|
mod flags;
|
||||||
mod index_record_option;
|
mod index_record_option;
|
||||||
|
mod ip_options;
|
||||||
mod json_object_options;
|
mod json_object_options;
|
||||||
mod named_field_document;
|
mod named_field_document;
|
||||||
mod numeric_options;
|
mod numeric_options;
|
||||||
@@ -138,6 +139,7 @@ pub use self::field_type::{FieldType, Type};
|
|||||||
pub use self::field_value::FieldValue;
|
pub use self::field_value::FieldValue;
|
||||||
pub use self::flags::{FAST, INDEXED, STORED};
|
pub use self::flags::{FAST, INDEXED, STORED};
|
||||||
pub use self::index_record_option::IndexRecordOption;
|
pub use self::index_record_option::IndexRecordOption;
|
||||||
|
pub use self::ip_options::IpOptions;
|
||||||
pub use self::json_object_options::JsonObjectOptions;
|
pub use self::json_object_options::JsonObjectOptions;
|
||||||
pub use self::named_field_document::NamedFieldDocument;
|
pub use self::named_field_document::NamedFieldDocument;
|
||||||
pub use self::numeric_options::NumericOptions;
|
pub use self::numeric_options::NumericOptions;
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ use crate::schema::flags::{FastFlag, IndexedFlag, SchemaFlagList, StoredFlag};
|
|||||||
/// Express whether a field is single-value or multi-valued.
|
/// Express whether a field is single-value or multi-valued.
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
|
||||||
pub enum Cardinality {
|
pub enum Cardinality {
|
||||||
/// The document must have exactly one value associated to the document.
|
/// The document must have exactly one value associated with the document.
|
||||||
#[serde(rename = "single")]
|
#[serde(rename = "single")]
|
||||||
SingleValue,
|
SingleValue,
|
||||||
/// The document can have any number of values associated to the document.
|
/// The document can have any number of values associated with the document.
|
||||||
/// This is more memory and CPU expensive than the `SingleValue` solution.
|
/// This is more memory and CPU expensive than the `SingleValue` solution.
|
||||||
#[serde(rename = "multi")]
|
#[serde(rename = "multi")]
|
||||||
MultiValues,
|
MultiValues,
|
||||||
@@ -124,7 +124,7 @@ impl NumericOptions {
|
|||||||
///
|
///
|
||||||
/// Fast fields are designed for random access.
|
/// Fast fields are designed for random access.
|
||||||
/// Access time are similar to a random lookup in an array.
|
/// Access time are similar to a random lookup in an array.
|
||||||
/// If more than one value is associated to a fast field, only the last one is
|
/// If more than one value is associated with a fast field, only the last one is
|
||||||
/// kept.
|
/// kept.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn set_fast(mut self, cardinality: Cardinality) -> NumericOptions {
|
pub fn set_fast(mut self, cardinality: Cardinality) -> NumericOptions {
|
||||||
|
|||||||
@@ -258,7 +258,7 @@ impl Eq for InnerSchema {}
|
|||||||
pub struct Schema(Arc<InnerSchema>);
|
pub struct Schema(Arc<InnerSchema>);
|
||||||
|
|
||||||
impl Schema {
|
impl Schema {
|
||||||
/// Return the `FieldEntry` associated to a `Field`.
|
/// Return the `FieldEntry` associated with a `Field`.
|
||||||
pub fn get_field_entry(&self, field: Field) -> &FieldEntry {
|
pub fn get_field_entry(&self, field: Field) -> &FieldEntry {
|
||||||
&self.0.fields[field.field_id() as usize]
|
&self.0.fields[field.field_id() as usize]
|
||||||
}
|
}
|
||||||
@@ -422,12 +422,8 @@ pub enum DocParsingError {
|
|||||||
impl DocParsingError {
|
impl DocParsingError {
|
||||||
/// Builds a NotJson DocParsingError
|
/// Builds a NotJson DocParsingError
|
||||||
fn invalid_json(invalid_json: &str) -> Self {
|
fn invalid_json(invalid_json: &str) -> Self {
|
||||||
let sample_json: String = if invalid_json.len() < 20 {
|
let sample = invalid_json.chars().take(20).collect();
|
||||||
invalid_json.to_string()
|
DocParsingError::InvalidJson(sample)
|
||||||
} else {
|
|
||||||
format!("{:?}...", &invalid_json[0..20])
|
|
||||||
};
|
|
||||||
DocParsingError::InvalidJson(sample_json)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -793,6 +789,11 @@ mod tests {
|
|||||||
))
|
))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
{
|
||||||
|
// Short JSON, under the 20 char take.
|
||||||
|
let json_err = schema.parse_document(r#"{"count": 50,}"#);
|
||||||
|
assert_matches!(json_err, Err(InvalidJson(_)));
|
||||||
|
}
|
||||||
{
|
{
|
||||||
let json_err = schema.parse_document(
|
let json_err = schema.parse_document(
|
||||||
r#"{
|
r#"{
|
||||||
|
|||||||
@@ -161,7 +161,7 @@ impl TextFieldIndexing {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the indexing options associated to this field.
|
/// Returns the indexing options associated with this field.
|
||||||
///
|
///
|
||||||
/// See [`IndexRecordOption`] for more detail.
|
/// See [`IndexRecordOption`] for more detail.
|
||||||
pub fn index_option(&self) -> IndexRecordOption {
|
pub fn index_option(&self) -> IndexRecordOption {
|
||||||
|
|||||||
@@ -342,7 +342,7 @@ impl SnippetGenerator {
|
|||||||
|
|
||||||
/// Generates a snippet for the given `Document`.
|
/// Generates a snippet for the given `Document`.
|
||||||
///
|
///
|
||||||
/// This method extract the text associated to the `SnippetGenerator`'s field
|
/// This method extract the text associated with the `SnippetGenerator`'s field
|
||||||
/// and computes a snippet.
|
/// and computes a snippet.
|
||||||
pub fn snippet_from_doc(&self, doc: &Document) -> Snippet {
|
pub fn snippet_from_doc(&self, doc: &Document) -> Snippet {
|
||||||
let text: String = doc
|
let text: String = doc
|
||||||
|
|||||||
@@ -104,6 +104,13 @@ impl ZstdCompressor {
|
|||||||
value, opt_name, err
|
value, opt_name, err
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
|
if value >= 15 {
|
||||||
|
warn!(
|
||||||
|
"High zstd compression level detected: {:?}. High compression levels \
|
||||||
|
(>=15) are slow and will limit indexing speed.",
|
||||||
|
value
|
||||||
|
)
|
||||||
|
}
|
||||||
compressor.compression_level = Some(value);
|
compressor.compression_level = Some(value);
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
|
|||||||
@@ -136,7 +136,7 @@ where A: Automaton
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Return the next `(key, value)` pair.
|
/// Return the next `(key, value)` pair.
|
||||||
#[cfg_attr(feature = "cargo-clippy", allow(clippy::should_implement_trait))]
|
#[allow(clippy::should_implement_trait)]
|
||||||
pub fn next(&mut self) -> Option<(&[u8], &TermInfo)> {
|
pub fn next(&mut self) -> Option<(&[u8], &TermInfo)> {
|
||||||
if self.advance() {
|
if self.advance() {
|
||||||
Some((self.key(), self.value()))
|
Some((self.key(), self.value()))
|
||||||
|
|||||||
@@ -138,12 +138,12 @@ impl TermDictionary {
|
|||||||
self.term_info_store.num_terms()
|
self.term_info_store.num_terms()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the ordinal associated to a given term.
|
/// Returns the ordinal associated with a given term.
|
||||||
pub fn term_ord<K: AsRef<[u8]>>(&self, key: K) -> io::Result<Option<TermOrdinal>> {
|
pub fn term_ord<K: AsRef<[u8]>>(&self, key: K) -> io::Result<Option<TermOrdinal>> {
|
||||||
Ok(self.fst_index.get(key))
|
Ok(self.fst_index.get(key))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stores the term associated to a given term ordinal in
|
/// Stores the term associated with a given term ordinal in
|
||||||
/// a `bytes` buffer.
|
/// a `bytes` buffer.
|
||||||
///
|
///
|
||||||
/// Term ordinals are defined as the position of the term in
|
/// Term ordinals are defined as the position of the term in
|
||||||
|
|||||||
@@ -179,7 +179,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Return the next `(key, value)` pair.
|
/// Return the next `(key, value)` pair.
|
||||||
#[cfg_attr(feature = "cargo-clippy", allow(clippy::should_implement_trait))]
|
#[allow(clippy::should_implement_trait)]
|
||||||
pub fn next(&mut self) -> Option<(&[u8], &TermInfo)> {
|
pub fn next(&mut self) -> Option<(&[u8], &TermInfo)> {
|
||||||
if self.advance() {
|
if self.advance() {
|
||||||
Some((self.key(), self.value()))
|
Some((self.key(), self.value()))
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ impl<W: io::Write> TermDictionaryBuilder<W> {
|
|||||||
/// to insert_key and insert_value.
|
/// to insert_key and insert_value.
|
||||||
///
|
///
|
||||||
/// Prefer using `.insert(key, value)`
|
/// Prefer using `.insert(key, value)`
|
||||||
#[allow(clippy::clippy::clippy::unnecessary_wraps)]
|
#[allow(clippy::unnecessary_wraps)]
|
||||||
pub(crate) fn insert_key(&mut self, key: &[u8]) -> io::Result<()> {
|
pub(crate) fn insert_key(&mut self, key: &[u8]) -> io::Result<()> {
|
||||||
self.sstable_writer.write_key(key);
|
self.sstable_writer.write_key(key);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -153,7 +153,7 @@ impl TermDictionary {
|
|||||||
self.num_terms as usize
|
self.num_terms as usize
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the ordinal associated to a given term.
|
/// Returns the ordinal associated with a given term.
|
||||||
pub fn term_ord<K: AsRef<[u8]>>(&self, key: K) -> io::Result<Option<TermOrdinal>> {
|
pub fn term_ord<K: AsRef<[u8]>>(&self, key: K) -> io::Result<Option<TermOrdinal>> {
|
||||||
let mut term_ord = 0u64;
|
let mut term_ord = 0u64;
|
||||||
let key_bytes = key.as_ref();
|
let key_bytes = key.as_ref();
|
||||||
@@ -167,7 +167,7 @@ impl TermDictionary {
|
|||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the term associated to a given term ordinal.
|
/// Returns the term associated with a given term ordinal.
|
||||||
///
|
///
|
||||||
/// Term ordinals are defined as the position of the term in
|
/// Term ordinals are defined as the position of the term in
|
||||||
/// the sorted list of terms.
|
/// the sorted list of terms.
|
||||||
|
|||||||
@@ -255,7 +255,7 @@ where T: Iterator<Item = usize>
|
|||||||
/// Emits all of the offsets where a codepoint starts
|
/// Emits all of the offsets where a codepoint starts
|
||||||
/// or a codepoint ends.
|
/// or a codepoint ends.
|
||||||
///
|
///
|
||||||
/// By convention, we emit [0] for the empty string.
|
/// By convention, we emit `[0]` for the empty string.
|
||||||
struct CodepointFrontiers<'a> {
|
struct CodepointFrontiers<'a> {
|
||||||
s: &'a str,
|
s: &'a str,
|
||||||
next_el: Option<usize>,
|
next_el: Option<usize>,
|
||||||
|
|||||||
Reference in New Issue
Block a user