etseidl commented on code in PR #11549:
URL: https://github.com/apache/arrow-rs/pull/11549#discussion_r4408898579


##########
parquet/src/arrow/bloom_filter.rs:
##########
@@ -0,0 +1,1150 @@
+// 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.
+    ///

Review Comment:
   My LLM thought it important to mention here that for time-based types, the 
probe units have to match the stored units. For example, a stored millisecond 
value of `1000` won't match a probe microsecond value of `1_000_000`.



-- 
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]

Reply via email to