rank-p commented on code in PR #27163:
URL: https://github.com/apache/datafusion/pull/27163#discussion_r4742026233


##########
datafusion/datasource-parquet/src/metadata.rs:
##########
@@ -1276,6 +1294,132 @@ fn sorting_columns_to_physical_exprs(
         .collect()
 }
 
+/// Returns how many leading `sorting_columns` are ordered across the whole
+/// file, given that every row group is sorted by all of them.
+///
+/// The row group statistics give the values that sort first and last in each
+/// row group. The file is ordered if the value that sorts last in each row
+/// group is not after the value that sorts first in the next row group. For
+/// `a ASC`:
+///
+/// ```text
+/// row groups [1, 2] [3, 4]: ordered, because 2 <= 3
+/// row groups [1, 4] [2, 3]: not ordered, because 4 > 2
+/// ```
+///
+/// A later column must be ordered only where all earlier columns are equal.
+/// For `a ASC, b ASC`:
+///
+/// ```text
+/// row groups [(1, 8), (1, 9)] [(2, 0), (2, 1)]: ordered by (a, b), because a 
increases
+/// row groups [(1, 8), (1, 9)] [(1, 0), (1, 1)]: ordered by (a) only, because 
a is equal and 9 > 0
+/// ```
+///
+/// A column whose order cannot be proved, for example because it has no
+/// usable statistics, counts as not ordered. Ordering is optional information,
+/// so this never fails the query.
+fn num_columns_ordered_across_row_groups(
+    metadata: &ParquetMetaData,
+    sorting_columns: &[SortingColumn],
+) -> usize {
+    let row_groups = metadata.row_groups();
+    if row_groups.len() < 2 {
+        return sorting_columns.len();
+    }
+    let file_metadata = metadata.file_metadata();
+    let parquet_schema = file_metadata.schema_descr();
+    let Ok(arrow_schema) =
+        parquet_to_arrow_schema(parquet_schema, 
file_metadata.key_value_metadata())
+    else {
+        return 0;
+    };
+    let resolver = LeafResolver::new(parquet_schema, &arrow_schema);
+
+    let mut sort_exprs = vec![];
+    let mut fields = vec![];
+    let mut mins = vec![];
+    let mut maxes = vec![];
+    for (num_ordered, sorting_column) in sorting_columns.iter().enumerate() {
+        let Some((min, max)) =
+            row_group_min_max(row_groups, parquet_schema, &resolver, 
sorting_column)
+        else {
+            return num_ordered;
+        };
+        // `MinMaxStatistics` finds a column by name, so name it by its 
position
+        let name = num_ordered.to_string();
+        sort_exprs.push(PhysicalSortExpr::new(
+            Arc::new(Column::new(&name, num_ordered)),
+            SortOptions::new(sorting_column.descending, 
sorting_column.nulls_first),
+        ));
+        fields.push(Field::new(name, min.data_type().clone(), true));
+        mins.push(min);
+        maxes.push(max);
+
+        let statistics = || {
+            let schema = Arc::new(Schema::new(fields.clone()));
+            let mins = RecordBatch::try_new(Arc::clone(&schema), 
mins.clone()).ok()?;
+            let maxes = RecordBatch::try_new(Arc::clone(&schema), 
maxes.clone()).ok()?;
+            let sort_order = LexOrdering::new(sort_exprs.iter().cloned())?;
+            MinMaxStatistics::new(&sort_order, &schema, mins, maxes).ok()
+        };
+        let Some(statistics) = statistics().filter(|statistics| 
statistics.is_sorted())
+        else {
+            return num_ordered;
+        };
+        // Each row group ends before the next one starts, so the later sorting
+        // columns cannot change the order
+        if (1..row_groups.len()).all(|i| statistics.max(i - 1) < 
statistics.min(i)) {
+            break;
+        }
+    }
+    sorting_columns.len()
+}
+
+/// Returns the min and the max of `sorting_column` in each row group, as two
+/// arrays with one entry per row group. Where a row group has NULLs, the entry
+/// on the side where NULLs sort is NULL. Returns `None` if the statistics do
+/// not provide the values.
+fn row_group_min_max(
+    row_groups: &[RowGroupMetaData],
+    parquet_schema: &SchemaDescriptor,
+    resolver: &LeafResolver,
+    sorting_column: &SortingColumn,
+) -> Option<(ArrayRef, ArrayRef)> {
+    let column_index = usize::try_from(sorting_column.column_idx).ok()?;
+    let name = parquet_schema.columns().get(column_index)?.name();
+    // The statistics must belong to the sorting column
+    if resolver.leaf_index(name) != Some(column_index) {
+        return None;
+    }
+    let converter = resolver
+        .converter(name)
+        .ok()?
+        .with_missing_null_counts_as_zero(false);
+    let mins = converter.row_group_mins(row_groups).ok()?;
+    let maxes = converter.row_group_maxes(row_groups).ok()?;
+    let null_counts = converter.row_group_null_counts(row_groups).ok()?;

Review Comment:
   Yes, this is still incorrect, I'd like to keep it out of this CR though. I 
added a comment



##########
datafusion/datasource-parquet/src/metadata.rs:
##########
@@ -1276,6 +1294,132 @@ fn sorting_columns_to_physical_exprs(
         .collect()
 }
 
+/// Returns how many leading `sorting_columns` are ordered across the whole
+/// file, given that every row group is sorted by all of them.
+///
+/// The row group statistics give the values that sort first and last in each
+/// row group. The file is ordered if the value that sorts last in each row
+/// group is not after the value that sorts first in the next row group. For
+/// `a ASC`:
+///
+/// ```text
+/// row groups [1, 2] [3, 4]: ordered, because 2 <= 3
+/// row groups [1, 4] [2, 3]: not ordered, because 4 > 2
+/// ```
+///
+/// A later column must be ordered only where all earlier columns are equal.
+/// For `a ASC, b ASC`:
+///
+/// ```text
+/// row groups [(1, 8), (1, 9)] [(2, 0), (2, 1)]: ordered by (a, b), because a 
increases
+/// row groups [(1, 8), (1, 9)] [(1, 0), (1, 1)]: ordered by (a) only, because 
a is equal and 9 > 0
+/// ```
+///
+/// A column whose order cannot be proved, for example because it has no
+/// usable statistics, counts as not ordered. Ordering is optional information,
+/// so this never fails the query.
+fn num_columns_ordered_across_row_groups(
+    metadata: &ParquetMetaData,
+    sorting_columns: &[SortingColumn],
+) -> usize {
+    let row_groups = metadata.row_groups();
+    if row_groups.len() < 2 {
+        return sorting_columns.len();
+    }
+    let file_metadata = metadata.file_metadata();
+    let parquet_schema = file_metadata.schema_descr();
+    let Ok(arrow_schema) =
+        parquet_to_arrow_schema(parquet_schema, 
file_metadata.key_value_metadata())
+    else {
+        return 0;
+    };
+    let resolver = LeafResolver::new(parquet_schema, &arrow_schema);
+
+    let mut sort_exprs = vec![];
+    let mut fields = vec![];
+    let mut mins = vec![];
+    let mut maxes = vec![];
+    for (num_ordered, sorting_column) in sorting_columns.iter().enumerate() {
+        let Some((min, max)) =
+            row_group_min_max(row_groups, parquet_schema, &resolver, 
sorting_column)
+        else {
+            return num_ordered;
+        };
+        // `MinMaxStatistics` finds a column by name, so name it by its 
position
+        let name = num_ordered.to_string();
+        sort_exprs.push(PhysicalSortExpr::new(
+            Arc::new(Column::new(&name, num_ordered)),
+            SortOptions::new(sorting_column.descending, 
sorting_column.nulls_first),
+        ));
+        fields.push(Field::new(name, min.data_type().clone(), true));
+        mins.push(min);
+        maxes.push(max);
+
+        let statistics = || {
+            let schema = Arc::new(Schema::new(fields.clone()));
+            let mins = RecordBatch::try_new(Arc::clone(&schema), 
mins.clone()).ok()?;
+            let maxes = RecordBatch::try_new(Arc::clone(&schema), 
maxes.clone()).ok()?;
+            let sort_order = LexOrdering::new(sort_exprs.iter().cloned())?;
+            MinMaxStatistics::new(&sort_order, &schema, mins, maxes).ok()
+        };
+        let Some(statistics) = statistics().filter(|statistics| 
statistics.is_sorted())
+        else {
+            return num_ordered;
+        };
+        // Each row group ends before the next one starts, so the later sorting
+        // columns cannot change the order
+        if (1..row_groups.len()).all(|i| statistics.max(i - 1) < 
statistics.min(i)) {
+            break;
+        }
+    }
+    sorting_columns.len()
+}
+
+/// Returns the min and the max of `sorting_column` in each row group, as two
+/// arrays with one entry per row group. Where a row group has NULLs, the entry
+/// on the side where NULLs sort is NULL. Returns `None` if the statistics do
+/// not provide the values.
+fn row_group_min_max(
+    row_groups: &[RowGroupMetaData],
+    parquet_schema: &SchemaDescriptor,
+    resolver: &LeafResolver,
+    sorting_column: &SortingColumn,
+) -> Option<(ArrayRef, ArrayRef)> {
+    let column_index = usize::try_from(sorting_column.column_idx).ok()?;
+    let name = parquet_schema.columns().get(column_index)?.name();
+    // The statistics must belong to the sorting column
+    if resolver.leaf_index(name) != Some(column_index) {

Review Comment:
   Added these



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to