alamb commented on code in PR #27163:
URL: https://github.com/apache/datafusion/pull/27163#discussion_r4699425159


##########
datafusion/datasource-parquet/src/metadata.rs:
##########
@@ -1248,6 +1266,134 @@ 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);
+
+    // Compares the value that sorts last in one row group with the value that
+    // sorts first in another
+    let comparator = |sorting_column: &SortingColumn| -> Option<DynComparator> 
{
+        let (first, last) =
+            row_group_sort_bounds(row_groups, parquet_schema, &resolver, 
sorting_column)?;
+        let options =
+            SortOptions::new(sorting_column.descending, 
sorting_column.nulls_first);
+        make_comparator(&last, &first, options).ok()
+    };
+    // One comparator per sorting column, created when the column is first
+    // needed. A later column is often not needed at all.
+    let mut comparators: Vec<Option<DynComparator>> = vec![];
+
+    let mut num_ordered = sorting_columns.len();
+    // Compare each row group with the next one, column by column
+    for i in 0..row_groups.len() - 1 {

Review Comment:
   I think we shoudl be using vectorized arrow kernels for this I think 
otherwise this will be quite slow for row files with many row groups / many 
columns
   
   
   In general there is a lot of overlap here with how 
`MinMaxStatistics::is_sorted` works to check that files do not overlap: 
https://github.com/apache/datafusion/blob/3f837ad0db6f0a9e80bdff0864db5b6ad980ce1a/datafusion/datasource/src/statistics.rs#L294
   
   I think we should try and refactor the code so that we can reuse the code
   
   
   Here is how you get min/max/nulls as arrow arrays:
   
   - row_group_mins: 
https://github.com/apache/arrow-rs/blob/60.1.0/parquet/src/arrow/arrow_reader/statistics.rs#L1845
   - row_group_maxes: 
https://github.com/apache/arrow-rs/blob/60.1.0/parquet/src/arrow/arrow_reader/statistics.rs#L1866
   - row_group_null_counts: 
https://github.com/apache/arrow-rs/blob/60.1.0/parquet/src/arrow/arrow_reader/statistics.rs#L1931
   
   
   Then to check a single column just use the `gt` kernel:
   
   ```rust
   let n = arr.len() - 1;
   // row i compares arr[i] with arr[i + 1]
   let out_of_order = gt(&arr.slice(0, n), &arr.slice(1, n))?;
   let sorted = out_of_order.true_count() == 0;
   ```
   
   Then for a multi-column sort, use a row converter, for example: 
   ```rust
   // One SortField per sorting column, carrying its sort options
   let fields = sorting_columns
       .iter()
       .zip(&lasts)
       .map(|(sc, arr)| {
           SortField::new_with_options(
               arr.data_type().clone(),
               SortOptions::new(sc.descending, sc.nulls_first),
           )
       })
       .collect();
   let converter = RowConverter::new(fields)?;
   
   // lasts / firsts: one array per sorting column, one entry per row group
   let last_rows = converter.convert_columns(&lasts)?;
   let first_rows = converter.convert_columns(&firsts)?;
   
   // row group i must end at or before the start of row group i + 1
   let sorted = (0..last_rows.num_rows() - 1)
       .all(|i| last_rows.row(i) <= first_rows.row(i + 1));
   ```
   
   



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