sdd commented on code in PR #565:
URL: https://github.com/apache/iceberg-rust/pull/565#discussion_r1746597564


##########
crates/iceberg/src/expr/visitors/page_index_evaluator.rs:
##########
@@ -0,0 +1,1491 @@
+// 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.
+
+//! Evaluates predicates against a Parquet Page Index
+
+use std::collections::HashMap;
+
+use fnv::FnvHashSet;
+use ordered_float::OrderedFloat;
+use parquet::arrow::arrow_reader::{RowSelection, RowSelector};
+use parquet::file::metadata::RowGroupMetaData;
+use parquet::file::page_index::index::Index;
+use parquet::format::PageLocation;
+
+use crate::expr::visitors::bound_predicate_visitor::{visit, 
BoundPredicateVisitor};
+use crate::expr::{BoundPredicate, BoundReference};
+use crate::spec::{Datum, PrimitiveLiteral, PrimitiveType, Schema};
+use crate::{Error, ErrorKind, Result};
+
+type OffsetIndex = Vec<Vec<PageLocation>>;
+
+const IN_PREDICATE_LIMIT: usize = 200;
+
+enum MissingColBehavior {
+    CantMatch,
+    MightMatch,
+}
+
+enum PageNullCount {
+    AllNull,
+    NoneNull,
+    SomeNull,
+    Unknown,
+}
+
+impl PageNullCount {
+    fn from_row_and_null_counts(num_rows: usize, null_count: Option<i64>) -> 
Self {
+        match (num_rows, null_count) {
+            (x, Some(y)) if x == y as usize => PageNullCount::AllNull,
+            (_, Some(0)) => PageNullCount::NoneNull,
+            (_, Some(_)) => PageNullCount::SomeNull,
+            _ => PageNullCount::Unknown,
+        }
+    }
+}
+
+pub(crate) struct PageIndexEvaluator<'a> {
+    column_index: &'a [Index],
+    offset_index: &'a OffsetIndex,
+    row_group_metadata: &'a RowGroupMetaData,
+    iceberg_field_id_to_parquet_column_index: &'a HashMap<i32, usize>,
+    snapshot_schema: &'a Schema,
+}
+
+impl<'a> PageIndexEvaluator<'a> {
+    pub(crate) fn new(
+        column_index: &'a [Index],
+        offset_index: &'a OffsetIndex,
+        row_group_metadata: &'a RowGroupMetaData,
+        field_id_map: &'a HashMap<i32, usize>,
+        snapshot_schema: &'a Schema,
+    ) -> Self {
+        Self {
+            column_index,
+            offset_index,
+            row_group_metadata,
+            iceberg_field_id_to_parquet_column_index: field_id_map,
+            snapshot_schema,
+        }
+    }
+
+    /// Evaluate this `PageIndexEvaluator`'s filter predicate against a
+    /// specific page's column index entry in a parquet file's page index.
+    /// [`ArrowReader`] uses the resulting [`RowSelection`] to reject
+    /// pages within a parquet file's row group that cannot contain rows
+    /// matching the filter predicate.
+    pub(crate) fn eval(
+        filter: &'a BoundPredicate,
+        column_index: &'a [Index],
+        offset_index: &'a OffsetIndex,
+        row_group_metadata: &'a RowGroupMetaData,
+        field_id_map: &'a HashMap<i32, usize>,
+        snapshot_schema: &'a Schema,
+    ) -> Result<Vec<RowSelector>> {
+        if row_group_metadata.num_rows() == 0 {
+            return Ok(vec![]);
+        }
+
+        let mut evaluator = Self::new(
+            column_index,
+            offset_index,
+            row_group_metadata,
+            field_id_map,
+            snapshot_schema,
+        );
+
+        Ok(visit(&mut evaluator, filter)?.iter().copied().collect())
+    }
+
+    fn select_all_rows(&self) -> Result<RowSelection> {
+        Ok(vec![RowSelector::select(
+            self.row_group_metadata.num_rows() as usize
+        )]
+        .into())
+    }
+
+    fn skip_all_rows(&self) -> Result<RowSelection> {
+        Ok(vec![].into())

Review Comment:
   Good spot - fixed. I think the original would work but your suggestion looks 
more intuitive to anyone reading the code.



##########
crates/iceberg/src/expr/visitors/page_index_evaluator.rs:
##########
@@ -0,0 +1,1491 @@
+// 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.
+
+//! Evaluates predicates against a Parquet Page Index
+
+use std::collections::HashMap;
+
+use fnv::FnvHashSet;
+use ordered_float::OrderedFloat;
+use parquet::arrow::arrow_reader::{RowSelection, RowSelector};
+use parquet::file::metadata::RowGroupMetaData;
+use parquet::file::page_index::index::Index;
+use parquet::format::PageLocation;
+
+use crate::expr::visitors::bound_predicate_visitor::{visit, 
BoundPredicateVisitor};
+use crate::expr::{BoundPredicate, BoundReference};
+use crate::spec::{Datum, PrimitiveLiteral, PrimitiveType, Schema};
+use crate::{Error, ErrorKind, Result};
+
+type OffsetIndex = Vec<Vec<PageLocation>>;
+
+const IN_PREDICATE_LIMIT: usize = 200;
+
+enum MissingColBehavior {
+    CantMatch,
+    MightMatch,
+}
+
+enum PageNullCount {
+    AllNull,
+    NoneNull,
+    SomeNull,
+    Unknown,
+}
+
+impl PageNullCount {
+    fn from_row_and_null_counts(num_rows: usize, null_count: Option<i64>) -> 
Self {
+        match (num_rows, null_count) {
+            (x, Some(y)) if x == y as usize => PageNullCount::AllNull,
+            (_, Some(0)) => PageNullCount::NoneNull,
+            (_, Some(_)) => PageNullCount::SomeNull,
+            _ => PageNullCount::Unknown,
+        }
+    }
+}
+
+pub(crate) struct PageIndexEvaluator<'a> {
+    column_index: &'a [Index],
+    offset_index: &'a OffsetIndex,
+    row_group_metadata: &'a RowGroupMetaData,
+    iceberg_field_id_to_parquet_column_index: &'a HashMap<i32, usize>,
+    snapshot_schema: &'a Schema,
+}
+
+impl<'a> PageIndexEvaluator<'a> {
+    pub(crate) fn new(
+        column_index: &'a [Index],
+        offset_index: &'a OffsetIndex,
+        row_group_metadata: &'a RowGroupMetaData,
+        field_id_map: &'a HashMap<i32, usize>,
+        snapshot_schema: &'a Schema,
+    ) -> Self {
+        Self {
+            column_index,
+            offset_index,
+            row_group_metadata,
+            iceberg_field_id_to_parquet_column_index: field_id_map,
+            snapshot_schema,
+        }
+    }
+
+    /// Evaluate this `PageIndexEvaluator`'s filter predicate against a
+    /// specific page's column index entry in a parquet file's page index.
+    /// [`ArrowReader`] uses the resulting [`RowSelection`] to reject
+    /// pages within a parquet file's row group that cannot contain rows
+    /// matching the filter predicate.
+    pub(crate) fn eval(
+        filter: &'a BoundPredicate,
+        column_index: &'a [Index],
+        offset_index: &'a OffsetIndex,
+        row_group_metadata: &'a RowGroupMetaData,
+        field_id_map: &'a HashMap<i32, usize>,
+        snapshot_schema: &'a Schema,
+    ) -> Result<Vec<RowSelector>> {
+        if row_group_metadata.num_rows() == 0 {
+            return Ok(vec![]);
+        }
+
+        let mut evaluator = Self::new(
+            column_index,
+            offset_index,
+            row_group_metadata,
+            field_id_map,
+            snapshot_schema,
+        );
+
+        Ok(visit(&mut evaluator, filter)?.iter().copied().collect())
+    }
+
+    fn select_all_rows(&self) -> Result<RowSelection> {
+        Ok(vec![RowSelector::select(
+            self.row_group_metadata.num_rows() as usize
+        )]
+        .into())
+    }
+
+    fn skip_all_rows(&self) -> Result<RowSelection> {
+        Ok(vec![].into())
+    }
+
+    fn calc_row_selection<F>(
+        &self,
+        field_id: i32,
+        predicate: F,
+        missing_col_behavior: MissingColBehavior,
+    ) -> Result<RowSelection>
+    where
+        F: Fn(Option<Datum>, Option<Datum>, PageNullCount) -> Result<bool>,
+    {
+        let Some(&parquet_column_index) =
+            self.iceberg_field_id_to_parquet_column_index.get(&field_id)
+        else {
+            // if the snapshot's column is not present in the row group,
+            // exit early
+            return match missing_col_behavior {
+                MissingColBehavior::CantMatch => self.skip_all_rows(),
+                MissingColBehavior::MightMatch => self.select_all_rows(),
+            };
+        };
+
+        let Some(field) = self.snapshot_schema.field_by_id(field_id) else {
+            return Err(Error::new(
+                ErrorKind::Unexpected,
+                format!("Field with id {} missing from snapshot schema", 
field_id),
+            ));
+        };
+
+        let Some(field_type) = field.field_type.as_primitive_type() else {
+            return Err(Error::new(
+                ErrorKind::Unexpected,
+                format!(
+                    "Field with id {} not convertible to primitive type",
+                    field_id
+                ),
+            ));
+        };
+
+        let Some(column_index) = self.column_index.get(parquet_column_index) 
else {
+            // This should not happen, but we fail soft anyway so that the 
scan is still
+            // successful, just a bit slower
+            return self.select_all_rows();
+        };
+
+        let Some(offset_index) = self.offset_index.get(parquet_column_index) 
else {
+            // if we have a column index, we should always have an offset 
index.
+            return Err(Error::new(
+                ErrorKind::Unexpected,
+                format!("Missing offset index for field id {}", field_id),
+            ));
+        };
+
+        let row_counts = self.calc_row_counts(offset_index);
+
+        let Some(page_filter) = Self::apply_predicate_to_column_index(
+            predicate,
+            field_type,
+            column_index,
+            &row_counts,
+        )?
+        else {
+            return self.select_all_rows();
+        };
+
+        let row_selectors: Vec<_> = row_counts
+            .iter()
+            .zip(page_filter.iter())
+            .map(|(&row_count, &is_selected)| {
+                if is_selected {
+                    RowSelector::select(row_count)
+                } else {
+                    RowSelector::skip(row_count)
+                }
+            })
+            .collect();
+
+        Ok(row_selectors.into())
+    }
+
+    fn calc_row_counts(&self, offset_index: &[PageLocation]) -> Vec<usize> {
+        let mut remaining_rows = self.row_group_metadata.num_rows() as usize;
+
+        let mut row_counts = Vec::with_capacity(self.column_index.len());

Review Comment:
   Thanks - `column_index` and `offset_index` should be the same length anyway 
but your suggestion makes this more consistent.



-- 
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: issues-unsubscr...@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org
For additional commands, e-mail: issues-h...@iceberg.apache.org

Reply via email to