mirror of
https://github.com/quickwit-oss/tantivy.git
synced 2026-11-27 04:54:12 +00:00
moving source around
This commit is contained in:
@@ -5,7 +5,8 @@ use std::sync::Arc;
|
||||
|
||||
use columnar::{Column, ColumnType, DynamicColumn, DynamicColumnHandle};
|
||||
|
||||
use crate::aggregation::{f64_to_fastfield_u64, Key, ValueSource, ValueSourceRegistry};
|
||||
use crate::aggregation::value_sources::ValueSource;
|
||||
use crate::aggregation::{f64_to_fastfield_u64, Key, ValueSourceRegistry};
|
||||
use crate::index::SegmentReader;
|
||||
|
||||
/// Get the missing value as internal u64 representation
|
||||
|
||||
@@ -690,19 +690,16 @@ fn normalize_histogram_req(req_data: &mut HistogramAggReqData) -> crate::Result<
|
||||
// per-term counts from the grid. Only this collect-time filter is touched — empty-bucket
|
||||
// emission reads `req.hard_bounds` directly (see `get_req_min_max`), and `hard_bounds` only
|
||||
// ever clips that range, so a wider-than-data bound leaves the result unchanged.
|
||||
// A computed source has no global range to compare against, so the collapse is simply not
|
||||
// attempted and the per-doc `bounds.contains` check stays.
|
||||
if let (true, Some((min_value, max_value))) = (
|
||||
req_data.req.hard_bounds.is_some(),
|
||||
req_data.accessor.bounds(),
|
||||
) {
|
||||
let col_min = f64_from_fastfield_u64(min_value, req_data.field_type);
|
||||
let col_max = f64_from_fastfield_u64(max_value, req_data.field_type);
|
||||
if col_min >= req_data.bounds.min && col_max <= req_data.bounds.max {
|
||||
req_data.bounds = HistogramBounds {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
};
|
||||
if req_data.req.hard_bounds.is_some() {
|
||||
if let Some((min_value, max_value)) = req_data.accessor.bounds() {
|
||||
let col_min = f64_from_fastfield_u64(min_value, req_data.field_type);
|
||||
let col_max = f64_from_fastfield_u64(max_value, req_data.field_type);
|
||||
if col_min >= req_data.bounds.min && col_max <= req_data.bounds.max {
|
||||
req_data.bounds = HistogramBounds {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -19,6 +19,7 @@ use crate::aggregation::intermediate_agg_result::{
|
||||
IntermediateRangeBucketEntry, IntermediateRangeBucketResult,
|
||||
};
|
||||
use crate::aggregation::segment_agg_result::{BucketIdProvider, SegmentAggregationCollector};
|
||||
use crate::aggregation::value_sources::ValueSource;
|
||||
use crate::aggregation::*;
|
||||
use crate::TantivyError;
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
use std::fmt::Debug;
|
||||
use std::sync::Arc;
|
||||
|
||||
use columnar::{ColumnType, ColumnValues};
|
||||
use columnar::{Cardinality, ColumnType, ColumnValues};
|
||||
|
||||
use super::{
|
||||
Bucket, SegmentTermCollector, TermsAggReqData, VecTermBuckets, MAX_NUM_BUCKETS_FOR_COUNT_LANES,
|
||||
@@ -23,7 +23,8 @@ use crate::aggregation::intermediate_agg_result::{
|
||||
IntermediateAggregationResult, IntermediateAggregationResults,
|
||||
};
|
||||
use crate::aggregation::segment_agg_result::{BucketIdProvider, SegmentAggregationCollector};
|
||||
use crate::aggregation::{f64_from_fastfield_u64, BucketId, ColumnBlockAccessor};
|
||||
use crate::aggregation::value_sources::ColumnBlockAccessor;
|
||||
use crate::aggregation::{f64_from_fastfield_u64, BucketId, ValueSource};
|
||||
|
||||
/// Maximum number of physical counters in the flattened flat grid. Above this the grid would be too
|
||||
/// large/cache-unfriendly, so we fall back to the general buffered path. Count lanes are included
|
||||
@@ -82,6 +83,7 @@ fn increment_grid_count<const LANES: usize>(
|
||||
|
||||
/// Resolver for a histogram whose entire value range maps to one bucket. It deliberately owns no
|
||||
/// block accessor: collecting this shape does not read or decode the histogram column at all.
|
||||
#[derive(Default)]
|
||||
struct SingleBucketResolver {
|
||||
next_count_lane: usize,
|
||||
}
|
||||
@@ -122,7 +124,7 @@ impl BucketResolver for SingleBucketResolver {
|
||||
struct ComputedBucketResolver {
|
||||
hist_block: ColumnBlockAccessor,
|
||||
next_count_lane: usize,
|
||||
column_values: Arc<dyn ColumnValues<u64>>,
|
||||
column_values: Arc<dyn ColumnValues>,
|
||||
field_type: ColumnType,
|
||||
interval: f64,
|
||||
offset: f64,
|
||||
@@ -134,7 +136,7 @@ struct ComputedBucketResolver {
|
||||
impl ComputedBucketResolver {
|
||||
fn new(
|
||||
hist_req_data: &HistogramAggReqData,
|
||||
hist_values: Arc<dyn ColumnValues<u64>>,
|
||||
hist_values: Arc<dyn ColumnValues>,
|
||||
base_pos: i64,
|
||||
num_buckets: usize,
|
||||
) -> Self {
|
||||
@@ -216,7 +218,7 @@ impl BucketResolver for ComputedBucketResolver {
|
||||
struct LinearBucketResolver<const NUM_BUCKETS: usize> {
|
||||
hist_block: ColumnBlockAccessor,
|
||||
next_count_lane: usize,
|
||||
column_values: Arc<dyn ColumnValues<u64>>,
|
||||
column_values: Arc<dyn ColumnValues>,
|
||||
boundaries: [u64; NUM_BUCKETS],
|
||||
num_buckets: usize,
|
||||
}
|
||||
@@ -226,7 +228,7 @@ impl<const NUM_BUCKETS: usize> LinearBucketResolver<NUM_BUCKETS> {
|
||||
/// falls back to [`ComputedBucketResolver`].
|
||||
fn new(
|
||||
hist_req_data: &HistogramAggReqData,
|
||||
hist_values: &Arc<dyn ColumnValues<u64>>,
|
||||
hist_values: &Arc<dyn ColumnValues>,
|
||||
base_pos: i64,
|
||||
num_time_buckets: usize,
|
||||
) -> Option<Self> {
|
||||
@@ -363,7 +365,7 @@ struct FlattenedTermHistogramCollector<R: BucketResolver, const LANES: usize> {
|
||||
base_pos: i64,
|
||||
terms_req_data: TermsAggReqData,
|
||||
/// The full terms full column's values
|
||||
terms_values: Arc<dyn ColumnValues<u64>>,
|
||||
terms_values: Arc<dyn ColumnValues>,
|
||||
hist_req_data: HistogramAggReqData,
|
||||
/// Private term block accessor. The bucket resolver owns a histogram block accessor when it
|
||||
/// needs one; the single-bucket resolver deliberately does not.
|
||||
@@ -521,9 +523,6 @@ pub(super) fn maybe_build_flattened_collector(
|
||||
// are less likely to get enough docs for the preallocation to be worth and there's a risk of
|
||||
// using too much memory. We could check the maximum theoretical buckets up-front and pass
|
||||
// them down.
|
||||
// Both columns must be materialized, not merely full: this path reads them through
|
||||
// `fetch_full_column_block` and derives its bucket grid from their global min/max, none of
|
||||
// which a computed source can provide.
|
||||
let fuseable = is_top_level
|
||||
// TODO: We can easily support this
|
||||
&& terms_req_data.allowed_term_ids.is_none()
|
||||
@@ -537,24 +536,16 @@ pub(super) fn maybe_build_flattened_collector(
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Check fullness once, here, and hand the bare value array downstream. Separating the values
|
||||
// from the index is what carries the proof: a full column's index is redundant, so nothing
|
||||
// below can be handed a non-full column even by mistake.
|
||||
let Some(terms_values) = terms_req_data
|
||||
.accessor
|
||||
.as_column()
|
||||
.filter(|column| {
|
||||
column.get_cardinality().is_full()
|
||||
// The flat counters are `u32`, bumped once per value, so no count can exceed the
|
||||
// column's value count. (Essentially always true here: the column is full, so its
|
||||
// value count equals the doc count, and `DocId` is `u32`.)
|
||||
&& column.values.num_vals() < u32::MAX
|
||||
})
|
||||
.map(|column| column.values.clone())
|
||||
else {
|
||||
// Check fullness once, here, and hand the bare values array downstream.
|
||||
let Some(terms_values) = try_get_column_full_values(&*terms_req_data.accessor) else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
// The flat counters are `u32`, bumped once per value, so no count can exceed the
|
||||
// column's value count. (Essentially always true here: the column is full, so its
|
||||
// value count equals the doc count, and `DocId` is `u32`.)
|
||||
if terms_values.num_vals() >= u32::MAX {
|
||||
return Ok(None);
|
||||
}
|
||||
// Clone + normalize the histogram request and get its dense bucket range; only take the
|
||||
// flattened path when the physical counter grid is small enough. Very small logical grids use
|
||||
// multiple counters per cell; larger grids retain scalar cells to avoid paying for lanes when
|
||||
@@ -563,17 +554,10 @@ pub(super) fn maybe_build_flattened_collector(
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
// Extract from the normalized clone that the resolvers will actually read, rather than from
|
||||
// the pre-normalization entry: the two are the same column only incidentally.
|
||||
// Owned rather than borrowed because `hist_req_data` is moved below.
|
||||
let Some(hist_values) = hist_req_data
|
||||
.accessor
|
||||
.as_column()
|
||||
.filter(|column| column.get_cardinality().is_full())
|
||||
.map(|column| column.values.clone())
|
||||
else {
|
||||
let Some(hist_values) = try_get_column_full_values(&*hist_req_data.accessor) else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let num_terms = col_max_val.saturating_add(1) as usize;
|
||||
let num_grid_cells = num_terms.saturating_mul(range.len);
|
||||
let use_count_lanes = num_grid_cells <= MAX_NUM_BUCKETS_FOR_COUNT_LANES;
|
||||
@@ -610,12 +594,21 @@ pub(super) fn maybe_build_flattened_collector(
|
||||
Ok(Some(collector))
|
||||
}
|
||||
|
||||
fn try_get_column_full_values(value_source: &dyn ValueSource) -> Option<Arc<dyn ColumnValues>> {
|
||||
let column = value_source.as_column()?;
|
||||
if column.get_cardinality() == Cardinality::Full {
|
||||
Some(column.values.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn build_flattened_collector<const LANES: usize>(
|
||||
agg_data: &mut AggregationsSegmentCtx,
|
||||
terms_req_data: &TermsAggReqData,
|
||||
hist_req_data: HistogramAggReqData,
|
||||
terms_values: Arc<dyn ColumnValues<u64>>,
|
||||
hist_values: Arc<dyn ColumnValues<u64>>,
|
||||
terms_values: Arc<dyn ColumnValues>,
|
||||
hist_values: Arc<dyn ColumnValues>,
|
||||
num_terms: usize,
|
||||
range: DenseRange,
|
||||
) -> crate::Result<Box<dyn SegmentAggregationCollector>> {
|
||||
@@ -626,7 +619,7 @@ fn build_flattened_collector<const LANES: usize>(
|
||||
let all_docs_in_bounds =
|
||||
hist_req_data.bounds.min == f64::MIN && hist_req_data.bounds.max == f64::MAX;
|
||||
if all_docs_in_bounds && num_time_buckets == 1 {
|
||||
let resolver = SingleBucketResolver { next_count_lane: 0 };
|
||||
let resolver = SingleBucketResolver::default();
|
||||
return build_flattened_collector_with_resolver::<SingleBucketResolver, LANES>(
|
||||
agg_data,
|
||||
terms_req_data,
|
||||
|
||||
@@ -429,7 +429,8 @@ pub(crate) fn build_segment_term_collector(
|
||||
let col_max_value = terms_req_data
|
||||
.accessor
|
||||
.as_column()
|
||||
.map_or(u64::MAX, |column| column.max_value());
|
||||
.map(|col| col.max_value())
|
||||
.unwrap_or(u64::MAX);
|
||||
let max_column_val: u64 =
|
||||
col_max_value.max(terms_req_data.missing_value_for_accessor.unwrap_or(0u64));
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::aggregation::intermediate_agg_result::{
|
||||
IntermediateAggregationResult, IntermediateAggregationResults, IntermediateMetricResult,
|
||||
};
|
||||
use crate::aggregation::segment_agg_result::SegmentAggregationCollector;
|
||||
use crate::aggregation::value_sources::ValueSource;
|
||||
use crate::aggregation::*;
|
||||
use crate::TantivyError;
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ pub use stats::*;
|
||||
pub use sum::*;
|
||||
pub use top_hits::*;
|
||||
|
||||
use crate::aggregation::ValueSource;
|
||||
use crate::aggregation::value_sources::ValueSource;
|
||||
use crate::schema::OwnedValue;
|
||||
|
||||
/// Contains all information required by metric aggregations like avg, min, max, sum, stats,
|
||||
|
||||
@@ -132,7 +132,6 @@ mod agg_data;
|
||||
mod agg_limits;
|
||||
pub mod agg_req;
|
||||
pub mod agg_result;
|
||||
mod block_accessor;
|
||||
pub mod bucket;
|
||||
pub(crate) mod buffered_sub_aggs;
|
||||
mod collector;
|
||||
@@ -147,9 +146,8 @@ use std::cmp::Ordering;
|
||||
use std::fmt::Display;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(crate) use block_accessor::ColumnBlockAccessor;
|
||||
pub use block_accessor::ValueSource;
|
||||
pub use value_sources::{ValueSourceProvider, ValueSourceRegistry};
|
||||
pub(crate) use value_sources::ColumnBlockAccessor;
|
||||
pub use value_sources::{ValueSource, ValueSourceProvider, ValueSourceRegistry};
|
||||
|
||||
#[cfg(test)]
|
||||
mod agg_tests;
|
||||
|
||||
+26
-122
@@ -1,36 +1,10 @@
|
||||
use std::cmp::Ordering;
|
||||
|
||||
use columnar::{Cardinality, Column, ColumnValues, RowId};
|
||||
use columnar::{Cardinality, ColumnValues, RowId};
|
||||
|
||||
use crate::aggregation::value_sources::ValueSource;
|
||||
use crate::DocId;
|
||||
|
||||
/// A source of values for a block of documents.
|
||||
pub trait ValueSource: std::fmt::Debug {
|
||||
/// Loads the values for `docs` into `values`, and for a non-full source the matching document
|
||||
/// ids into `docids`, returning how the two are aligned.
|
||||
///
|
||||
/// `row_ids` is scratch the implementation may use freely. `docs` is sorted ascending with no
|
||||
/// duplicates.
|
||||
fn load_block(
|
||||
&self,
|
||||
docs: &[DocId],
|
||||
values: &mut Vec<u64>,
|
||||
docids: &mut Vec<DocId>,
|
||||
row_ids: &mut Vec<RowId>,
|
||||
) -> Cardinality;
|
||||
|
||||
/// Downcast the BlockValueSource to a Column.
|
||||
fn as_column(&self) -> Option<&Column<u64>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Global value bounds, for fast paths that need to size or clamp something up front.
|
||||
fn bounds(&self) -> Option<(u64, u64)> {
|
||||
let column = self.as_column()?;
|
||||
Some((column.min_value(), column.max_value()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Buffers the values associated with a block of documents loaded from a [`BlockValueSource`].
|
||||
///
|
||||
/// Regardless of their original types, values are loaded in their `u64` representation using the
|
||||
@@ -40,6 +14,7 @@ pub(crate) struct ColumnBlockAccessor {
|
||||
/// Values loaded for the latest document block, in monotonic `u64` representation.
|
||||
val_cache: Vec<u64>,
|
||||
/// Document ID corresponding to each value in `val_cache` for a non-full source.
|
||||
/// For full sources, this is likely to be empty.
|
||||
///
|
||||
/// A document can occur more than once for a multivalued source. For a full source this buffer
|
||||
/// is ignored because `val_cache` is aligned directly with the requested document block.
|
||||
@@ -57,34 +32,6 @@ pub(crate) struct ColumnBlockAccessor {
|
||||
cardinality: Cardinality,
|
||||
}
|
||||
|
||||
impl ValueSource for Column<u64> {
|
||||
#[inline]
|
||||
fn load_block(
|
||||
&self,
|
||||
docs: &[DocId],
|
||||
values: &mut Vec<u64>,
|
||||
docids: &mut Vec<DocId>,
|
||||
row_ids: &mut Vec<RowId>,
|
||||
) -> Cardinality {
|
||||
let cardinality = self.index.get_cardinality();
|
||||
if cardinality.is_full() {
|
||||
load_full_column_values(docs, &*self.values, values);
|
||||
} else {
|
||||
docids.clear();
|
||||
row_ids.clear();
|
||||
self.row_ids_for_docs(docs, docids, row_ids);
|
||||
values.resize(row_ids.len(), 0u64);
|
||||
self.values.get_vals(row_ids, values);
|
||||
}
|
||||
cardinality
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn as_column(&self) -> Option<&Column<u64>> {
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl ColumnBlockAccessor {
|
||||
#[inline]
|
||||
pub(crate) fn fetch_block(&mut self, docs: &[DocId], source: &dyn ValueSource) {
|
||||
@@ -111,7 +58,7 @@ impl ColumnBlockAccessor {
|
||||
docs: &[DocId],
|
||||
column_values: &dyn ColumnValues<u64>,
|
||||
) {
|
||||
load_full_column_values(docs, column_values, &mut self.val_cache);
|
||||
super::load_full_column_values(docs, column_values, &mut self.val_cache);
|
||||
self.cardinality = Cardinality::Full;
|
||||
}
|
||||
|
||||
@@ -315,41 +262,6 @@ impl ColumnBlockAccessor {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn load_full_column_values(
|
||||
docs: &[DocId],
|
||||
column_values: &dyn ColumnValues<u64>,
|
||||
values: &mut Vec<u64>,
|
||||
) {
|
||||
// Skip the resize when already the right length (common case: fixed-size blocks).
|
||||
if values.len() != docs.len() {
|
||||
values.resize(docs.len(), 0u64);
|
||||
}
|
||||
// When the docs form a contiguous ascending run we can fetch the values as a single range.
|
||||
// This lets codecs (e.g. bitpacked) bulk-decode the slice instead of gathering value-by-value.
|
||||
if is_contiguous(docs) {
|
||||
column_values.get_range(docs[0] as u64, values);
|
||||
} else {
|
||||
column_values.get_vals(docs, values);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if `docs` is a contiguous ascending run `[d, d + 1, ..., d + n - 1]`.
|
||||
///
|
||||
/// Assumes `docs` is sorted ascending and free of duplicates (the invariant for the
|
||||
/// doc blocks passed to `fetch_block`), so comparing the endpoints is sufficient.
|
||||
#[inline]
|
||||
fn is_contiguous(docs: &[u32]) -> bool {
|
||||
let (Some(&first), Some(&last)) = (docs.first(), docs.last()) else {
|
||||
return false;
|
||||
};
|
||||
debug_assert!(
|
||||
docs.windows(2).all(|w| w[0] < w[1]),
|
||||
"fetch_block requires docs sorted ascending without duplicates"
|
||||
);
|
||||
(last - first) as usize + 1 == docs.len()
|
||||
}
|
||||
|
||||
/// Given two sorted lists of docids `docs` and `hits`, hits is a subset of `docs`.
|
||||
/// Write in the output Vec all of the docs that are not in `hits`.
|
||||
///
|
||||
@@ -389,6 +301,8 @@ fn find_missing_docs(docs: &[u32], hits: &[u32], output: &mut Vec<u32>) {
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use columnar::Column;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -434,7 +348,7 @@ mod tests {
|
||||
assert!(accessor.has_one_value_per_doc(&docs));
|
||||
assert_eq!(
|
||||
accessor.iter_docid_vals(&docs).collect::<Vec<_>>(),
|
||||
vec![(2, 20), (4, 40), (8, 80)]
|
||||
[(2, 20), (4, 40), (8, 80)]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -479,13 +393,13 @@ mod tests {
|
||||
assert!(!accessor.has_one_value_per_doc(&docs));
|
||||
assert_eq!(
|
||||
accessor.iter_docid_vals(&docs).collect::<Vec<_>>(),
|
||||
vec![(1, 11), (3, 33)]
|
||||
[(1, 11), (3, 33)]
|
||||
);
|
||||
|
||||
accessor.fetch_block_with_missing(&docs, &*computed, Some(99));
|
||||
let mut pairs = accessor.iter_docid_vals(&docs).collect::<Vec<_>>();
|
||||
pairs.sort_unstable();
|
||||
assert_eq!(pairs, vec![(0, 99), (1, 11), (2, 99), (3, 33)]);
|
||||
assert_eq!(pairs, [(0, 99), (1, 11), (2, 99), (3, 33)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -495,7 +409,7 @@ mod tests {
|
||||
|
||||
let mut missing_docs: Vec<u32> = Vec::new();
|
||||
find_missing_docs(&docs, &hits, &mut missing_docs);
|
||||
assert_eq!(missing_docs, vec![1, 3, 5, 7, 9]);
|
||||
assert_eq!(missing_docs, [1, 3, 5, 7, 9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -504,7 +418,7 @@ mod tests {
|
||||
let hits: Vec<u32> = vec![2, 4, 6, 8, 10];
|
||||
let mut missing_docs: Vec<u32> = Vec::new();
|
||||
find_missing_docs(&docs, &hits, &mut missing_docs);
|
||||
assert_eq!(missing_docs, Vec::<u32>::new());
|
||||
assert_eq!(missing_docs, [0u32; 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -528,7 +442,7 @@ mod tests {
|
||||
assert!(accessor.has_one_value_per_doc(&docs));
|
||||
assert_eq!(
|
||||
accessor.iter_docid_vals(&docs).collect::<Vec<_>>(),
|
||||
vec![(2, 20), (4, 40), (8, 80)]
|
||||
[(2, 20), (4, 40), (8, 80)]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -546,7 +460,7 @@ mod tests {
|
||||
assert!(accessor.has_one_value_per_doc(&docs));
|
||||
assert_eq!(
|
||||
accessor.iter_docid_vals(&docs).collect::<Vec<_>>(),
|
||||
vec![(0, 99), (1, 10), (2, 99), (4, 40)]
|
||||
[(0, 99), (1, 10), (2, 99), (4, 40)]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -564,7 +478,7 @@ mod tests {
|
||||
assert!(!accessor.has_one_value_per_doc(&docs));
|
||||
assert_eq!(
|
||||
accessor.iter_docid_vals(&docs).collect::<Vec<_>>(),
|
||||
vec![(0, 1), (0, 3), (1, 5)]
|
||||
[(0, 1), (0, 3), (1, 5)]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -589,11 +503,11 @@ mod tests {
|
||||
|
||||
assert_eq!(
|
||||
accessor.iter_vals().collect::<Vec<_>>(),
|
||||
vec![99, 10, 99, 40, 70, 99]
|
||||
[99, 10, 99, 40, 70, 99]
|
||||
);
|
||||
assert_eq!(
|
||||
accessor.iter_docid_vals(&docs).collect::<Vec<_>>(),
|
||||
vec![(0, 99), (1, 10), (2, 99), (4, 40), (7, 70), (8, 99)]
|
||||
[(0, 99), (1, 10), (2, 99), (4, 40), (7, 70), (8, 99)]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -603,8 +517,8 @@ mod tests {
|
||||
accessor.docid_cache = vec![0, 0, 2, 3];
|
||||
accessor.val_cache = vec![10, 10, 10, 10];
|
||||
accessor.dedup_docid_val_pairs();
|
||||
assert_eq!(accessor.docid_cache, vec![0, 2, 3]);
|
||||
assert_eq!(accessor.val_cache, vec![10, 10, 10]);
|
||||
assert_eq!(accessor.docid_cache, [0, 2, 3]);
|
||||
assert_eq!(accessor.val_cache, [10, 10, 10]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -614,8 +528,8 @@ mod tests {
|
||||
accessor.docid_cache = vec![0, 0, 0];
|
||||
accessor.val_cache = vec![1, 2, 1];
|
||||
accessor.dedup_docid_val_pairs();
|
||||
assert_eq!(accessor.docid_cache, vec![0, 0]);
|
||||
assert_eq!(accessor.val_cache, vec![1, 2]);
|
||||
assert_eq!(accessor.docid_cache, [0, 0]);
|
||||
assert_eq!(accessor.val_cache, [1, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -625,8 +539,8 @@ mod tests {
|
||||
accessor.docid_cache = vec![0, 0, 0, 1, 1];
|
||||
accessor.val_cache = vec![3, 1, 3, 5, 5];
|
||||
accessor.dedup_docid_val_pairs();
|
||||
assert_eq!(accessor.docid_cache, vec![0, 0, 1]);
|
||||
assert_eq!(accessor.val_cache, vec![1, 3, 5]);
|
||||
assert_eq!(accessor.docid_cache, [0, 0, 1]);
|
||||
assert_eq!(accessor.val_cache, [1, 3, 5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -635,8 +549,8 @@ mod tests {
|
||||
accessor.docid_cache = vec![0, 0, 1];
|
||||
accessor.val_cache = vec![1, 2, 3];
|
||||
accessor.dedup_docid_val_pairs();
|
||||
assert_eq!(accessor.docid_cache, vec![0, 0, 1]);
|
||||
assert_eq!(accessor.val_cache, vec![1, 2, 3]);
|
||||
assert_eq!(accessor.docid_cache, [0, 0, 1]);
|
||||
assert_eq!(accessor.val_cache, [1, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -645,18 +559,8 @@ mod tests {
|
||||
accessor.docid_cache = vec![0];
|
||||
accessor.val_cache = vec![1];
|
||||
accessor.dedup_docid_val_pairs();
|
||||
assert_eq!(accessor.docid_cache, vec![0]);
|
||||
assert_eq!(accessor.val_cache, vec![1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_contiguous() {
|
||||
assert!(!is_contiguous(&[]));
|
||||
assert!(is_contiguous(&[5]));
|
||||
assert!(is_contiguous(&[5, 6, 7, 8]));
|
||||
assert!(is_contiguous(&[0, 1, 2]));
|
||||
assert!(!is_contiguous(&[5, 7, 8]));
|
||||
assert!(!is_contiguous(&[0, 1, 3]));
|
||||
assert_eq!(accessor.docid_cache, [0]);
|
||||
assert_eq!(accessor.val_cache, [1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -0,0 +1,101 @@
|
||||
mod block_accessor;
|
||||
mod registry;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
|
||||
pub(crate) use block_accessor::ColumnBlockAccessor;
|
||||
use columnar::{Cardinality, Column, ColumnValues, RowId};
|
||||
pub use registry::{ValueSourceProvider, ValueSourceRegistry};
|
||||
|
||||
use crate::DocId;
|
||||
|
||||
/// A source of values for a block of documents.
|
||||
pub trait ValueSource: std::fmt::Debug {
|
||||
/// Loads the values for `docs` into `values`, and for a non-full source the matching document
|
||||
/// ids into `docids`, returning how the two are aligned.
|
||||
///
|
||||
/// `row_ids` is scratch the implementation may use freely. `docs` is sorted ascending with no
|
||||
/// duplicates.
|
||||
fn load_block(
|
||||
&self,
|
||||
docs: &[DocId],
|
||||
values: &mut Vec<u64>,
|
||||
docids: &mut Vec<DocId>,
|
||||
row_ids: &mut Vec<RowId>,
|
||||
) -> Cardinality;
|
||||
|
||||
/// Downcast the BlockValueSource to a Column.
|
||||
fn as_column(&self) -> Option<&Column<u64>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Global value bounds, for fast paths that need to size or clamp something up front.
|
||||
fn bounds(&self) -> Option<(u64, u64)> {
|
||||
let column = self.as_column()?;
|
||||
Some((column.min_value(), column.max_value()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ValueSource for Column<u64> {
|
||||
#[inline]
|
||||
fn load_block(
|
||||
&self,
|
||||
docs: &[DocId],
|
||||
values: &mut Vec<u64>,
|
||||
docids: &mut Vec<DocId>,
|
||||
row_ids: &mut Vec<RowId>,
|
||||
) -> Cardinality {
|
||||
let cardinality = self.index.get_cardinality();
|
||||
if cardinality.is_full() {
|
||||
load_full_column_values(docs, &*self.values, values);
|
||||
} else {
|
||||
docids.clear();
|
||||
row_ids.clear();
|
||||
self.row_ids_for_docs(docs, docids, row_ids);
|
||||
values.resize(row_ids.len(), 0u64);
|
||||
self.values.get_vals(row_ids, values);
|
||||
}
|
||||
cardinality
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn as_column(&self) -> Option<&Column<u64>> {
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn load_full_column_values(
|
||||
docs: &[DocId],
|
||||
column_values: &dyn ColumnValues<u64>,
|
||||
values: &mut Vec<u64>,
|
||||
) {
|
||||
// Skip the resize when already the right length (common case: fixed-size blocks).
|
||||
if values.len() != docs.len() {
|
||||
values.resize(docs.len(), 0u64);
|
||||
}
|
||||
// When the docs form a contiguous ascending run we can fetch the values as a single range.
|
||||
// This lets codecs (e.g. bitpacked) bulk-decode the slice instead of gathering value-by-value.
|
||||
if is_contiguous(docs) {
|
||||
column_values.get_range(docs[0] as u64, values);
|
||||
} else {
|
||||
column_values.get_vals(docs, values);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if `docs` is a contiguous ascending run `[d, d + 1, ..., d + n - 1]`.
|
||||
///
|
||||
/// Assumes `docs` is sorted ascending and free of duplicates (the invariant for the
|
||||
/// doc blocks passed to `fetch_block`), so comparing the endpoints is sufficient.
|
||||
#[inline]
|
||||
fn is_contiguous(docs: &[u32]) -> bool {
|
||||
let (Some(&first), Some(&last)) = (docs.first(), docs.last()) else {
|
||||
return false;
|
||||
};
|
||||
debug_assert!(
|
||||
docs.windows(2).all(|w| w[0] < w[1]),
|
||||
"fetch_block requires docs sorted ascending without duplicates"
|
||||
);
|
||||
(last - first) as usize + 1 == docs.len()
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use std::sync::Arc;
|
||||
|
||||
use columnar::ColumnType;
|
||||
|
||||
use super::block_accessor::ValueSource;
|
||||
use super::ValueSource;
|
||||
use crate::SegmentReader;
|
||||
|
||||
/// Acts as a ValueSource object factory, producing value source for a given Segment.
|
||||
@@ -48,7 +48,7 @@ mod tests {
|
||||
use columnar::Cardinality;
|
||||
|
||||
use super::*;
|
||||
use crate::aggregation::ColumnBlockAccessor;
|
||||
use crate::schema::Schema;
|
||||
use crate::DocId;
|
||||
|
||||
/// A stand-in source: every document has the value 1. Deliberately trivial — the point is to
|
||||
@@ -95,92 +95,21 @@ mod tests {
|
||||
let mut registry = ValueSourceRegistry::default();
|
||||
registry.register("computed", Arc::new(ConstantProvider(1)));
|
||||
registry.register("computed", Arc::new(ConstantProvider(2)));
|
||||
let index = index_with_scores(&[1u64]);
|
||||
let index = crate::Index::create_in_ram(Schema::builder().build());
|
||||
let mut writer = index.writer_for_tests().unwrap();
|
||||
writer.add_document(crate::doc!()).unwrap();
|
||||
writer.commit().unwrap();
|
||||
let searcher = index.reader().unwrap().searcher();
|
||||
let value_source_provider = registry.get("computed").unwrap();
|
||||
let mut block_accessor = ColumnBlockAccessor::default();
|
||||
let value_source = value_source_provider
|
||||
.for_segment(searcher.segment_reader(0u32))
|
||||
.unwrap();
|
||||
let mut values = Vec::new();
|
||||
let mut doc_ids = Vec::new();
|
||||
let mut row_ids = Vec::new();
|
||||
let docs = &[1u32];
|
||||
block_accessor.fetch_block(docs, &*value_source);
|
||||
assert!(block_accessor.has_one_value_per_doc(docs));
|
||||
assert_eq!(block_accessor.values(), &[2u64]);
|
||||
}
|
||||
|
||||
fn index_with_scores(scores: &[u64]) -> crate::Index {
|
||||
use crate::schema::{Schema, FAST};
|
||||
let mut builder = Schema::builder();
|
||||
let score = builder.add_u64_field("score", FAST);
|
||||
let index = crate::Index::create_in_ram(builder.build());
|
||||
let mut writer = index.writer_for_tests().unwrap();
|
||||
for &value in scores {
|
||||
writer.add_document(crate::doc!(score => value)).unwrap();
|
||||
}
|
||||
writer.commit().unwrap();
|
||||
index
|
||||
}
|
||||
|
||||
fn run_agg(index: &crate::Index, aggs: serde_json::Value) -> serde_json::Value {
|
||||
let mut registry = ValueSourceRegistry::default();
|
||||
registry.register("computed", Arc::new(ConstantProvider(1u64)));
|
||||
run_agg_with_registry(index, aggs, registry)
|
||||
}
|
||||
|
||||
fn run_agg_with_registry(
|
||||
index: &crate::Index,
|
||||
aggs: serde_json::Value,
|
||||
registry: ValueSourceRegistry,
|
||||
) -> serde_json::Value {
|
||||
use crate::aggregation::agg_req::Aggregations;
|
||||
use crate::aggregation::{AggContextParams, AggregationCollector};
|
||||
use crate::query::AllQuery;
|
||||
|
||||
let context = AggContextParams::default().with_value_sources(Arc::new(registry));
|
||||
let aggs: Aggregations = serde_json::from_value(aggs).unwrap();
|
||||
let collector = AggregationCollector::from_aggs(aggs, context);
|
||||
let searcher = index.reader().unwrap().searcher();
|
||||
let result = searcher.search(&AllQuery, &collector).unwrap();
|
||||
serde_json::to_value(result).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_metric_over_registered_source() {
|
||||
let index = index_with_scores(&[10, 20, 30, 40]);
|
||||
let result = run_agg(
|
||||
&index,
|
||||
serde_json::json!({ "s": { "stats": { "field": "computed" } } }),
|
||||
);
|
||||
// Every document contributes exactly 1.
|
||||
assert_eq!(result["s"]["count"], 4);
|
||||
assert_eq!(result["s"]["sum"], 4.0);
|
||||
assert_eq!(result["s"]["avg"], 1.0);
|
||||
assert_eq!(result["s"]["min"], 1.0);
|
||||
assert_eq!(result["s"]["max"], 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_registered_source_as_sub_aggregation_of_terms() {
|
||||
// The sub-aggregation reads the computed source out of the per-bucket doc buffer, which
|
||||
// is the path that matters: the parent drains the shared block accessor before the child
|
||||
// fetches into it.
|
||||
let index = index_with_scores(&[7, 7, 7, 9]);
|
||||
let result = run_agg(
|
||||
&index,
|
||||
serde_json::json!({
|
||||
"by_score": {
|
||||
"terms": { "field": "score" },
|
||||
"aggs": { "s": { "sum": { "field": "computed" } } }
|
||||
}
|
||||
}),
|
||||
);
|
||||
let buckets = result["by_score"]["buckets"].as_array().unwrap();
|
||||
assert_eq!(buckets.len(), 2);
|
||||
assert_eq!(buckets[0]["key"], 7.0);
|
||||
assert_eq!(buckets[0]["doc_count"], 3);
|
||||
assert_eq!(buckets[0]["s"]["value"], 3.0);
|
||||
assert_eq!(buckets[1]["key"], 9.0);
|
||||
assert_eq!(buckets[1]["doc_count"], 1);
|
||||
assert_eq!(buckets[1]["s"]["value"], 1.0);
|
||||
value_source.load_block(docs, &mut values, &mut doc_ids, &mut row_ids);
|
||||
assert!(doc_ids.is_empty());
|
||||
assert_eq!(&values, &[2u64]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use columnar::ColumnType;
|
||||
|
||||
use super::*;
|
||||
use crate::SegmentReader;
|
||||
|
||||
/// A stand-in source: every document has the value 1. Deliberately trivial — the point is to
|
||||
/// exercise registration and dispatch, not expression evaluation.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Constant(u64);
|
||||
|
||||
impl ValueSource for Constant {
|
||||
fn load_block(
|
||||
&self,
|
||||
docs: &[DocId],
|
||||
values: &mut Vec<u64>,
|
||||
_docids: &mut Vec<DocId>,
|
||||
_row_ids: &mut Vec<columnar::RowId>,
|
||||
) -> Cardinality {
|
||||
values.clear();
|
||||
values.resize(docs.len(), self.0);
|
||||
Cardinality::Full
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ConstantProvider(u64);
|
||||
|
||||
impl ValueSourceProvider for ConstantProvider {
|
||||
fn column_type(&self) -> ColumnType {
|
||||
ColumnType::U64
|
||||
}
|
||||
|
||||
fn for_segment(&self, _reader: &SegmentReader) -> crate::Result<Arc<dyn ValueSource>> {
|
||||
Ok(Arc::new(Constant(self.0)))
|
||||
}
|
||||
}
|
||||
fn index_with_scores(scores: &[u64]) -> crate::Index {
|
||||
use crate::schema::{Schema, FAST};
|
||||
let mut builder = Schema::builder();
|
||||
let score = builder.add_u64_field("score", FAST);
|
||||
let index = crate::Index::create_in_ram(builder.build());
|
||||
let mut writer = index.writer_for_tests().unwrap();
|
||||
for &value in scores {
|
||||
writer.add_document(crate::doc!(score => value)).unwrap();
|
||||
}
|
||||
writer.commit().unwrap();
|
||||
index
|
||||
}
|
||||
|
||||
fn run_agg(index: &crate::Index, aggs: serde_json::Value) -> serde_json::Value {
|
||||
let mut registry = ValueSourceRegistry::default();
|
||||
registry.register("computed", Arc::new(ConstantProvider(1u64)));
|
||||
run_agg_with_registry(index, aggs, registry)
|
||||
}
|
||||
|
||||
fn run_agg_with_registry(
|
||||
index: &crate::Index,
|
||||
aggs: serde_json::Value,
|
||||
registry: ValueSourceRegistry,
|
||||
) -> serde_json::Value {
|
||||
use crate::aggregation::agg_req::Aggregations;
|
||||
use crate::aggregation::{AggContextParams, AggregationCollector};
|
||||
use crate::query::AllQuery;
|
||||
|
||||
let context = AggContextParams::default().with_value_sources(Arc::new(registry));
|
||||
let aggs: Aggregations = serde_json::from_value(aggs).unwrap();
|
||||
let collector = AggregationCollector::from_aggs(aggs, context);
|
||||
let searcher = index.reader().unwrap().searcher();
|
||||
let result = searcher.search(&AllQuery, &collector).unwrap();
|
||||
serde_json::to_value(result).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_metric_over_registered_source() {
|
||||
let index = index_with_scores(&[10, 20, 30, 40]);
|
||||
let result = run_agg(
|
||||
&index,
|
||||
serde_json::json!({ "s": { "stats": { "field": "computed" } } }),
|
||||
);
|
||||
// Every document contributes exactly 1.
|
||||
assert_eq!(result["s"]["count"], 4);
|
||||
assert_eq!(result["s"]["sum"], 4.0);
|
||||
assert_eq!(result["s"]["avg"], 1.0);
|
||||
assert_eq!(result["s"]["min"], 1.0);
|
||||
assert_eq!(result["s"]["max"], 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_registered_source_as_sub_aggregation_of_terms() {
|
||||
// The sub-aggregation reads the computed source out of the per-bucket doc buffer, which
|
||||
// is the path that matters: the parent drains the shared block accessor before the child
|
||||
// fetches into it.
|
||||
let index = index_with_scores(&[7, 7, 7, 9]);
|
||||
let result = run_agg(
|
||||
&index,
|
||||
serde_json::json!({
|
||||
"by_score": {
|
||||
"terms": { "field": "score" },
|
||||
"aggs": { "s": { "sum": { "field": "computed" } } }
|
||||
}
|
||||
}),
|
||||
);
|
||||
let buckets = result["by_score"]["buckets"].as_array().unwrap();
|
||||
assert_eq!(buckets.len(), 2);
|
||||
assert_eq!(buckets[0]["key"], 7.0);
|
||||
assert_eq!(buckets[0]["doc_count"], 3);
|
||||
assert_eq!(buckets[0]["s"]["value"], 3.0);
|
||||
assert_eq!(buckets[1]["key"], 9.0);
|
||||
assert_eq!(buckets[1]["doc_count"], 1);
|
||||
assert_eq!(buckets[1]["s"]["value"], 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_contiguous() {
|
||||
assert!(!is_contiguous(&[]));
|
||||
assert!(is_contiguous(&[5]));
|
||||
assert!(is_contiguous(&[5, 6, 7, 8]));
|
||||
assert!(is_contiguous(&[0, 1, 2]));
|
||||
assert!(!is_contiguous(&[5, 7, 8]));
|
||||
assert!(!is_contiguous(&[0, 1, 3]));
|
||||
}
|
||||
Reference in New Issue
Block a user