bhaskargurram-ai commented on code in PR #11549: URL: https://github.com/apache/arrow-rs/pull/11549#discussion_r4275903300
########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,377 @@ +// 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::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type}; +use arrow_array::{Array, BooleanArray}; +use arrow_buffer::BooleanBuffer; +use arrow_schema::DataType; + +use crate::arrow::arrow_writer::{coerce_to_fixed_len_byte_array, coerce_to_i32, coerce_to_i64}; +use crate::basic::Type as PhysicalType; +use crate::bloom_filter::Sbbf; +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. +/// +/// ``` +/// # 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 +#[derive(Debug, Clone, Copy)] +pub struct ArrowSbbf<'a> { + sbbf: &'a Sbbf, + physical_type: PhysicalType, +} + +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 { + Self { + sbbf, + physical_type: column.physical_type(), + } + } + + /// 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. + /// + /// Returns an error if [`ArrowWriter`] cannot write `array`'s data type to a + /// column of this physical type. + /// + /// [`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()); + } + + let sbbf = self.sbbf; + let found = match (self.physical_type, array.data_type()) { + (PhysicalType::INT32, _) => coerce_to_i32(array)? + .iter() + .map(|v| sbbf.check(v)) + .collect(), + (PhysicalType::INT64, _) => coerce_to_i64(array)? + .iter() + .map(|v| sbbf.check(v)) + .collect(), + (PhysicalType::FLOAT, DataType::Float32) => array + .as_primitive::<Float32Type>() + .values() + .iter() + .map(|v| sbbf.check(v)) + .collect(), + (PhysicalType::DOUBLE, DataType::Float64) => array + .as_primitive::<Float64Type>() + .values() + .iter() + .map(|v| sbbf.check(v)) + .collect(), + (PhysicalType::BOOLEAN, DataType::Boolean) => array + .as_boolean() + .values() + .iter() + .map(|v| sbbf.check(&v)) + .collect(), + (PhysicalType::BYTE_ARRAY, DataType::Utf8) => { + check_bytes(sbbf, array.as_string::<i32>()) + } + (PhysicalType::BYTE_ARRAY, DataType::LargeUtf8) => { + check_bytes(sbbf, array.as_string::<i64>()) + } + (PhysicalType::BYTE_ARRAY, DataType::Utf8View) => { + check_bytes(sbbf, array.as_string_view()) + } + (PhysicalType::BYTE_ARRAY, DataType::Binary) => { + check_bytes(sbbf, array.as_binary::<i32>()) + } + (PhysicalType::BYTE_ARRAY, DataType::LargeBinary) => { + check_bytes(sbbf, array.as_binary::<i64>()) + } + (PhysicalType::BYTE_ARRAY, DataType::BinaryView) => { + check_bytes(sbbf, array.as_binary_view()) + } + (PhysicalType::FIXED_LEN_BYTE_ARRAY, _) => { + coerce_to_fixed_len_byte_array(array, 0..array.len())? + .iter() + .map(|v| sbbf.check(v)) + .collect() + } Review Comment: Thanks for the repro, that was a real bug. `ArrowSbbf::new` now keeps the column's `type_length` and decimal scale. For a FLBA column, decimals of any precision are converted to big-endian two's complement of exactly `type_length` bytes: sign-extended when the native type is narrower, and with the leading bytes dropped when it is wider. If those dropped bytes aren't pure sign extension, the value can't be in the column, so it comes back as definitely absent. Your case (written at precision 30, checked at 20/30/38) is now a test, together with Decimal32/64/256 and an out-of-range value whose low 13 bytes equal 12345. I also added a check on scale: a decimal array with a different scale from the column's returns an error (for INT32, INT64 and FLBA decimal columns), and so does checking a decimal array against a non-decimal column. A `FixedSizeBinary` array whose width differs from the column's length returns an error too rather than false, since the writer could never have written it to that column; returning all-false would hide a caller bug like checking the wrong column. Precision differences are converted rather than rejected, since a wider type with the same values is common for predicate literals. INT32/INT64 decimal columns still use the writer's `as` cast, so an out-of-range value there can give a false positive but never a false negative. -- 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]
