diff --git a/columnar/src/column/mod.rs b/columnar/src/column/mod.rs index 70daf022e..6977e5f8c 100644 --- a/columnar/src/column/mod.rs +++ b/columnar/src/column/mod.rs @@ -11,6 +11,8 @@ use std::sync::Arc; use common::BinarySerializable; pub use dictionary_encoded::{BytesColumn, StrColumn}; #[cfg(feature = "plain_codec")] +pub(crate) use plain::PlainColumnSerializer; +#[cfg(feature = "plain_codec")] #[doc(hidden)] pub use plain::{PlainBlock, encode_block as encode_plain_block}; #[cfg(feature = "plain_codec")] diff --git a/columnar/src/column/plain/mod.rs b/columnar/src/column/plain/mod.rs index 9fd679f38..021272ed4 100644 --- a/columnar/src/column/plain/mod.rs +++ b/columnar/src/column/plain/mod.rs @@ -25,8 +25,6 @@ use std::{fmt, io}; use common::OwnedBytes; use common::file_slice::FileSlice; -// Only used by tests until the columnar writer supports the plain codec. -#[cfg_attr(not(test), allow(unused_imports))] pub(crate) use serializer::PlainColumnSerializer; #[doc(hidden)] diff --git a/columnar/src/column/plain/serializer.rs b/columnar/src/column/plain/serializer.rs index ec30fbd1b..0fce40367 100644 --- a/columnar/src/column/plain/serializer.rs +++ b/columnar/src/column/plain/serializer.rs @@ -1,6 +1,3 @@ -// Only used by tests until the columnar writer supports the plain codec. -#![cfg_attr(not(test), allow(dead_code))] - use std::io; use super::block::encode_block; diff --git a/columnar/src/columnar/merge/tests.rs b/columnar/src/columnar/merge/tests.rs index d1f4cc72e..fc361b55a 100644 --- a/columnar/src/columnar/merge/tests.rs +++ b/columnar/src/columnar/merge/tests.rs @@ -637,3 +637,29 @@ proptest! { } } + +#[cfg(feature = "plain_codec")] +#[test] +fn test_merge_columnar_plain_column_returns_error() { + use crate::StrColumnCodec; + let mut columnar_writer = ColumnarWriter::default(); + columnar_writer.set_str_column_codec("texts", ColumnType::Str, StrColumnCodec::Plain); + columnar_writer.record_str(0, "texts", "a"); + let mut plain_buffer: Vec = Vec::new(); + columnar_writer + .serialize(1, None, &mut plain_buffer) + .unwrap(); + let plain_columnar = ColumnarReader::open(plain_buffer).unwrap(); + let dictionary_columnar = make_text_columnar_multiple_columns(&[("texts", &[&["b"]])]); + let columnars = &[&plain_columnar, &dictionary_columnar]; + let stack_merge_order = StackMergeOrder::stack(columnars); + let mut buffer = Vec::new(); + let merge_error = crate::columnar::merge_columnar( + columnars, + &[], + MergeRowOrder::Stack(stack_merge_order), + &mut buffer, + ) + .unwrap_err(); + assert_eq!(merge_error.kind(), io::ErrorKind::InvalidInput); +} diff --git a/columnar/src/columnar/writer/column_operation.rs b/columnar/src/columnar/writer/column_operation.rs index b26a6dd33..d8370f160 100644 --- a/columnar/src/columnar/writer/column_operation.rs +++ b/columnar/src/columnar/writer/column_operation.rs @@ -126,7 +126,7 @@ pub(super) trait SymbolValue: Clone + Copy { // Serializes the symbol into the given buffer. // Returns the number of bytes written into the buffer. /// # Panics - /// May not exceed 9bytes + /// May not exceed 16 bytes fn serialize(self, buffer: &mut [u8]) -> u8; // Panics if invalid fn deserialize(bytes: &[u8]) -> Self; @@ -242,6 +242,40 @@ impl SymbolValue for UnorderedId { } } +/// Location of a plain-encoded value in the value bytes of its column. +/// +/// The value is `value_bytes[start..start + len]`. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd)] +pub(crate) struct PlainValueSpan { + pub start: u64, + pub len: u32, +} + +impl SymbolValue for PlainValueSpan { + /// `num_start_bytes: u8 | start (LE, num_start_bytes) | len (LE, remaining bytes)`. + /// + /// Leading zero bytes are dropped. At most 1 + 8 + 4 = 13 bytes. + fn serialize(self, output: &mut [u8]) -> u8 { + let num_start_bytes = compute_num_bytes_for_u64(self.start); + output[0] = num_start_bytes as u8; + let len_offset = 1 + num_start_bytes; + output[1..len_offset].copy_from_slice(&self.start.to_le_bytes()[..num_start_bytes]); + let num_len_bytes = self.len.serialize(&mut output[len_offset..]); + len_offset as u8 + num_len_bytes + } + + fn deserialize(mut bytes: &[u8]) -> Self { + let num_start_bytes = pop_first_byte(&mut bytes).unwrap() as usize; + let (start_bytes, len_bytes) = bytes.split_at(num_start_bytes); + let mut start_octets: [u8; 8] = [0u8; 8]; + start_octets[..start_bytes.len()].copy_from_slice(start_bytes); + PlainValueSpan { + start: u64::from_le_bytes(start_octets), + len: u32::deserialize(len_bytes), + } + } +} + fn compute_num_bytes_for_u64(val: u64) -> usize { let msb = (64u32 - val.leading_zeros()) as usize; msb.div_ceil(8) @@ -313,6 +347,24 @@ mod tests { assert_eq!(column_op, serdeser_symbol); } + #[test] + fn test_plain_value_span_serialization() { + for start in [0u64, 1, 255, 256, 1 << 40, u64::MAX] { + for len in [0u32, 1, 300, u32::MAX] { + let column_op = ColumnOperation::Value(PlainValueSpan { start, len }); + let buf = column_op.serialize(); + // 1 metadata byte + at most 13 bytes. + assert!(buf.as_ref().len() <= 14); + let mut buffer = buf.as_ref().to_vec(); + buffer.extend_from_slice(b"234234"); + let mut bytes = &buffer[..]; + let serdeser_op = ColumnOperation::::deserialize(&mut bytes); + assert_eq!(serdeser_op, Some(column_op)); + assert_eq!(bytes, b"234234"); + } + } + } + #[test] fn test_compute_num_bytes_for_u64() { assert_eq!(compute_num_bytes_for_u64(0), 0); diff --git a/columnar/src/columnar/writer/column_writers.rs b/columnar/src/columnar/writer/column_writers.rs index 6d3e2a415..e072be561 100644 --- a/columnar/src/columnar/writer/column_writers.rs +++ b/columnar/src/columnar/writer/column_writers.rs @@ -2,9 +2,9 @@ use std::cmp::Ordering; use stacker::{ExpUnrolledLinkedList, MemoryArena}; -use crate::columnar::writer::column_operation::{ColumnOperation, SymbolValue}; +use crate::columnar::writer::column_operation::{ColumnOperation, PlainValueSpan, SymbolValue}; use crate::dictionary::{DictionaryBuilder, UnorderedId}; -use crate::{Cardinality, NumericalType, NumericalValue, RowId}; +use crate::{Cardinality, NumericalType, NumericalValue, RowId, StrColumnCodec}; #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[repr(u8)] @@ -94,6 +94,11 @@ impl ColumnWriter { self.write_symbol(ColumnOperation::Value(value), arena); } + /// Returns true if no value has been recorded yet. + pub(crate) fn is_empty(&self) -> bool { + self.last_doc_opt.is_none() + } + // Get the cardinality. // The overall number of docs in the column is necessary to // deal with the case where the all docs contain 1 value, except some documents @@ -240,9 +245,25 @@ impl NumericalColumnWriter { } } +/// Storage of the values of a `Str` or `Bytes` column while indexing. +#[derive(Copy, Clone)] +pub(crate) enum StrOrBytesValues { + /// Values are deduplicated in `dictionaries[dictionary_id]`. The column records + /// `UnorderedId`s. + Dictionary { dictionary_id: u32 }, + /// Values are appended to `value_bytes` in record order, without deduplication. The column + /// records the `PlainValueSpan` of each value in `value_bytes`. + Plain { + /// We store the actual payloads in a separate exp unrolled linked list. + value_bytes: ExpUnrolledLinkedList, + /// Number of bytes in `value_bytes`. + num_bytes: u64, + }, +} + #[derive(Copy, Clone)] pub(crate) struct StrOrBytesColumnWriter { - pub(crate) dictionary_id: u32, + pub(crate) values: StrOrBytesValues, pub(crate) column_writer: ColumnWriter, // If true, when facing a multivalued cardinality, // values associated to a given document will be sorted. @@ -256,13 +277,30 @@ pub(crate) struct StrOrBytesColumnWriter { impl StrOrBytesColumnWriter { pub(crate) fn with_dictionary_id(dictionary_id: u32) -> StrOrBytesColumnWriter { + StrOrBytesColumnWriter::with_values(StrOrBytesValues::Dictionary { dictionary_id }) + } + + pub(crate) fn with_values(values: StrOrBytesValues) -> StrOrBytesColumnWriter { StrOrBytesColumnWriter { - dictionary_id, + values, column_writer: Default::default(), sort_values_within_row: false, } } + pub(crate) fn codec(&self) -> StrColumnCodec { + match self.values { + StrOrBytesValues::Dictionary { .. } => StrColumnCodec::Dictionary, + StrOrBytesValues::Plain { .. } => StrColumnCodec::Plain, + } + } + + /// Returns true if no value has been recorded yet. + pub(crate) fn is_empty(&self) -> bool { + self.column_writer.is_empty() + } + + /// Panics if the value of a plain column is larger than `u32::MAX` bytes. pub(crate) fn record_bytes( &mut self, doc: RowId, @@ -270,17 +308,48 @@ impl StrOrBytesColumnWriter { dictionaries: &mut [DictionaryBuilder], arena: &mut MemoryArena, ) { - let unordered_id = - dictionaries[self.dictionary_id as usize].get_or_allocate_id(bytes, arena); - self.column_writer.record(doc, unordered_id, arena); + match &mut self.values { + StrOrBytesValues::Dictionary { dictionary_id } => { + let unordered_id: UnorderedId = + dictionaries[*dictionary_id as usize].get_or_allocate_id(bytes, arena); + self.column_writer.record(doc, unordered_id, arena); + } + StrOrBytesValues::Plain { + value_bytes, + num_bytes, + } => { + let len: u32 = u32::try_from(bytes.len()).expect("field value to large"); + let span = PlainValueSpan { + start: *num_bytes, + len: len as u32, + }; + value_bytes.writer(arena).extend_from_slice(bytes); + *num_bytes += len as u64; + self.column_writer.record(doc, span, arena); + } + } } - pub(super) fn operation_iterator<'a>( + /// Panics if the column does not use the dictionary codec. + pub(super) fn dictionary_operation_iterator<'a>( &self, arena: &MemoryArena, old_to_new_ids: Option<&[RowId]>, byte_buffer: &'a mut Vec, ) -> impl Iterator> + 'a + use<'a> { + assert_eq!(self.codec(), StrColumnCodec::Dictionary); + self.column_writer + .operation_iterator(arena, old_to_new_ids, byte_buffer) + } + + /// Panics if the column does not use the plain codec. + pub(super) fn plain_operation_iterator<'a>( + &self, + arena: &MemoryArena, + old_to_new_ids: Option<&[RowId]>, + byte_buffer: &'a mut Vec, + ) -> impl Iterator> + 'a + use<'a> { + assert_eq!(self.codec(), StrColumnCodec::Plain); self.column_writer .operation_iterator(arena, old_to_new_ids, byte_buffer) } diff --git a/columnar/src/columnar/writer/mod.rs b/columnar/src/columnar/writer/mod.rs index 522e1d0d1..f373022ab 100644 --- a/columnar/src/columnar/writer/mod.rs +++ b/columnar/src/columnar/writer/mod.rs @@ -12,13 +12,14 @@ pub(crate) use column_writers::CompatibleNumericalTypes; use common::CountingWriter; use common::json_path_writer::JSON_END_OF_PATH; pub(crate) use serializer::ColumnarSerializer; -use stacker::{Addr, ArenaHashMap, MemoryArena}; +use stacker::{Addr, ArenaHashMap, ExpUnrolledLinkedList, MemoryArena}; use crate::column_index::{SerializableColumnIndex, SerializableOptionalIndex}; use crate::column_values::{MonotonicallyMappableToU64, MonotonicallyMappableToU128}; -use crate::columnar::column_type::ColumnType; +use crate::columnar::column_type::{ColumnType, StrColumnCodec, column_key_code}; +use crate::columnar::writer::column_operation::PlainValueSpan; use crate::columnar::writer::column_writers::{ - ColumnWriter, NumericalColumnWriter, StrOrBytesColumnWriter, + ColumnWriter, NumericalColumnWriter, StrOrBytesColumnWriter, StrOrBytesValues, }; use crate::columnar::writer::value_index::{IndexBuilder, PreallocatedIndexBuilders}; use crate::dictionary::{DictionaryBuilder, TermIdMapping, UnorderedId}; @@ -32,6 +33,8 @@ struct SpareBuffers { value_index_builders: PreallocatedIndexBuilders, u64_values: Vec, ip_addr_values: Vec, + #[cfg(feature = "plain_codec")] + plain_value_spans: Vec, } /// Makes it possible to create a new columnar. @@ -128,16 +131,44 @@ impl ColumnarWriter { let Some(str_or_bytes_column) = str_or_bytes_column_opt else { return Vec::new(); }; - let dictionary_builder = &self.dictionaries[str_or_bytes_column.dictionary_id as usize]; - let term_id_mapping = dictionary_builder.build_term_id_mapping(&self.arena); - collect_sort_order_from_ops( - str_or_bytes_column.operation_iterator(&self.arena, None, &mut symbols_buffer), - num_docs, - reversed, - |uid| Some(term_id_mapping.to_ord(uid).0), - None, - |a, b| a.cmp(b), - ) + match str_or_bytes_column.values { + StrOrBytesValues::Dictionary { dictionary_id } => { + let dictionary_builder = &self.dictionaries[dictionary_id as usize]; + let term_id_mapping = dictionary_builder.build_term_id_mapping(&self.arena); + collect_sort_order_from_ops( + str_or_bytes_column.dictionary_operation_iterator( + &self.arena, + None, + &mut symbols_buffer, + ), + num_docs, + reversed, + |uid| Some(term_id_mapping.to_ord(uid).0), + None, + |a, b| a.cmp(b), + ) + } + StrOrBytesValues::Plain { + value_bytes, + num_bytes, + } => { + // Values are sorted by bytes. This copies the bytes of the column. + let mut all_value_bytes: Vec = Vec::with_capacity(num_bytes as usize); + value_bytes.read_to_end(&self.arena, &mut all_value_bytes); + collect_sort_order_from_ops( + str_or_bytes_column.plain_operation_iterator( + &self.arena, + None, + &mut symbols_buffer, + ), + num_docs, + reversed, + |span| Some(plain_value_bytes(&all_value_bytes, span)), + None, + |a, b| a.cmp(b), + ) + } + } } /// Records a column type. This is useful to bypass the coercion process, @@ -159,27 +190,10 @@ impl ColumnarWriter { } match column_type { ColumnType::Str | ColumnType::Bytes => { - let (hash_map, dictionaries) = ( - if column_type == ColumnType::Str { - &mut self.str_field_hash_map - } else { - &mut self.bytes_field_hash_map - }, - &mut self.dictionaries, - ); - hash_map.mutate_or_create( - column_name.as_bytes(), - |column_opt: Option| { - let mut column_writer = if let Some(column_writer) = column_opt { - column_writer - } else { - let dictionary_id = dictionaries.len() as u32; - dictionaries.push(DictionaryBuilder::default()); - StrOrBytesColumnWriter::with_dictionary_id(dictionary_id) - }; - column_writer.sort_values_within_row = sort_values_within_row; - column_writer - }, + self.mutate_or_create_str_or_bytes_column( + column_name, + column_type, + |column_writer| column_writer.sort_values_within_row = sort_values_within_row, ); } ColumnType::Bool => { @@ -212,6 +226,109 @@ impl ColumnarWriter { } } + /// Sets the codec of a `Str` or `Bytes` column, creating the column if it does not exist. + /// + /// Columns are dictionary encoded by default. Values of dictionary encoded columns are + /// deduplicated while indexing. Values of plain columns are not: each value is appended to + /// the memory arena. + /// + /// Contract: the codec must be set before any value is recorded in the column. Setting the + /// codec twice keeps the last one. + /// + /// Switching an existing column to the plain codec leaves its (empty) dictionary unused: + /// call this before `record_column_type` to avoid allocating it. + /// + /// Panics if `column_type` is not `Str` or `Bytes`, if the column already has values with + /// another codec, or if `codec` is `Plain` and the `plain_codec` feature is disabled. + pub fn set_str_column_codec( + &mut self, + column_name: &str, + column_type: ColumnType, + codec: StrColumnCodec, + ) { + assert!( + matches!(column_type, ColumnType::Str | ColumnType::Bytes), + "a codec can only be set on str and bytes columns" + ); + #[cfg(not(feature = "plain_codec"))] + assert!( + codec != StrColumnCodec::Plain, + "the plain codec requires the `plain_codec` feature" + ); + let (hash_map, dictionaries) = ( + if column_type == ColumnType::Str { + &mut self.str_field_hash_map + } else { + &mut self.bytes_field_hash_map + }, + &mut self.dictionaries, + ); + hash_map.mutate_or_create( + column_name.as_bytes(), + |column_opt: Option| { + if let Some(column_writer) = column_opt { + if column_writer.codec() == codec { + return column_writer; + } + assert!( + column_writer.is_empty(), + "the codec of a column must be set before values are recorded" + ); + } + let values = match codec { + StrColumnCodec::Dictionary => { + let dictionary_id = dictionaries.len() as u32; + dictionaries.push(DictionaryBuilder::default()); + StrOrBytesValues::Dictionary { dictionary_id } + } + StrColumnCodec::Plain => StrOrBytesValues::Plain { + value_bytes: ExpUnrolledLinkedList::default(), + num_bytes: 0, + }, + }; + let mut column_writer = StrOrBytesColumnWriter::with_values(values); + if let Some(previous_column_writer) = column_opt { + column_writer.sort_values_within_row = + previous_column_writer.sort_values_within_row; + } + column_writer + }, + ); + } + + /// Applies `mutate` to the `Str` or `Bytes` column writer, creating it if it does not exist. + /// + /// Precondition: `column_type` is `Str` or `Bytes`. + fn mutate_or_create_str_or_bytes_column( + &mut self, + column_name: &str, + column_type: ColumnType, + mut mutate: impl FnMut(&mut StrOrBytesColumnWriter), + ) { + let (hash_map, dictionaries) = ( + if column_type == ColumnType::Str { + &mut self.str_field_hash_map + } else { + &mut self.bytes_field_hash_map + }, + &mut self.dictionaries, + ); + hash_map.mutate_or_create( + column_name.as_bytes(), + |column_opt: Option| { + let mut column_writer = if let Some(column_writer) = column_opt { + column_writer + } else { + let dictionary_id = dictionaries.len() as u32; + dictionaries.push(DictionaryBuilder::default()); + StrOrBytesColumnWriter::with_dictionary_id(dictionary_id) + }; + mutate(&mut column_writer); + column_writer + }, + ); + } + /// Registers a full `i64` column whose values are generated when this writer is serialized. pub fn record_tie_breaker_column(&mut self, column_name: &str) { self.record_column_type(column_name, ColumnType::I64, false); @@ -325,45 +442,41 @@ impl ColumnarWriter { ) -> io::Result<()> { let mut serializer = ColumnarSerializer::new(wrt); - let mut columns: Vec<(&[u8], ColumnType, Addr)> = self + let mut columns: Vec<(&[u8], ColumnType, StrColumnCodec, Addr)> = self .numerical_field_hash_map .iter() .map(|(column_name, addr)| { let numerical_column_writer: NumericalColumnWriter = self.numerical_field_hash_map.read(addr); let column_type = numerical_column_writer.numerical_type().into(); - (column_name, column_type, addr) + (column_name, column_type, StrColumnCodec::Dictionary, addr) }) .collect(); - columns.extend( - self.bytes_field_hash_map - .iter() - .map(|(column_name, addr)| (column_name, ColumnType::Bytes, addr)), - ); - columns.extend( - self.str_field_hash_map - .iter() - .map(|(column_name, addr)| (column_name, ColumnType::Str, addr)), - ); - columns.extend( - self.bool_field_hash_map - .iter() - .map(|(column_name, addr)| (column_name, ColumnType::Bool, addr)), - ); - columns.extend( - self.ip_addr_field_hash_map - .iter() - .map(|(column_name, addr)| (column_name, ColumnType::IpAddr, addr)), - ); - columns.extend( - self.datetime_field_hash_map - .iter() - .map(|(column_name, addr)| (column_name, ColumnType::DateTime, addr)), - ); - columns.sort_unstable_by_key(|(column_name, col_type, _)| (*column_name, *col_type)); + columns.extend(self.bytes_field_hash_map.iter().map(|(column_name, addr)| { + let column_writer: StrOrBytesColumnWriter = self.bytes_field_hash_map.read(addr); + (column_name, ColumnType::Bytes, column_writer.codec(), addr) + })); + columns.extend(self.str_field_hash_map.iter().map(|(column_name, addr)| { + let column_writer: StrOrBytesColumnWriter = self.str_field_hash_map.read(addr); + (column_name, ColumnType::Str, column_writer.codec(), addr) + })); + for (hash_map, column_type) in [ + (&self.bool_field_hash_map, ColumnType::Bool), + (&self.ip_addr_field_hash_map, ColumnType::IpAddr), + (&self.datetime_field_hash_map, ColumnType::DateTime), + ] { + columns.extend(hash_map.iter().map(|(column_name, addr)| { + (column_name, column_type, StrColumnCodec::Dictionary, addr) + })); + } + // The serializer requires the columns in the order of their keys. The key code of + // plain columns does not follow the order of the column types. + columns.sort_unstable_by_key(|(column_name, column_type, codec, _)| { + (*column_name, column_key_code(*column_type, *codec)) + }); let (arena, buffers, dictionaries) = (&self.arena, &mut self.buffers, &self.dictionaries); let mut symbol_byte_buffer: Vec = Vec::new(); - for (column_name, column_type, addr) in columns { + for (column_name, column_type, codec, addr) in columns { if column_name.contains(&JSON_END_OF_PATH) { // Tantivy uses b'0' as a separator for nested fields in JSON. // Column names with a b'0' are not simply ignored by the columnar (and the inverted @@ -414,27 +527,61 @@ impl ColumnarWriter { } else { self.str_field_hash_map.read(addr) }; - let dictionary_builder = - &dictionaries[str_or_bytes_column_writer.dictionary_id as usize]; let cardinality = str_or_bytes_column_writer .column_writer .get_cardinality(num_docs); - let mut column_serializer = - serializer.start_serialize_column(column_name, column_type); - serialize_bytes_or_str_column( - cardinality, - num_docs, - str_or_bytes_column_writer.sort_values_within_row, - dictionary_builder, - str_or_bytes_column_writer.operation_iterator( - arena, - old_to_new_row_ids, - &mut symbol_byte_buffer, - ), - buffers, - &self.arena, - &mut column_serializer, - )?; + let mut column_serializer = serializer.start_serialize_column_with_codec( + column_name, + column_type, + codec, + ); + match str_or_bytes_column_writer.values { + StrOrBytesValues::Dictionary { dictionary_id } => { + serialize_bytes_or_str_column( + cardinality, + num_docs, + str_or_bytes_column_writer.sort_values_within_row, + &dictionaries[dictionary_id as usize], + str_or_bytes_column_writer.dictionary_operation_iterator( + arena, + old_to_new_row_ids, + &mut symbol_byte_buffer, + ), + buffers, + &self.arena, + &mut column_serializer, + )?; + } + #[cfg(feature = "plain_codec")] + StrOrBytesValues::Plain { + value_bytes, + num_bytes, + } => { + serialize_plain_bytes_or_str_column( + cardinality, + num_docs, + str_or_bytes_column_writer.sort_values_within_row, + old_to_new_row_ids.is_some(), + &value_bytes, + num_bytes, + str_or_bytes_column_writer.plain_operation_iterator( + arena, + old_to_new_row_ids, + &mut symbol_byte_buffer, + ), + buffers, + &self.arena, + &mut column_serializer, + )?; + } + #[cfg(not(feature = "plain_codec"))] + StrOrBytesValues::Plain { .. } => { + unreachable!( + "`set_str_column_codec` rejects the plain codec without the \ + `plain_codec` feature" + ) + } + } column_serializer.finalize()?; } ColumnType::F64 | ColumnType::I64 | ColumnType::U64 => { @@ -615,6 +762,89 @@ fn serialize_bytes_or_str_column( Ok(()) } +/// Returns the bytes of the plain value `span`. +/// +/// Precondition: `all_value_bytes` holds all of the value bytes of the column of `span`. +fn plain_value_bytes(all_value_bytes: &[u8], span: PlainValueSpan) -> &[u8] { + let start = span.start as usize; + &all_value_bytes[start..start + span.len as usize] +} + +/// Serializes a plain-encoded `Str` or `Bytes` column with the `PlainColumnSerializer`. +/// +/// `value_bytes` holds the `num_bytes` bytes of the values, in record order. If +/// `sort_values_within_row` is set, the values of a row are sorted by bytes. +/// +/// Without doc remapping and without sorting, the values are streamed from the arena. Otherwise, +/// the value bytes are first copied in a buffer for random access. +#[cfg(feature = "plain_codec")] +#[expect(clippy::too_many_arguments)] +fn serialize_plain_bytes_or_str_column( + cardinality: Cardinality, + num_docs: RowId, + sort_values_within_row: bool, + is_remapped: bool, + value_bytes: &ExpUnrolledLinkedList, + num_bytes: u64, + operation_it: impl Iterator>, + buffers: &mut SpareBuffers, + arena: &MemoryArena, + wrt: impl io::Write, +) -> io::Result<()> { + let SpareBuffers { + value_index_builders, + plain_value_spans, + .. + } = buffers; + plain_value_spans.clear(); + let column_index = build_serializable_column_index( + operation_it, + cardinality, + num_docs, + value_index_builders, + plain_value_spans, + ); + let mut plain_serializer = crate::column::PlainColumnSerializer::new(wrt); + let multivalued_index_opt = match &column_index { + SerializableColumnIndex::Multivalued(multivalued_index) if sort_values_within_row => { + Some(multivalued_index) + } + _ => None, + }; + if !is_remapped && multivalued_index_opt.is_none() { + // The spans are contiguous and in record order: the values are streamed. + let mut value_chunks = value_bytes.iter_chunks(arena); + let mut num_bytes_read: u64 = 0; + for span in plain_value_spans.iter() { + debug_assert_eq!(span.start, num_bytes_read); + let len = span.len as usize; + plain_serializer.add_value_with(len, |block_bytes| { + value_chunks.read_exact_into(len, block_bytes) + })?; + num_bytes_read += span.len as u64; + } + debug_assert_eq!(num_bytes_read, num_bytes); + return plain_serializer.finish(column_index); + } + let mut all_value_bytes: Vec = Vec::with_capacity(num_bytes as usize); + value_bytes.read_to_end(arena, &mut all_value_bytes); + if let Some(multivalued_index) = multivalued_index_opt { + let mut start_index: usize = 0; + for end_index in multivalued_index.start_offsets.boxed_iter() { + let end_index = end_index as usize; + plain_value_spans[start_index..end_index].sort_unstable_by(|left, right| { + plain_value_bytes(&all_value_bytes, *left) + .cmp(plain_value_bytes(&all_value_bytes, *right)) + }); + start_index = end_index; + } + } + for span in plain_value_spans.iter() { + plain_serializer.add_value(plain_value_bytes(&all_value_bytes, *span))?; + } + plain_serializer.finish(column_index) +} + fn serialize_numerical_column( cardinality: Cardinality, num_docs: RowId, @@ -727,32 +957,13 @@ fn send_to_serialize_column_mappable_to_u128< mut wrt: impl io::Write, ) -> io::Result<()> { values.clear(); - // TODO: split index and values - let serializable_column_index = match cardinality { - Cardinality::Full => { - consume_operation_iterator( - op_iterator, - value_index_builders.borrow_required_index_builder(), - values, - ); - SerializableColumnIndex::Full - } - Cardinality::Optional => { - let optional_index_builder = value_index_builders.borrow_optional_index_builder(); - consume_operation_iterator(op_iterator, optional_index_builder, values); - let optional_index = optional_index_builder.finish(num_rows); - SerializableColumnIndex::Optional(SerializableOptionalIndex { - num_rows, - non_null_row_ids: Box::new(optional_index), - }) - } - Cardinality::Multivalued => { - let multivalued_index_builder = value_index_builders.borrow_multivalued_index_builder(); - consume_operation_iterator(op_iterator, multivalued_index_builder, values); - let serializable_multivalued_index = multivalued_index_builder.finish(num_rows); - SerializableColumnIndex::Multivalued(serializable_multivalued_index) - } - }; + let serializable_column_index = build_serializable_column_index( + op_iterator, + cardinality, + num_rows, + value_index_builders, + values, + ); crate::column::serialize_column_mappable_to_u128( serializable_column_index, &&values[..], @@ -771,7 +982,38 @@ fn send_to_serialize_column_mappable_to_u64( mut wrt: impl io::Write, ) -> io::Result<()> { values.clear(); - let serializable_column_index = match cardinality { + let serializable_column_index = build_serializable_column_index( + op_iterator, + cardinality, + num_rows, + value_index_builders, + values, + ); + if sort_values_within_row + && let SerializableColumnIndex::Multivalued(multivalued_index) = &serializable_column_index + { + sort_values_within_row_in_place(multivalued_index.start_offsets.boxed_iter(), values); + } + crate::column::serialize_column_mappable_to_u64( + serializable_column_index, + &&values[..], + &mut wrt, + )?; + Ok(()) +} + +/// Consumes the operations: values are appended to `values`, and the returned column index maps +/// rows to them. +/// +/// Contract: `cardinality` is the cardinality of the column described by `op_iterator`. +fn build_serializable_column_index<'a, T: Ord>( + op_iterator: impl Iterator>, + cardinality: Cardinality, + num_rows: RowId, + value_index_builders: &'a mut PreallocatedIndexBuilders, + values: &mut Vec, +) -> SerializableColumnIndex<'a> { + match cardinality { Cardinality::Full => { consume_operation_iterator( op_iterator, @@ -792,22 +1034,9 @@ fn send_to_serialize_column_mappable_to_u64( Cardinality::Multivalued => { let multivalued_index_builder = value_index_builders.borrow_multivalued_index_builder(); consume_operation_iterator(op_iterator, multivalued_index_builder, values); - let serializable_multivalued_index = multivalued_index_builder.finish(num_rows); - if sort_values_within_row { - sort_values_within_row_in_place( - serializable_multivalued_index.start_offsets.boxed_iter(), - values, - ); - } - SerializableColumnIndex::Multivalued(serializable_multivalued_index) + SerializableColumnIndex::Multivalued(multivalued_index_builder.finish(num_rows)) } - }; - crate::column::serialize_column_mappable_to_u64( - serializable_column_index, - &&values[..], - &mut wrt, - )?; - Ok(()) + } } fn sort_values_within_row_in_place( @@ -953,4 +1182,294 @@ mod tests { ColumnOperation::Value(NumericalValue::I64(17i64)) )); } + + #[cfg(feature = "plain_codec")] + mod plain { + use crate::{ + ColumnType, ColumnarReader, DynamicColumn, PlainBytesColumn, RowId, StrColumnCodec, + }; + + fn serialize_and_open( + columnar_writer: &mut crate::ColumnarWriter, + num_docs: RowId, + old_to_new_row_ids: Option<&[RowId]>, + ) -> ColumnarReader { + let mut buffer: Vec = Vec::new(); + columnar_writer + .serialize(num_docs, old_to_new_row_ids, &mut buffer) + .unwrap(); + ColumnarReader::open(buffer).unwrap() + } + + fn open_single_column(columnar: &ColumnarReader, column_name: &str) -> DynamicColumn { + let handles = columnar.read_columns(column_name).unwrap(); + assert_eq!(handles.len(), 1); + handles[0].open().unwrap() + } + + fn values_per_doc(column: &PlainBytesColumn, num_docs: u32) -> Vec>> { + let mut reader = column.reader(); + let mut values_per_doc: Vec>> = Vec::with_capacity(num_docs as usize); + for doc in 0..num_docs { + let mut doc_values: Vec> = Vec::new(); + reader + .for_each_value(doc, |value| doc_values.push(value.to_vec())) + .unwrap(); + values_per_doc.push(doc_values); + } + values_per_doc + } + + fn to_bytes(values_per_doc: &[&[&str]]) -> Vec>> { + values_per_doc + .iter() + .map(|doc_values| { + doc_values + .iter() + .map(|value| value.as_bytes().to_vec()) + .collect() + }) + .collect() + } + + #[test] + fn test_plain_str_column() { + let mut columnar_writer = crate::ColumnarWriter::default(); + columnar_writer.set_str_column_codec("text", ColumnType::Str, StrColumnCodec::Plain); + columnar_writer.record_str(0, "text", "hello"); + columnar_writer.record_str(0, "text", "world"); + columnar_writer.record_str(2, "text", "hello"); + columnar_writer.record_str(3, "text", ""); + let columnar = serialize_and_open(&mut columnar_writer, 4, None); + let DynamicColumn::PlainStr(plain_str_column) = open_single_column(&columnar, "text") + else { + panic!("expected a plain str column"); + }; + let plain_bytes_column = PlainBytesColumn::from(plain_str_column); + assert_eq!(plain_bytes_column.num_values(), 4); + assert_eq!( + values_per_doc(&plain_bytes_column, 4), + to_bytes(&[&["hello", "world"], &[], &["hello"], &[""]]) + ); + } + + #[test] + fn test_plain_bytes_column_optional() { + let mut columnar_writer = crate::ColumnarWriter::default(); + columnar_writer.set_str_column_codec("bytes", ColumnType::Bytes, StrColumnCodec::Plain); + columnar_writer.record_bytes(1, "bytes", b"b"); + columnar_writer.record_bytes(2, "bytes", b"a"); + let columnar = serialize_and_open(&mut columnar_writer, 3, None); + let DynamicColumn::PlainBytes(plain_bytes_column) = + open_single_column(&columnar, "bytes") + else { + panic!("expected a plain bytes column"); + }; + assert_eq!( + plain_bytes_column.get_cardinality(), + crate::Cardinality::Optional + ); + assert_eq!( + values_per_doc(&plain_bytes_column, 3), + to_bytes(&[&[], &["b"], &["a"]]) + ); + } + + #[test] + fn test_plain_column_with_doc_remapping() { + let mut columnar_writer = crate::ColumnarWriter::default(); + columnar_writer.set_str_column_codec("text", ColumnType::Str, StrColumnCodec::Plain); + columnar_writer.record_str(0, "text", "doc0"); + columnar_writer.record_str(1, "text", "doc1"); + columnar_writer.record_str(2, "text", "doc2"); + let old_to_new_row_ids: Vec = vec![2, 0, 1]; + let columnar = serialize_and_open(&mut columnar_writer, 3, Some(&old_to_new_row_ids)); + let DynamicColumn::PlainStr(plain_str_column) = open_single_column(&columnar, "text") + else { + panic!("expected a plain str column"); + }; + assert_eq!( + values_per_doc(&PlainBytesColumn::from(plain_str_column), 3), + to_bytes(&[&["doc1"], &["doc2"], &["doc0"]]) + ); + } + + #[test] + fn test_plain_column_sort_values_within_row() { + let mut columnar_writer = crate::ColumnarWriter::default(); + columnar_writer.record_column_type("text", ColumnType::Str, true); + columnar_writer.set_str_column_codec("text", ColumnType::Str, StrColumnCodec::Plain); + for value in ["c", "a", "b"] { + columnar_writer.record_str(0, "text", value); + } + columnar_writer.record_str(1, "text", "z"); + columnar_writer.record_str(1, "text", "y"); + let columnar = serialize_and_open(&mut columnar_writer, 2, None); + let DynamicColumn::PlainStr(plain_str_column) = open_single_column(&columnar, "text") + else { + panic!("expected a plain str column"); + }; + assert_eq!( + values_per_doc(&PlainBytesColumn::from(plain_str_column), 2), + to_bytes(&[&["a", "b", "c"], &["y", "z"]]) + ); + } + + #[test] + fn test_plain_column_key_order() { + // The key code of a plain bytes column (0x13) is greater than the key code of a + // dictionary str column (0x04), although `Bytes < Str`. + let mut columnar_writer = crate::ColumnarWriter::default(); + columnar_writer.set_str_column_codec("field", ColumnType::Bytes, StrColumnCodec::Plain); + columnar_writer.record_bytes(0, "field", b"bytes"); + columnar_writer.record_str(0, "field", "str"); + columnar_writer.record_numerical(0, "field", 1u64); + let columnar = serialize_and_open(&mut columnar_writer, 1, None); + let mut codecs: Vec<(ColumnType, Option)> = columnar + .read_columns("field") + .unwrap() + .iter() + .map(|handle| (handle.column_type(), handle.str_codec())) + .collect(); + codecs.sort_by_key(|(column_type, _)| *column_type); + assert_eq!( + codecs, + vec![ + (ColumnType::I64, None), + (ColumnType::Bytes, Some(StrColumnCodec::Plain)), + (ColumnType::Str, Some(StrColumnCodec::Dictionary)), + ] + ); + } + + #[test] + fn test_plain_column_large_values() { + // Larger than a memory arena page (1 MiB) and than an `ExpUnrolledLinkedList` block. + let large_value: Vec = (0..3_000_000u32).map(|i| (i % 251) as u8).collect(); + let mut columnar_writer = crate::ColumnarWriter::default(); + columnar_writer.set_str_column_codec("bytes", ColumnType::Bytes, StrColumnCodec::Plain); + columnar_writer.record_bytes(0, "bytes", b"small"); + columnar_writer.record_bytes(1, "bytes", &large_value); + columnar_writer.record_bytes(1, "bytes", b""); + columnar_writer.record_bytes(2, "bytes", b"small2"); + let columnar = serialize_and_open(&mut columnar_writer, 3, None); + let DynamicColumn::PlainBytes(plain_bytes_column) = + open_single_column(&columnar, "bytes") + else { + panic!("expected a plain bytes column"); + }; + assert_eq!( + values_per_doc(&plain_bytes_column, 3), + vec![ + vec![b"small".to_vec()], + vec![large_value, Vec::new()], + vec![b"small2".to_vec()], + ] + ); + } + + #[test] + fn test_plain_column_values_are_not_deduplicated() { + let value: Vec = vec![b'x'; 1_000]; + let num_docs: u32 = 3_000; + let mut columnar_writer = crate::ColumnarWriter::default(); + columnar_writer.set_str_column_codec("bytes", ColumnType::Bytes, StrColumnCodec::Plain); + for doc in 0..num_docs { + columnar_writer.record_bytes(doc, "bytes", &value); + } + // Each value is stored in the memory arena. + assert!(columnar_writer.mem_usage() >= num_docs as usize * value.len()); + let columnar = serialize_and_open(&mut columnar_writer, num_docs, None); + let DynamicColumn::PlainBytes(plain_bytes_column) = + open_single_column(&columnar, "bytes") + else { + panic!("expected a plain bytes column"); + }; + assert_eq!(plain_bytes_column.num_values(), num_docs); + assert_eq!( + values_per_doc(&plain_bytes_column, num_docs), + vec![vec![value]; num_docs as usize] + ); + } + + #[test] + fn test_plain_columns_interleaved() { + let mut columnar_writer = crate::ColumnarWriter::default(); + columnar_writer.set_str_column_codec("left", ColumnType::Str, StrColumnCodec::Plain); + columnar_writer.set_str_column_codec("right", ColumnType::Str, StrColumnCodec::Plain); + for doc in 0..100u32 { + columnar_writer.record_str(doc, "left", &format!("left{doc}")); + columnar_writer.record_str(doc, "right", &format!("right{doc}")); + } + let columnar = serialize_and_open(&mut columnar_writer, 100, None); + for column_name in ["left", "right"] { + let DynamicColumn::PlainStr(plain_str_column) = + open_single_column(&columnar, column_name) + else { + panic!("expected a plain str column"); + }; + let expected: Vec>> = (0..100u32) + .map(|doc| vec![format!("{column_name}{doc}").into_bytes()]) + .collect(); + assert_eq!( + values_per_doc(&PlainBytesColumn::from(plain_str_column), 100), + expected + ); + } + } + + #[test] + fn test_plain_column_sort_order() { + let mut columnar_writer = crate::ColumnarWriter::default(); + columnar_writer.set_str_column_codec("text", ColumnType::Str, StrColumnCodec::Plain); + columnar_writer.record_str(0, "text", "b"); + columnar_writer.record_str(2, "text", "a"); + columnar_writer.record_str(3, "text", "c"); + // Only the first value of a doc is used. + columnar_writer.record_str(3, "text", "0"); + assert_eq!( + columnar_writer.sort_order("text", 4, false), + vec![1, 2, 0, 3] + ); + assert_eq!( + columnar_writer.sort_order("text", 4, true), + vec![3, 0, 2, 1] + ); + } + + #[test] + fn test_set_str_column_codec_switch_before_values() { + let mut columnar_writer = crate::ColumnarWriter::default(); + columnar_writer.record_column_type("text", ColumnType::Str, true); + columnar_writer.set_str_column_codec("text", ColumnType::Str, StrColumnCodec::Plain); + columnar_writer.set_str_column_codec("text", ColumnType::Str, StrColumnCodec::Plain); + columnar_writer.record_str(0, "text", "b"); + columnar_writer.record_str(0, "text", "a"); + let columnar = serialize_and_open(&mut columnar_writer, 1, None); + let DynamicColumn::PlainStr(plain_str_column) = open_single_column(&columnar, "text") + else { + panic!("expected a plain str column"); + }; + // `sort_values_within_row` is kept when the codec changes. + assert_eq!( + values_per_doc(&PlainBytesColumn::from(plain_str_column), 1), + to_bytes(&[&["a", "b"]]) + ); + } + + #[test] + #[should_panic(expected = "the codec of a column must be set before values are recorded")] + fn test_set_str_column_codec_after_values_panics() { + let mut columnar_writer = crate::ColumnarWriter::default(); + columnar_writer.record_str(0, "text", "a"); + columnar_writer.set_str_column_codec("text", ColumnType::Str, StrColumnCodec::Plain); + } + + #[test] + #[should_panic(expected = "a codec can only be set on str and bytes columns")] + fn test_set_str_column_codec_numerical_panics() { + let mut columnar_writer = crate::ColumnarWriter::default(); + columnar_writer.set_str_column_codec("num", ColumnType::U64, StrColumnCodec::Plain); + } + } } diff --git a/src/fastfield/writer.rs b/src/fastfield/writer.rs index 4178f736a..0259fbae4 100644 --- a/src/fastfield/writer.rs +++ b/src/fastfield/writer.rs @@ -1,6 +1,6 @@ use std::io; -use columnar::{ColumnarWriter, NumericalValue}; +use columnar::{ColumnType, ColumnarWriter, NumericalValue, StrColumnCodec}; use common::{DateTimePrecision, JsonPathWriter}; use tokenizer_api::Token; @@ -32,6 +32,40 @@ fn resolve_fast_field_tokenizer( Ok(Some(text_analyzer)) } +/// Returns the column type and the codec of a `Str` or `Bytes` fast field, or `None` for other +/// field types. +/// +/// Returns an error if the codec is not supported for this field. +fn fast_field_str_or_bytes_codec( + field_name: &str, + field_type: &FieldType, +) -> crate::Result> { + let (column_type, codec) = match field_type { + FieldType::Str(text_options) => (ColumnType::Str, text_options.get_fast_field_codec()), + FieldType::Bytes(bytes_options) => { + (ColumnType::Bytes, bytes_options.get_fast_field_codec()) + } + FieldType::JsonObject(json_object_options) => { + if json_object_options.get_fast_field_codec() == Some(StrColumnCodec::Plain) { + return Err(TantivyError::InvalidArgument(format!( + "the plain fast field codec is not supported for the JSON field `{field_name}`" + ))); + } + return Ok(None); + } + _ => return Ok(None), + }; + let Some(codec) = codec else { + return Ok(None); + }; + if codec == StrColumnCodec::Plain && !cfg!(feature = "plain_codec") { + return Err(TantivyError::InvalidArgument(format!( + "the plain fast field codec of field `{field_name}` requires the `plain_codec` feature" + ))); + } + Ok(Some((column_type, codec))) +} + /// The `FastFieldsWriter` groups all of the fast field writers. pub struct FastFieldsWriter { columnar_writer: ColumnarWriter, @@ -94,6 +128,12 @@ impl FastFieldsWriter { )?; } + // The codec is set first: a plain column then never allocates a dictionary. + if let Some((column_type, codec)) = + fast_field_str_or_bytes_codec(field_entry.name(), field_entry.field_type())? + { + columnar_writer.set_str_column_codec(field_entry.name(), column_type, codec); + } let sort_values_within_row = value_type == Type::Facet; if let Some(column_type) = value_type_to_column_type(value_type) { columnar_writer.record_column_type( @@ -409,6 +449,119 @@ mod tests { assert!(fast_fields_writer.per_field_tokenizer[json_field.field_id() as usize].is_none()); } + #[cfg(feature = "plain_codec")] + #[test] + fn test_plain_codec_text_and_bytes_fast_fields() { + use columnar::{ColumnType, DynamicColumn, PlainBytesColumn, StrColumnCodec}; + + use crate::schema::{BytesOptions, TextOptions}; + use crate::{Index, IndexWriter}; + + let mut schema_builder = Schema::builder(); + let text_field = schema_builder.add_text_field( + "text", + TextOptions::default().set_fast_codec(StrColumnCodec::Plain), + ); + let bytes_field = schema_builder.add_bytes_field( + "bytes", + BytesOptions::default().set_fast_codec(StrColumnCodec::Plain), + ); + let dictionary_text_field = schema_builder.add_text_field("dictionary_text", FAST); + let index = Index::create_in_ram(schema_builder.build()); + let mut index_writer: IndexWriter = index.writer_for_tests().unwrap(); + index_writer + .add_document(doc!( + text_field => "hello", + text_field => "world", + bytes_field => b"abc".as_ref(), + dictionary_text_field => "dict", + )) + .unwrap(); + index_writer.add_document(doc!()).unwrap(); + index_writer + .add_document(doc!(text_field => "hello")) + .unwrap(); + index_writer.commit().unwrap(); + let searcher = index.reader().unwrap().searcher(); + let fast_fields = searcher.segment_reader(0).fast_fields(); + + let read_values = |column: &PlainBytesColumn| -> Vec>> { + let mut reader = column.reader(); + (0..3) + .map(|doc| { + let mut doc_values: Vec> = Vec::new(); + reader + .for_each_value(doc, |value| doc_values.push(value.to_vec())) + .unwrap(); + doc_values + }) + .collect() + }; + + let text_column = fast_fields + .dynamic_column_handle("text", ColumnType::Str) + .unwrap() + .unwrap() + .open() + .unwrap(); + let DynamicColumn::PlainStr(plain_str_column) = text_column else { + panic!("expected a plain str column"); + }; + assert_eq!( + read_values(&PlainBytesColumn::from(plain_str_column)), + vec![ + vec![b"hello".to_vec(), b"world".to_vec()], + vec![], + vec![b"hello".to_vec()] + ] + ); + + let bytes_column = fast_fields + .dynamic_column_handle("bytes", ColumnType::Bytes) + .unwrap() + .unwrap() + .open() + .unwrap(); + let DynamicColumn::PlainBytes(plain_bytes_column) = bytes_column else { + panic!("expected a plain bytes column"); + }; + assert_eq!( + read_values(&plain_bytes_column), + vec![vec![b"abc".to_vec()], vec![], vec![]] + ); + + let dictionary_text_handle = fast_fields + .dynamic_column_handle("dictionary_text", ColumnType::Str) + .unwrap() + .unwrap(); + assert_eq!( + dictionary_text_handle.str_codec(), + Some(StrColumnCodec::Dictionary) + ); + } + + #[test] + fn test_plain_codec_json_field_rejected() { + let json_options: crate::schema::JsonObjectOptions = + serde_json::from_value(serde_json::json!({ + "stored": false, + "fast": { "codec": "plain" } + })) + .unwrap(); + let mut schema_builder = Schema::builder(); + schema_builder.add_json_field("json", json_options); + let schema = schema_builder.build(); + let Err(error) = FastFieldsWriter::from_schema(&schema) else { + panic!("the plain codec should be rejected for JSON fields"); + }; + assert!( + error + .to_string() + .contains("not supported for the JSON field"), + "unexpected error: {error}" + ); + } + fn test_columnar_from_jsons_aux( json_docs: &[serde_json::Value], expand_dots: bool, diff --git a/src/indexer/merger.rs b/src/indexer/merger.rs index 4d0d9d2de..f8ea7d8e3 100644 --- a/src/indexer/merger.rs +++ b/src/indexer/merger.rs @@ -1290,6 +1290,34 @@ mod tests { Ok(()) } + #[cfg(feature = "plain_codec")] + #[test] + fn test_merge_plain_fast_field_returns_error() { + let mut schema_builder = schema::Schema::builder(); + let text_options = + schema::TextOptions::default().set_fast_codec(columnar::StrColumnCodec::Plain); + let text_field = schema_builder.add_text_field("text", text_options); + let index = Index::create_in_ram(schema_builder.build()); + let mut index_writer: IndexWriter = index.writer_for_tests().unwrap(); + index_writer.set_merge_policy(Box::new(NoMergePolicy)); + index_writer.add_document(doc!(text_field => "a")).unwrap(); + index_writer.commit().unwrap(); + index_writer.add_document(doc!(text_field => "b")).unwrap(); + index_writer.commit().unwrap(); + // `IndexWriter::merge` panics on merge errors in tests: the merger is called directly. + let segments = index.searchable_segments().unwrap(); + assert_eq!(segments.len(), 2); + let merger = + super::IndexMerger::open(index.schema(), index.settings().clone(), &segments).unwrap(); + let merge_error = merger.write(&index.new_segment()).unwrap_err(); + assert!( + merge_error + .to_string() + .contains("merging plain-encoded columns is not supported"), + "unexpected error: {merge_error}" + ); + } + #[derive(Debug, Clone, Copy, Eq, PartialEq)] enum IndexingOp { ZeroVal, diff --git a/src/schema/bytes_options.rs b/src/schema/bytes_options.rs index e5c28ea15..54594fc9d 100644 --- a/src/schema/bytes_options.rs +++ b/src/schema/bytes_options.rs @@ -1,18 +1,66 @@ use std::ops::BitOr; +use columnar::StrColumnCodec; use serde::{Deserialize, Serialize}; use super::flags::{FastFlag, IndexedFlag, SchemaFlagList, StoredFlag}; +use super::text_options::merge_str_column_codecs; /// Define how a bytes field should be handled by tantivy. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(from = "BytesOptionsDeser")] pub struct BytesOptions { indexed: bool, fieldnorms: bool, - fast: bool, + /// Codec of the fast field, or `None` if the field is not a fast field. + #[serde(with = "fast_field_bytes_options_serde")] + fast: Option, stored: bool, } +/// Wire format of the fast field options of bytes fields, as an `Option`: +/// - `false`: not a fast field. +/// - `true`: a fast field with the dictionary codec. +/// - `{"codec": "plain"}`: a fast field with the given codec. The key is optional. +mod fast_field_bytes_options_serde { + use columnar::StrColumnCodec; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + #[derive(Serialize, Deserialize)] + #[serde(untagged)] + enum WireFormat { + IsEnabled(bool), + EnabledWithOptions { + #[serde(default)] + codec: StrColumnCodec, + }, + } + + pub fn serialize( + fast_codec: &Option, + serializer: S, + ) -> Result + where + S: Serializer, + { + let wire_format = match fast_codec { + None => WireFormat::IsEnabled(false), + Some(StrColumnCodec::Dictionary) => WireFormat::IsEnabled(true), + Some(codec) => WireFormat::EnabledWithOptions { codec: *codec }, + }; + wire_format.serialize(serializer) + } + + pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> + where D: Deserializer<'de> { + let fast_codec = match WireFormat::deserialize(deserializer)? { + WireFormat::IsEnabled(false) => None, + WireFormat::IsEnabled(true) => Some(StrColumnCodec::Dictionary), + WireFormat::EnabledWithOptions { codec } => Some(codec), + }; + Ok(fast_codec) + } +} + /// For backward compatibility we add an intermediary to interpret the /// lack of fieldnorms attribute as "true" if and only if indexed. /// @@ -23,7 +71,8 @@ struct BytesOptionsDeser { indexed: bool, #[serde(default)] fieldnorms: Option, - fast: bool, + #[serde(with = "fast_field_bytes_options_serde")] + fast: Option, stored: bool, } @@ -54,6 +103,12 @@ impl BytesOptions { /// Returns true if the value is a fast field. #[inline] pub fn is_fast(&self) -> bool { + self.fast.is_some() + } + + /// Returns the codec of the fast field, or `None` if the field is not a fast field. + #[inline] + pub fn get_fast_field_codec(&self) -> Option { self.fast } @@ -86,9 +141,24 @@ impl BytesOptions { /// Set the field as a fast field. /// /// Fast fields are designed for random access. + /// + /// Keeps the codec if one was already set, with the dictionary codec as default. #[must_use] pub fn set_fast(mut self) -> BytesOptions { - self.fast = true; + self.fast.get_or_insert(StrColumnCodec::Dictionary); + self + } + + /// Sets the codec of the fast field. The default is [`StrColumnCodec::Dictionary`]. + /// + /// The field also becomes a fast field. + /// + /// The plain codec stores the values without term ordinals. It is better suited to fields + /// with a high cardinality. Merging segments with plain columns is not supported yet: it + /// returns an error. + #[must_use] + pub fn set_fast_codec(mut self, codec: StrColumnCodec) -> BytesOptions { + self.fast = Some(codec); self } @@ -112,7 +182,12 @@ impl> BitOr for BytesOptions { indexed: self.indexed | other.indexed, fieldnorms: self.fieldnorms | other.fieldnorms, stored: self.stored | other.stored, - fast: self.fast | other.fast, + fast: match (self.fast, other.fast) { + (Some(left_codec), Some(right_codec)) => { + Some(merge_str_column_codecs(left_codec, right_codec)) + } + (left_codec_opt, right_codec_opt) => left_codec_opt.or(right_codec_opt), + }, } } } @@ -129,7 +204,7 @@ impl From for BytesOptions { indexed: false, fieldnorms: false, stored: false, - fast: true, + fast: Some(StrColumnCodec::Dictionary), } } } @@ -140,7 +215,7 @@ impl From for BytesOptions { indexed: false, fieldnorms: false, stored: true, - fast: false, + fast: None, } } } @@ -151,7 +226,7 @@ impl From for BytesOptions { indexed: true, fieldnorms: true, stored: false, - fast: false, + fast: None, } } } @@ -169,6 +244,8 @@ where #[cfg(test)] mod tests { + use columnar::StrColumnCodec; + use crate::schema::{BytesOptions, FAST, INDEXED, STORED}; #[test] @@ -227,7 +304,7 @@ mod tests { &BytesOptions { indexed: true, fieldnorms: true, - fast: false, + fast: None, stored: false } ); @@ -246,7 +323,7 @@ mod tests { &BytesOptions { indexed: false, fieldnorms: false, - fast: false, + fast: None, stored: false } ); @@ -266,7 +343,7 @@ mod tests { &BytesOptions { indexed: true, fieldnorms: false, - fast: false, + fast: None, stored: false } ); @@ -287,9 +364,54 @@ mod tests { &BytesOptions { indexed: false, fieldnorms: true, - fast: false, + fast: None, stored: false } ); } + + #[test] + fn test_bytes_options_fast_codec_serde() { + let bytes_options = BytesOptions::default().set_fast_codec(StrColumnCodec::Plain); + assert!(bytes_options.is_fast()); + assert_eq!( + bytes_options.get_fast_field_codec(), + Some(StrColumnCodec::Plain) + ); + let serialized = serde_json::to_value(&bytes_options).unwrap(); + assert_eq!( + serialized, + serde_json::json!({ + "indexed": false, + "fieldnorms": false, + "fast": { "codec": "plain" }, + "stored": false + }) + ); + let deserialized: BytesOptions = serde_json::from_value(serialized).unwrap(); + assert_eq!(deserialized, bytes_options); + + // The dictionary codec is serialized as `true`. + let serialized = serde_json::to_value(BytesOptions::default().set_fast()).unwrap(); + assert_eq!(serialized["fast"], serde_json::json!(true)); + let deserialized: BytesOptions = serde_json::from_value(serialized).unwrap(); + assert_eq!( + deserialized.get_fast_field_codec(), + Some(StrColumnCodec::Dictionary) + ); + assert_eq!(BytesOptions::default().get_fast_field_codec(), None); + } + + #[test] + fn test_bytes_options_fast_codec_composition() { + let plain_options = BytesOptions::default().set_fast_codec(StrColumnCodec::Plain); + assert_eq!( + (plain_options.clone() | STORED).get_fast_field_codec(), + Some(StrColumnCodec::Plain) + ); + assert_eq!( + (BytesOptions::from(STORED) | plain_options).get_fast_field_codec(), + Some(StrColumnCodec::Plain) + ); + } } diff --git a/src/schema/json_object_options.rs b/src/schema/json_object_options.rs index ae02a2b6d..10a94d2cd 100644 --- a/src/schema/json_object_options.rs +++ b/src/schema/json_object_options.rs @@ -78,6 +78,14 @@ impl JsonObjectOptions { .and_then(|fast_field_options| fast_field_options.tokenizer.as_deref()) } + /// Returns the codec of the fast field, or `None` if the field is not a fast field. + /// + /// Only the dictionary codec is supported for JSON fields. + #[inline] + pub(crate) fn get_fast_field_codec(&self) -> Option { + Some(self.fast.as_ref()?.codec) + } + /// Returns `true` iff dots in json keys should be expanded. /// /// When expand_dots is enabled, json object like @@ -139,8 +147,8 @@ impl JsonObjectOptions { /// from the dictionary. #[must_use] pub fn set_fast(mut self, tokenizer_name: impl ToString) -> Self { - let tokenizer = Some(tokenizer_name.to_string()); - self.fast = Some(FastFieldTextOptions { tokenizer }); + let fast_options = self.fast.get_or_insert_with(FastFieldTextOptions::default); + fast_options.tokenizer = Some(tokenizer_name.to_string()); self } @@ -149,7 +157,8 @@ impl JsonObjectOptions { /// Text values are recorded as is. This is the same as the `FAST` flag. #[must_use] pub fn set_fast_no_tokenizer(mut self) -> Self { - self.fast = Some(FastFieldTextOptions { tokenizer: None }); + let fast_options = self.fast.get_or_insert_with(FastFieldTextOptions::default); + fast_options.tokenizer = None; self } diff --git a/src/schema/text_options.rs b/src/schema/text_options.rs index 2b51c3fed..bb408c5ed 100644 --- a/src/schema/text_options.rs +++ b/src/schema/text_options.rs @@ -1,6 +1,7 @@ use std::borrow::Cow; use std::ops::BitOr; +use columnar::StrColumnCodec; use serde::{Deserialize, Serialize}; use super::flags::{CoerceFlag, FastFlag}; @@ -35,30 +36,63 @@ pub(crate) struct FastFieldTextOptions { /// `Some("raw")`: the analyzer registered under the raw name may have extra filters, such as /// a token length limit. pub tokenizer: Option, + /// Codec of the column storing the values. + pub codec: StrColumnCodec, } pub(super) fn merge_fast_field_options( left: Option, right: Option, ) -> Option { + let (left, right) = match (left, right) { + (None, right) => return right, + (left, None) => return left, + (Some(left), Some(right)) => (left, right), + }; // A configured tokenizer takes precedence over recording values as is. - match (left, right) { - (Some(left), Some(right)) if left.tokenizer.is_none() => Some(right), - (Some(left), _) => Some(left), - (None, right) => right, + Some(FastFieldTextOptions { + tokenizer: left.tokenizer.or(right.tokenizer), + codec: merge_str_column_codecs(left.codec, right.codec), + }) +} + +/// Returns the codec of two combined fast field options: the plain codec takes precedence over +/// the default dictionary codec. +pub(super) fn merge_str_column_codecs( + left: StrColumnCodec, + right: StrColumnCodec, +) -> StrColumnCodec { + if left == StrColumnCodec::Plain || right == StrColumnCodec::Plain { + StrColumnCodec::Plain + } else { + StrColumnCodec::Dictionary } } +/// Wire format of the fast field options of text and JSON fields: +/// - `false`: not a fast field. +/// - `true`: a fast field without tokenizer, with the dictionary codec. +/// - `{"with_tokenizer": "..", "codec": "plain"}`: both keys are optional. pub(super) mod fast_field_text_options_serde { + use columnar::StrColumnCodec; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use super::FastFieldTextOptions; + fn is_dictionary(codec: &StrColumnCodec) -> bool { + *codec == StrColumnCodec::Dictionary + } + #[derive(Serialize, Deserialize)] #[serde(untagged)] enum WireFormat { IsEnabled(bool), - EnabledWithTokenizer { with_tokenizer: String }, + EnabledWithOptions { + #[serde(default, skip_serializing_if = "Option::is_none")] + with_tokenizer: Option, + #[serde(default, skip_serializing_if = "is_dictionary")] + codec: StrColumnCodec, + }, } pub fn serialize( @@ -70,11 +104,13 @@ pub(super) mod fast_field_text_options_serde { { let wire_format = match fast_field_options { None => WireFormat::IsEnabled(false), - Some(FastFieldTextOptions { tokenizer: None }) => WireFormat::IsEnabled(true), Some(FastFieldTextOptions { - tokenizer: Some(tokenizer_name), - }) => WireFormat::EnabledWithTokenizer { - with_tokenizer: tokenizer_name.clone(), + tokenizer: None, + codec: StrColumnCodec::Dictionary, + }) => WireFormat::IsEnabled(true), + Some(FastFieldTextOptions { tokenizer, codec }) => WireFormat::EnabledWithOptions { + with_tokenizer: tokenizer.clone(), + codec: *codec, }, }; wire_format.serialize(serializer) @@ -86,8 +122,12 @@ pub(super) mod fast_field_text_options_serde { match wire_format { WireFormat::IsEnabled(false) => Ok(None), WireFormat::IsEnabled(true) => Ok(Some(FastFieldTextOptions::default())), - WireFormat::EnabledWithTokenizer { with_tokenizer } => Ok(Some(FastFieldTextOptions { - tokenizer: Some(with_tokenizer), + WireFormat::EnabledWithOptions { + with_tokenizer, + codec, + } => Ok(Some(FastFieldTextOptions { + tokenizer: with_tokenizer, + codec, })), } } @@ -125,6 +165,12 @@ impl TextOptions { self.fast.as_ref()?.tokenizer.as_deref() } + /// Returns the codec of the fast field, or `None` if the field is not a fast field. + #[inline] + pub fn get_fast_field_codec(&self) -> Option { + Some(self.fast.as_ref()?.codec) + } + /// Returns true if values should be coerced to strings (numbers, null). #[inline] pub fn should_coerce(&self) -> bool { @@ -151,8 +197,8 @@ impl TextOptions { /// from the dictionary. #[must_use] pub fn set_fast(mut self, tokenizer_name: impl ToString) -> TextOptions { - let tokenizer = Some(tokenizer_name.to_string()); - self.fast = Some(FastFieldTextOptions { tokenizer }); + let fast_options = self.fast.get_or_insert_with(FastFieldTextOptions::default); + fast_options.tokenizer = Some(tokenizer_name.to_string()); self } @@ -161,7 +207,23 @@ impl TextOptions { /// Values are recorded as is. This is the same as the `FAST` flag. #[must_use] pub fn set_fast_no_tokenizer(mut self) -> TextOptions { - self.fast = Some(FastFieldTextOptions { tokenizer: None }); + let fast_options = self.fast.get_or_insert_with(FastFieldTextOptions::default); + fast_options.tokenizer = None; + self + } + + /// Sets the codec of the fast field. The default is [`StrColumnCodec::Dictionary`]. + /// + /// If the field is not a fast field yet, it becomes a fast field without tokenizer. The + /// tokenizer and the codec can be set in any order. + /// + /// The plain codec stores the values without term ordinals. It is better suited to fields + /// with a high cardinality. Merging segments with plain columns is not supported yet: it + /// returns an error. + #[must_use] + pub fn set_fast_codec(mut self, codec: StrColumnCodec) -> TextOptions { + let fast_options = self.fast.get_or_insert_with(FastFieldTextOptions::default); + fast_options.codec = codec; self } @@ -356,6 +418,8 @@ where #[cfg(test)] mod tests { + use columnar::StrColumnCodec; + use crate::schema::text_options::FastFieldTextOptions; use crate::schema::*; @@ -432,7 +496,8 @@ mod tests { assert_eq!( options.fast, Some(FastFieldTextOptions { - tokenizer: Some("default".to_string()) + tokenizer: Some("default".to_string()), + codec: StrColumnCodec::Dictionary, }) ); let serialized = serde_json::to_value(&options).unwrap(); @@ -444,7 +509,8 @@ mod tests { assert_eq!( options.fast, Some(FastFieldTextOptions { - tokenizer: Some("default".to_string()) + tokenizer: Some("default".to_string()), + codec: StrColumnCodec::Dictionary, }) ); @@ -452,11 +518,23 @@ mod tests { "fast": true } "#; let options: TextOptions = serde_json::from_str(json).unwrap(); - assert_eq!(options.fast, Some(FastFieldTextOptions { tokenizer: None })); + assert_eq!( + options.fast, + Some(FastFieldTextOptions { + tokenizer: None, + codec: StrColumnCodec::Dictionary, + }) + ); let serialized = serde_json::to_value(&options).unwrap(); assert_eq!(serialized["fast"], serde_json::json!(true)); let options: TextOptions = serde_json::from_value(serialized).unwrap(); - assert_eq!(options.fast, Some(FastFieldTextOptions { tokenizer: None })); + assert_eq!( + options.fast, + Some(FastFieldTextOptions { + tokenizer: None, + codec: StrColumnCodec::Dictionary, + }) + ); let json = r#" { "fast": false @@ -496,4 +574,56 @@ mod tests { let serialized = serde_json::to_value(&options).unwrap(); assert_eq!(serialized["fast"], serde_json::json!(true)); } + + #[test] + fn serde_fast_field_codec() { + let options: TextOptions = + serde_json::from_value(serde_json::json!({ "fast": { "codec": "plain" } })).unwrap(); + assert_eq!(options.get_fast_field_codec(), Some(StrColumnCodec::Plain)); + assert_eq!(options.get_fast_field_tokenizer_name(), None); + let serialized = serde_json::to_value(&options).unwrap(); + assert_eq!(serialized["fast"], serde_json::json!({ "codec": "plain" })); + + let options = TextOptions::default() + .set_fast_codec(StrColumnCodec::Plain) + .set_fast("raw"); + let serialized = serde_json::to_value(&options).unwrap(); + assert_eq!( + serialized["fast"], + serde_json::json!({ "with_tokenizer": "raw", "codec": "plain" }) + ); + let deserialized: TextOptions = serde_json::from_value(serialized).unwrap(); + assert_eq!(deserialized, options); + + // The dictionary codec is the default, and is not serialized. + let options = TextOptions::default().set_fast_codec(StrColumnCodec::Dictionary); + assert_eq!(options, FAST.into()); + assert_eq!( + serde_json::to_value(&options).unwrap()["fast"], + serde_json::json!(true) + ); + let options: TextOptions = serde_json::from_value( + serde_json::json!({ "fast": { "with_tokenizer": "raw", "codec": "dictionary" } }), + ) + .unwrap(); + assert_eq!( + options.get_fast_field_codec(), + Some(StrColumnCodec::Dictionary) + ); + assert_eq!(options.get_fast_field_tokenizer_name(), Some("raw")); + } + + #[test] + fn test_fast_field_codec_composition() { + let plain_options = TextOptions::default().set_fast_codec(StrColumnCodec::Plain); + let tokenized_options = TextOptions::default().set_fast("default"); + for options in [ + plain_options.clone() | tokenized_options.clone(), + tokenized_options | plain_options, + ] { + assert_eq!(options.get_fast_field_codec(), Some(StrColumnCodec::Plain)); + assert_eq!(options.get_fast_field_tokenizer_name(), Some("default")); + } + assert_eq!(TextOptions::default().get_fast_field_codec(), None); + } }