alamb commented on code in PR #11549: URL: https://github.com/apache/arrow-rs/pull/11549#discussion_r4431591924
########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,1167 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Check Arrow arrays against Parquet bloom filters + +use arrow_array::builder::BooleanBuilder; +use arrow_array::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type, RunEndIndexType}; +use arrow_array::{Array, BooleanArray, RunArray, downcast_run_array}; +use arrow_buffer::{ArrowNativeType, BooleanBuffer}; +use arrow_schema::DataType; + +use crate::arrow::arrow_writer::{ + FixedLenByteArrayVisitor, PrimitiveVisitor, visit_fixed_len_byte_array, visit_i32, visit_i64, +}; +use crate::basic::{ConvertedType, LogicalType, Type as PhysicalType}; +use crate::bloom_filter::Sbbf; +use crate::data_type::AsBytes; +use crate::errors::{ParquetError, Result}; +use crate::schema::types::ColumnDescriptor; + +/// A Parquet bloom filter ([`Sbbf`]) that can be checked with Arrow arrays +/// +/// [`ArrowWriter`] converts some Arrow types to a different Parquet physical +/// type before writing them, for example `Int8` and `UInt16` are stored as +/// `INT32`, and the bloom filter is built from the converted values. Checking +/// such a filter with [`Sbbf::check`] and the original Arrow value hashes +/// different bytes, and so reports values that are present as absent. +/// +/// [`ArrowSbbf::check`] applies the same conversion as [`ArrowWriter`] +/// before checking the filter. +/// +/// These are the Arrow types whose values [`ArrowWriter`] stores differently: +/// +/// | Arrow type | Parquet physical type | Stored value | +/// |---|---|---| +/// | `Int8`, `Int16` | `INT32` | Sign-extended | +/// | `UInt8`, `UInt16` | `INT32` | Zero-extended | +/// | `UInt32` | `INT32` | Same bits, so values above `i32::MAX` are negative | +/// | `UInt64` | `INT64` | Same bits, so values above `i64::MAX` are negative | +/// | `Date64` | `INT32` with [`coerce_types`], otherwise `INT64` | With [`coerce_types`], days rounded towards zero; otherwise milliseconds | +/// | `Decimal32` to `Decimal256` of precision 1 to 9 | `INT32` | Unscaled value, with wider types truncated to 32 bits | +/// | `Decimal64` to `Decimal256` of precision 10 to 18 | `INT64` | Unscaled value, with wider types truncated to 64 bits | +/// | `Decimal128`, `Decimal256` of precision 19 or more | `FIXED_LEN_BYTE_ARRAY` | Unscaled value as big-endian two's complement, truncated to the length for the precision | +/// | `Float16` | `FIXED_LEN_BYTE_ARRAY` of length 2 | Little-endian bytes | +/// | `Interval(YearMonth)`, `Interval(DayTime)` | `FIXED_LEN_BYTE_ARRAY` of length 12 | Months, days and milliseconds as little-endian 32-bit integers; the fields the Arrow type does not have are zero | +/// +/// Other types are stored as they are. A dictionary or run-end encoded array is +/// stored as its values. +/// +/// ``` +/// # use std::sync::Arc; +/// # use bytes::Bytes; +/// # use arrow_array::{ArrayRef, Int8Array, RecordBatch}; +/// # use parquet::arrow::ArrowWriter; +/// # use parquet::arrow::bloom_filter::ArrowSbbf; +/// # use parquet::file::properties::{ReaderProperties, WriterProperties}; +/// # use parquet::file::reader::{FileReader, SerializedFileReader}; +/// # use parquet::file::serialized_reader::ReadOptionsBuilder; +/// let array: ArrayRef = Arc::new(Int8Array::from(vec![1, 2, 3])); +/// let batch = RecordBatch::try_from_iter([("c", array)]).unwrap(); +/// +/// let props = WriterProperties::builder() +/// .set_bloom_filter_enabled(true) +/// .build(); +/// let mut buffer = Vec::new(); +/// let mut writer = ArrowWriter::try_new(&mut buffer, batch.schema(), Some(props)).unwrap(); +/// writer.write(&batch).unwrap(); +/// writer.close().unwrap(); +/// +/// let options = ReadOptionsBuilder::new() +/// .with_reader_properties( +/// ReaderProperties::builder() +/// .set_read_bloom_filter(true) +/// .build(), +/// ) +/// .build(); +/// let reader = SerializedFileReader::new_with_options(Bytes::from(buffer), options).unwrap(); +/// let row_group = reader.get_row_group(0).unwrap(); +/// let sbbf = row_group.get_column_bloom_filter(0).unwrap(); +/// let column = reader.metadata().row_group(0).column(0).column_descr(); +/// +/// // Checking the Arrow value directly hashes a single byte, not the INT32 that was written +/// assert!(!sbbf.check(&1_i8)); +/// +/// let found = ArrowSbbf::new(sbbf, column) +/// .check(&Int8Array::from(vec![1, 3, 4])) +/// .unwrap(); +/// assert!(found.value(0)); +/// assert!(found.value(1)); +/// assert!(!found.value(2)); +/// ``` +/// +/// [`ArrowWriter`]: crate::arrow::ArrowWriter +/// [`coerce_types`]: crate::file::properties::WriterPropertiesBuilder::set_coerce_types +#[derive(Debug, Clone, Copy)] +pub struct ArrowSbbf<'a> { Review Comment: I am surprised that this structure doesn't also have the Arrow type For example the array reader does it like this https://github.com/apache/arrow-rs/blob/70d8190350ffb2fd3a34c92d8844d505eaf0af75/parquet/src/arrow/array_reader/primitive_array.rs#L119-L125 And then does the validation for compatible physical type once rather than on each input array ########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,1167 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Check Arrow arrays against Parquet bloom filters + +use arrow_array::builder::BooleanBuilder; +use arrow_array::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type, RunEndIndexType}; +use arrow_array::{Array, BooleanArray, RunArray, downcast_run_array}; +use arrow_buffer::{ArrowNativeType, BooleanBuffer}; +use arrow_schema::DataType; + +use crate::arrow::arrow_writer::{ + FixedLenByteArrayVisitor, PrimitiveVisitor, visit_fixed_len_byte_array, visit_i32, visit_i64, +}; +use crate::basic::{ConvertedType, LogicalType, Type as PhysicalType}; +use crate::bloom_filter::Sbbf; +use crate::data_type::AsBytes; +use crate::errors::{ParquetError, Result}; +use crate::schema::types::ColumnDescriptor; + +/// A Parquet bloom filter ([`Sbbf`]) that can be checked with Arrow arrays +/// +/// [`ArrowWriter`] converts some Arrow types to a different Parquet physical +/// type before writing them, for example `Int8` and `UInt16` are stored as +/// `INT32`, and the bloom filter is built from the converted values. Checking +/// such a filter with [`Sbbf::check`] and the original Arrow value hashes +/// different bytes, and so reports values that are present as absent. +/// +/// [`ArrowSbbf::check`] applies the same conversion as [`ArrowWriter`] +/// before checking the filter. +/// +/// These are the Arrow types whose values [`ArrowWriter`] stores differently: Review Comment: This is a bit of an implementation detail that I think can be removed from these comments. The whole point of this API is so that users don't have to worry about the details of parquet -> arrow conversion ########## parquet/src/arrow/arrow_writer/mod.rs: ########## @@ -1752,66 +1598,359 @@ fn write_leaf( ColumnWriter::ByteArrayColumnWriter(_) => { unreachable!("should use ByteArrayWriter") } - ColumnWriter::FixedLenByteArrayColumnWriter(typed) => { - let bytes = match column.data_type() { - ArrowDataType::Interval(interval_unit) => match interval_unit { - IntervalUnit::YearMonth => { - let array = column.as_primitive::<IntervalYearMonthType>(); - get_interval_ym_array_slice(array, indices.iter().copied()) - } - IntervalUnit::DayTime => { - let array = column.as_primitive::<IntervalDayTimeType>(); - get_interval_dt_array_slice(array, indices.iter().copied()) - } - IntervalUnit::MonthDayNano => { - return Err(ParquetError::NYI(format!( - "Attempting to write an Arrow interval type {interval_unit:?} to parquet that is not yet implemented" - ))); - } - }, - ArrowDataType::FixedSizeBinary(_) => { - let array = column.as_fixed_size_binary(); - get_fsb_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal32(_, _) => { - let array = column.as_primitive::<Decimal32Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal64(_, _) => { - let array = column.as_primitive::<Decimal64Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal128(_, _) => { - let array = column.as_primitive::<Decimal128Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal256(_, _) => { - let array = column.as_primitive::<Decimal256Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Float16 => { - let array = column.as_primitive::<Float16Type>(); - get_float_16_array_slice(array, indices.iter().copied()) - } - _ => { - return Err(ParquetError::NYI( - "Attempting to write an Arrow type that is not yet implemented".to_string(), - )); - } + ColumnWriter::FixedLenByteArrayColumnWriter(typed) => visit_fixed_len_byte_array( + column, + WriteFixedLenByteArray { + writer: typed, + levels, + }, + )?, + } +} + +/// Receives the values [`ArrowWriter`] stores for an Arrow array in an `INT32` +/// (`T = i32`) or `INT64` (`T = i64`) column, which are also the values hashed +/// into the column's bloom filter +/// +/// [`visit_i32`] and [`visit_i64`] hold the conversion from each Arrow type, and +/// call [`Self::slice`] when the Arrow values are stored as they are, or +/// [`Self::map`] when each value is converted. This lets the writer borrow the +/// Arrow buffer when no conversion is needed, and lets +/// [`ArrowSbbf`](crate::arrow::bloom_filter::ArrowSbbf) check converted values +/// one at a time without collecting them. +pub(crate) trait PrimitiveVisitor<T> { + type Output; + + /// Receives values that are stored as they are + fn slice(self, values: &[T]) -> Self::Output; + + /// Receives values that are each stored as `convert(value)` + fn map<S: Copy>(self, values: &[S], convert: impl Fn(S) -> T) -> Self::Output; +} + +/// Passes the values [`ArrowWriter`] stores for `column` in an `INT32` column to `visitor` +pub(crate) fn visit_i32<V: PrimitiveVisitor<i32>>( + column: &dyn arrow_array::Array, + visitor: V, +) -> Result<V::Output> { + // Note: this should match the contents of arrow_to_parquet_type + let output = match column.data_type() { + ArrowDataType::Null => visitor.slice(Int32Array::new_null(column.len()).values()), + ArrowDataType::Int8 => { + visitor.map(column.as_primitive::<Int8Type>().values(), |x| x as i32) + } + ArrowDataType::Int16 => { + visitor.map(column.as_primitive::<Int16Type>().values(), |x| x as i32) + } + ArrowDataType::Int32 => visitor.slice(column.as_primitive::<Int32Type>().values()), + ArrowDataType::UInt8 => { + visitor.map(column.as_primitive::<UInt8Type>().values(), |x| x as i32) + } + ArrowDataType::UInt16 => { + visitor.map(column.as_primitive::<UInt16Type>().values(), |x| x as i32) + } + ArrowDataType::UInt32 => { + // follow C++ implementation and use overflow/reinterpret cast from u32 to i32 which will map + // `(i32::MAX as u32)..u32::MAX` to `i32::MIN..0` + let values = column.as_primitive::<UInt32Type>().values(); + visitor.slice(values.inner().typed_data()) + } + ArrowDataType::Date32 => visitor.slice(column.as_primitive::<Date32Type>().values()), + ArrowDataType::Time32(TimeUnit::Second) => { + visitor.slice(column.as_primitive::<Time32SecondType>().values()) + } + ArrowDataType::Time32(TimeUnit::Millisecond) => { + visitor.slice(column.as_primitive::<Time32MillisecondType>().values()) + } + ArrowDataType::Date64 => { + // If the column is a Date64, we truncate it + visitor.map(column.as_primitive::<Date64Type>().values(), |x| { + (x / 86_400_000) as i32 Review Comment: added as `date64_stored_as_days` ########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,1167 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Check Arrow arrays against Parquet bloom filters + +use arrow_array::builder::BooleanBuilder; +use arrow_array::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type, RunEndIndexType}; +use arrow_array::{Array, BooleanArray, RunArray, downcast_run_array}; +use arrow_buffer::{ArrowNativeType, BooleanBuffer}; +use arrow_schema::DataType; + +use crate::arrow::arrow_writer::{ + FixedLenByteArrayVisitor, PrimitiveVisitor, visit_fixed_len_byte_array, visit_i32, visit_i64, +}; +use crate::basic::{ConvertedType, LogicalType, Type as PhysicalType}; +use crate::bloom_filter::Sbbf; +use crate::data_type::AsBytes; +use crate::errors::{ParquetError, Result}; +use crate::schema::types::ColumnDescriptor; + +/// A Parquet bloom filter ([`Sbbf`]) that can be checked with Arrow arrays +/// +/// [`ArrowWriter`] converts some Arrow types to a different Parquet physical +/// type before writing them, for example `Int8` and `UInt16` are stored as +/// `INT32`, and the bloom filter is built from the converted values. Checking +/// such a filter with [`Sbbf::check`] and the original Arrow value hashes +/// different bytes, and so reports values that are present as absent. +/// +/// [`ArrowSbbf::check`] applies the same conversion as [`ArrowWriter`] +/// before checking the filter. +/// +/// These are the Arrow types whose values [`ArrowWriter`] stores differently: +/// +/// | Arrow type | Parquet physical type | Stored value | +/// |---|---|---| +/// | `Int8`, `Int16` | `INT32` | Sign-extended | +/// | `UInt8`, `UInt16` | `INT32` | Zero-extended | +/// | `UInt32` | `INT32` | Same bits, so values above `i32::MAX` are negative | +/// | `UInt64` | `INT64` | Same bits, so values above `i64::MAX` are negative | +/// | `Date64` | `INT32` with [`coerce_types`], otherwise `INT64` | With [`coerce_types`], days rounded towards zero; otherwise milliseconds | +/// | `Decimal32` to `Decimal256` of precision 1 to 9 | `INT32` | Unscaled value, with wider types truncated to 32 bits | +/// | `Decimal64` to `Decimal256` of precision 10 to 18 | `INT64` | Unscaled value, with wider types truncated to 64 bits | +/// | `Decimal128`, `Decimal256` of precision 19 or more | `FIXED_LEN_BYTE_ARRAY` | Unscaled value as big-endian two's complement, truncated to the length for the precision | +/// | `Float16` | `FIXED_LEN_BYTE_ARRAY` of length 2 | Little-endian bytes | +/// | `Interval(YearMonth)`, `Interval(DayTime)` | `FIXED_LEN_BYTE_ARRAY` of length 12 | Months, days and milliseconds as little-endian 32-bit integers; the fields the Arrow type does not have are zero | +/// +/// Other types are stored as they are. A dictionary or run-end encoded array is +/// stored as its values. +/// +/// ``` +/// # use std::sync::Arc; +/// # use bytes::Bytes; +/// # use arrow_array::{ArrayRef, Int8Array, RecordBatch}; +/// # use parquet::arrow::ArrowWriter; +/// # use parquet::arrow::bloom_filter::ArrowSbbf; +/// # use parquet::file::properties::{ReaderProperties, WriterProperties}; +/// # use parquet::file::reader::{FileReader, SerializedFileReader}; +/// # use parquet::file::serialized_reader::ReadOptionsBuilder; +/// let array: ArrayRef = Arc::new(Int8Array::from(vec![1, 2, 3])); +/// let batch = RecordBatch::try_from_iter([("c", array)]).unwrap(); +/// +/// let props = WriterProperties::builder() +/// .set_bloom_filter_enabled(true) +/// .build(); +/// let mut buffer = Vec::new(); +/// let mut writer = ArrowWriter::try_new(&mut buffer, batch.schema(), Some(props)).unwrap(); +/// writer.write(&batch).unwrap(); +/// writer.close().unwrap(); +/// +/// let options = ReadOptionsBuilder::new() +/// .with_reader_properties( +/// ReaderProperties::builder() +/// .set_read_bloom_filter(true) +/// .build(), +/// ) +/// .build(); +/// let reader = SerializedFileReader::new_with_options(Bytes::from(buffer), options).unwrap(); +/// let row_group = reader.get_row_group(0).unwrap(); +/// let sbbf = row_group.get_column_bloom_filter(0).unwrap(); +/// let column = reader.metadata().row_group(0).column(0).column_descr(); +/// +/// // Checking the Arrow value directly hashes a single byte, not the INT32 that was written +/// assert!(!sbbf.check(&1_i8)); +/// +/// let found = ArrowSbbf::new(sbbf, column) +/// .check(&Int8Array::from(vec![1, 3, 4])) +/// .unwrap(); +/// assert!(found.value(0)); +/// assert!(found.value(1)); +/// assert!(!found.value(2)); +/// ``` +/// +/// [`ArrowWriter`]: crate::arrow::ArrowWriter +/// [`coerce_types`]: crate::file::properties::WriterPropertiesBuilder::set_coerce_types +#[derive(Debug, Clone, Copy)] +pub struct ArrowSbbf<'a> { + sbbf: &'a Sbbf, + physical_type: PhysicalType, + /// The length of the column's values if it is a `FIXED_LEN_BYTE_ARRAY` column, + /// otherwise 0 + type_length: usize, Review Comment: including the arrow type would naturally also include the type length and decimal details ########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,1167 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Check Arrow arrays against Parquet bloom filters + +use arrow_array::builder::BooleanBuilder; +use arrow_array::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type, RunEndIndexType}; +use arrow_array::{Array, BooleanArray, RunArray, downcast_run_array}; +use arrow_buffer::{ArrowNativeType, BooleanBuffer}; +use arrow_schema::DataType; + +use crate::arrow::arrow_writer::{ + FixedLenByteArrayVisitor, PrimitiveVisitor, visit_fixed_len_byte_array, visit_i32, visit_i64, +}; +use crate::basic::{ConvertedType, LogicalType, Type as PhysicalType}; +use crate::bloom_filter::Sbbf; +use crate::data_type::AsBytes; +use crate::errors::{ParquetError, Result}; +use crate::schema::types::ColumnDescriptor; + +/// A Parquet bloom filter ([`Sbbf`]) that can be checked with Arrow arrays +/// +/// [`ArrowWriter`] converts some Arrow types to a different Parquet physical +/// type before writing them, for example `Int8` and `UInt16` are stored as +/// `INT32`, and the bloom filter is built from the converted values. Checking +/// such a filter with [`Sbbf::check`] and the original Arrow value hashes +/// different bytes, and so reports values that are present as absent. +/// +/// [`ArrowSbbf::check`] applies the same conversion as [`ArrowWriter`] +/// before checking the filter. +/// +/// These are the Arrow types whose values [`ArrowWriter`] stores differently: +/// +/// | Arrow type | Parquet physical type | Stored value | +/// |---|---|---| +/// | `Int8`, `Int16` | `INT32` | Sign-extended | +/// | `UInt8`, `UInt16` | `INT32` | Zero-extended | +/// | `UInt32` | `INT32` | Same bits, so values above `i32::MAX` are negative | +/// | `UInt64` | `INT64` | Same bits, so values above `i64::MAX` are negative | +/// | `Date64` | `INT32` with [`coerce_types`], otherwise `INT64` | With [`coerce_types`], days rounded towards zero; otherwise milliseconds | +/// | `Decimal32` to `Decimal256` of precision 1 to 9 | `INT32` | Unscaled value, with wider types truncated to 32 bits | +/// | `Decimal64` to `Decimal256` of precision 10 to 18 | `INT64` | Unscaled value, with wider types truncated to 64 bits | +/// | `Decimal128`, `Decimal256` of precision 19 or more | `FIXED_LEN_BYTE_ARRAY` | Unscaled value as big-endian two's complement, truncated to the length for the precision | +/// | `Float16` | `FIXED_LEN_BYTE_ARRAY` of length 2 | Little-endian bytes | +/// | `Interval(YearMonth)`, `Interval(DayTime)` | `FIXED_LEN_BYTE_ARRAY` of length 12 | Months, days and milliseconds as little-endian 32-bit integers; the fields the Arrow type does not have are zero | +/// +/// Other types are stored as they are. A dictionary or run-end encoded array is +/// stored as its values. +/// +/// ``` +/// # use std::sync::Arc; +/// # use bytes::Bytes; +/// # use arrow_array::{ArrayRef, Int8Array, RecordBatch}; +/// # use parquet::arrow::ArrowWriter; +/// # use parquet::arrow::bloom_filter::ArrowSbbf; +/// # use parquet::file::properties::{ReaderProperties, WriterProperties}; +/// # use parquet::file::reader::{FileReader, SerializedFileReader}; +/// # use parquet::file::serialized_reader::ReadOptionsBuilder; +/// let array: ArrayRef = Arc::new(Int8Array::from(vec![1, 2, 3])); +/// let batch = RecordBatch::try_from_iter([("c", array)]).unwrap(); +/// +/// let props = WriterProperties::builder() +/// .set_bloom_filter_enabled(true) +/// .build(); +/// let mut buffer = Vec::new(); +/// let mut writer = ArrowWriter::try_new(&mut buffer, batch.schema(), Some(props)).unwrap(); +/// writer.write(&batch).unwrap(); +/// writer.close().unwrap(); +/// +/// let options = ReadOptionsBuilder::new() +/// .with_reader_properties( +/// ReaderProperties::builder() +/// .set_read_bloom_filter(true) +/// .build(), +/// ) +/// .build(); +/// let reader = SerializedFileReader::new_with_options(Bytes::from(buffer), options).unwrap(); +/// let row_group = reader.get_row_group(0).unwrap(); +/// let sbbf = row_group.get_column_bloom_filter(0).unwrap(); +/// let column = reader.metadata().row_group(0).column(0).column_descr(); +/// +/// // Checking the Arrow value directly hashes a single byte, not the INT32 that was written +/// assert!(!sbbf.check(&1_i8)); +/// +/// let found = ArrowSbbf::new(sbbf, column) +/// .check(&Int8Array::from(vec![1, 3, 4])) +/// .unwrap(); +/// assert!(found.value(0)); +/// assert!(found.value(1)); +/// assert!(!found.value(2)); +/// ``` +/// +/// [`ArrowWriter`]: crate::arrow::ArrowWriter +/// [`coerce_types`]: crate::file::properties::WriterPropertiesBuilder::set_coerce_types +#[derive(Debug, Clone, Copy)] +pub struct ArrowSbbf<'a> { + sbbf: &'a Sbbf, + physical_type: PhysicalType, + /// The length of the column's values if it is a `FIXED_LEN_BYTE_ARRAY` column, + /// otherwise 0 + type_length: usize, + /// The scale of the column's values if it is a decimal column + decimal_scale: Option<i32>, +} + +impl<'a> ArrowSbbf<'a> { + /// Create a new [`ArrowSbbf`] for the bloom filter of the column described by `column` + pub fn new(sbbf: &'a Sbbf, column: &ColumnDescriptor) -> Self { Review Comment: As above, it might be nice to pass in the optional arrow type here, to mirror what the array reader does and reuse the type mapping ########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,1167 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Check Arrow arrays against Parquet bloom filters + +use arrow_array::builder::BooleanBuilder; +use arrow_array::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type, RunEndIndexType}; +use arrow_array::{Array, BooleanArray, RunArray, downcast_run_array}; +use arrow_buffer::{ArrowNativeType, BooleanBuffer}; +use arrow_schema::DataType; + +use crate::arrow::arrow_writer::{ + FixedLenByteArrayVisitor, PrimitiveVisitor, visit_fixed_len_byte_array, visit_i32, visit_i64, +}; +use crate::basic::{ConvertedType, LogicalType, Type as PhysicalType}; +use crate::bloom_filter::Sbbf; +use crate::data_type::AsBytes; +use crate::errors::{ParquetError, Result}; +use crate::schema::types::ColumnDescriptor; + +/// A Parquet bloom filter ([`Sbbf`]) that can be checked with Arrow arrays +/// +/// [`ArrowWriter`] converts some Arrow types to a different Parquet physical +/// type before writing them, for example `Int8` and `UInt16` are stored as +/// `INT32`, and the bloom filter is built from the converted values. Checking +/// such a filter with [`Sbbf::check`] and the original Arrow value hashes +/// different bytes, and so reports values that are present as absent. +/// +/// [`ArrowSbbf::check`] applies the same conversion as [`ArrowWriter`] +/// before checking the filter. +/// +/// These are the Arrow types whose values [`ArrowWriter`] stores differently: +/// +/// | Arrow type | Parquet physical type | Stored value | +/// |---|---|---| +/// | `Int8`, `Int16` | `INT32` | Sign-extended | +/// | `UInt8`, `UInt16` | `INT32` | Zero-extended | +/// | `UInt32` | `INT32` | Same bits, so values above `i32::MAX` are negative | +/// | `UInt64` | `INT64` | Same bits, so values above `i64::MAX` are negative | +/// | `Date64` | `INT32` with [`coerce_types`], otherwise `INT64` | With [`coerce_types`], days rounded towards zero; otherwise milliseconds | +/// | `Decimal32` to `Decimal256` of precision 1 to 9 | `INT32` | Unscaled value, with wider types truncated to 32 bits | +/// | `Decimal64` to `Decimal256` of precision 10 to 18 | `INT64` | Unscaled value, with wider types truncated to 64 bits | +/// | `Decimal128`, `Decimal256` of precision 19 or more | `FIXED_LEN_BYTE_ARRAY` | Unscaled value as big-endian two's complement, truncated to the length for the precision | +/// | `Float16` | `FIXED_LEN_BYTE_ARRAY` of length 2 | Little-endian bytes | +/// | `Interval(YearMonth)`, `Interval(DayTime)` | `FIXED_LEN_BYTE_ARRAY` of length 12 | Months, days and milliseconds as little-endian 32-bit integers; the fields the Arrow type does not have are zero | +/// +/// Other types are stored as they are. A dictionary or run-end encoded array is +/// stored as its values. +/// +/// ``` +/// # use std::sync::Arc; +/// # use bytes::Bytes; +/// # use arrow_array::{ArrayRef, Int8Array, RecordBatch}; +/// # use parquet::arrow::ArrowWriter; +/// # use parquet::arrow::bloom_filter::ArrowSbbf; +/// # use parquet::file::properties::{ReaderProperties, WriterProperties}; +/// # use parquet::file::reader::{FileReader, SerializedFileReader}; +/// # use parquet::file::serialized_reader::ReadOptionsBuilder; +/// let array: ArrayRef = Arc::new(Int8Array::from(vec![1, 2, 3])); +/// let batch = RecordBatch::try_from_iter([("c", array)]).unwrap(); +/// +/// let props = WriterProperties::builder() +/// .set_bloom_filter_enabled(true) +/// .build(); +/// let mut buffer = Vec::new(); +/// let mut writer = ArrowWriter::try_new(&mut buffer, batch.schema(), Some(props)).unwrap(); +/// writer.write(&batch).unwrap(); +/// writer.close().unwrap(); +/// +/// let options = ReadOptionsBuilder::new() +/// .with_reader_properties( +/// ReaderProperties::builder() +/// .set_read_bloom_filter(true) +/// .build(), +/// ) +/// .build(); +/// let reader = SerializedFileReader::new_with_options(Bytes::from(buffer), options).unwrap(); +/// let row_group = reader.get_row_group(0).unwrap(); +/// let sbbf = row_group.get_column_bloom_filter(0).unwrap(); +/// let column = reader.metadata().row_group(0).column(0).column_descr(); +/// +/// // Checking the Arrow value directly hashes a single byte, not the INT32 that was written +/// assert!(!sbbf.check(&1_i8)); +/// +/// let found = ArrowSbbf::new(sbbf, column) +/// .check(&Int8Array::from(vec![1, 3, 4])) +/// .unwrap(); +/// assert!(found.value(0)); +/// assert!(found.value(1)); +/// assert!(!found.value(2)); +/// ``` +/// +/// [`ArrowWriter`]: crate::arrow::ArrowWriter +/// [`coerce_types`]: crate::file::properties::WriterPropertiesBuilder::set_coerce_types +#[derive(Debug, Clone, Copy)] +pub struct ArrowSbbf<'a> { + sbbf: &'a Sbbf, + physical_type: PhysicalType, + /// The length of the column's values if it is a `FIXED_LEN_BYTE_ARRAY` column, + /// otherwise 0 + type_length: usize, + /// The scale of the column's values if it is a decimal column + decimal_scale: Option<i32>, +} + +impl<'a> ArrowSbbf<'a> { + /// Create a new [`ArrowSbbf`] for the bloom filter of the column described by `column` + pub fn new(sbbf: &'a Sbbf, column: &ColumnDescriptor) -> Self { + let decimal_scale = match column.logical_type_ref() { + Some(LogicalType::Decimal(decimal)) => Some(decimal.scale), + _ if column.converted_type() == ConvertedType::DECIMAL => Some(column.type_scale()), + _ => None, + }; + Self { + sbbf, + physical_type: column.physical_type(), + // The schema checks that the length of a FIXED_LEN_BYTE_ARRAY column + // is positive, and other columns have no length + type_length: column.type_length().try_into().unwrap_or(0), + decimal_scale, + } + } + + /// Check each value of `array` against the bloom filter + /// + /// Returns `true` if the value may be present, and `false` if it is + /// definitely absent. Nulls in `array` are null in the result. + /// + /// Decimal values of any precision can be checked against a decimal column + /// of the same scale. They are converted to the column's physical type and, + /// for a `FIXED_LEN_BYTE_ARRAY` column, to the column's length, truncating + /// a value that is too large in the same way as [`ArrowWriter`]. + /// + /// Values of time types (timestamps, times, durations and `Date64`) are + /// checked in the unit of `array`'s data type, which must be the unit the + /// column was written in, as they are not converted between units. For + /// example, a `Timestamp(Millisecond, _)` value of `1_000` is not found by + /// checking the same instant as a `Timestamp(Microsecond, _)` value of + /// `1_000_000`. + /// + /// Returns an error if [`ArrowWriter`] cannot write `array`'s data type to a + /// column of this physical type, if only one of `array` and the column is + /// a decimal or their scales differ, or if `array` is a `FixedSizeBinary` + /// array whose values have a different length than the column's. + /// + /// [`ArrowWriter`]: crate::arrow::ArrowWriter + pub fn check(&self, array: &dyn Array) -> Result<BooleanArray> { + if let Some(dictionary) = array.as_any_dictionary_opt() { + let values = self.check(dictionary.values().as_ref())?; + let found = arrow_select::take::take(&values, dictionary.keys(), None)?; + return Ok(found.as_boolean().clone()); + } + match array.data_type() { + DataType::Null => return Ok(BooleanArray::new_null(array.len())), + DataType::RunEndEncoded(_, _) => { + return downcast_run_array!( + array => self.check_run_array(array), + _ => unreachable!("RunEndEncoded array is not a RunArray"), + ); + } + _ => {} + } + self.validate_decimal(array.data_type())?; Review Comment: this whole function seems to re-derive the Arrow -> Parquet type mapping, which seems like it adds significant unecessary complexity. Is there any way we can reuse the existing conversion? Here are the existing conversions found by my agent Parquet → Arrow - parquet_to_arrow_field(&ColumnDescriptor) -> Result<Field>: https://github.com/apache/arrow-rs/blob/70d8190350ffb2fd3a34c92d8844d505eaf0af75/parquet/src/arrow/schema/mod.rs#L644-L670 - convert_primitive(parquet_type, hint): https://github.com/apache/arrow-rs/blob/70d8190350ffb2fd3a34c92d8844d505eaf0af75/parquet/src/arrow/schema/primitive.rs#L24-L38 - apply_hint, which restores types from the embedded Arrow schema (Date64, Timestamp(Second), decimal widths, intervals, …): https://github.com/apache/arrow-rs/blob/70d8190350ffb2fd3a34c92d8844d505eaf0af75/parquet/src/arrow/schema/primitive.rs#L40-L108 - from_parquet, the type the reader uses when there's no embedded schema (decimals, unsigned integers, Float16, FixedSizeBinary(n), …): https://github.com/apache/arrow-rs/blob/70d8190350ffb2fd3a34c92d8844d505eaf0af75/parquet/src/arrow/schema/primitive.rs#L111 Arrow → Parquet - arrow_to_parquet_type(field, coerce_types) (private): https://github.com/apache/arrow-rs/blob/70d8190350ffb2fd3a34c92d8844d505eaf0af75/parquet/src/arrow/schema/mod.rs#L684 - ArrowSchemaConverter, the public wrapper; convert is at L608: https://github.com/apache/arrow-rs/blob/70d8190350ffb2fd3a34c92d8844d505eaf0af75/parquet/src/arrow/schema/mod.rs#L540 - On docs.rs: https://docs.rs/parquet/latest/parquet/arrow/struct.ArrowSchemaConverter.html -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
