rdettai commented on a change in pull request #1141: URL: https://github.com/apache/arrow-datafusion/pull/1141#discussion_r735325807
########## File path: datafusion/src/datasource/listing/helpers.rs ########## @@ -0,0 +1,682 @@ +// 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. + +//! Helper functions for the table implementation + +use std::sync::Arc; + +use arrow::{ + array::{ + Array, ArrayBuilder, ArrayRef, Date64Array, Date64Builder, StringArray, + StringBuilder, UInt64Array, UInt64Builder, + }, + datatypes::{DataType, Field, Schema}, + record_batch::RecordBatch, +}; +use chrono::{TimeZone, Utc}; +use futures::{ + stream::{self}, + StreamExt, TryStreamExt, +}; +use log::debug; + +use crate::{ + error::Result, + execution::context::ExecutionContext, + logical_plan::{self, Expr}, + physical_plan::functions::Volatility, + scalar::ScalarValue, +}; + +use crate::datasource::{ + object_store::{FileMeta, ObjectStore, SizedFile}, + MemTable, PartitionedFile, PartitionedFileStream, +}; + +const FILE_SIZE_COLUMN_NAME: &str = "_df_part_file_size_"; +const FILE_PATH_COLUMN_NAME: &str = "_df_part_file_path_"; +const FILE_MODIFIED_COLUMN_NAME: &str = "_df_part_file_modified_"; + +/// Partition the list of files into `n` groups +pub fn split_files( + partitioned_files: Vec<PartitionedFile>, + n: usize, +) -> Vec<Vec<PartitionedFile>> { + if partitioned_files.is_empty() { + return vec![]; + } + let mut chunk_size = partitioned_files.len() / n; + if partitioned_files.len() % n > 0 { + chunk_size += 1; + } + partitioned_files + .chunks(chunk_size) + .map(|c| c.to_vec()) + .collect() +} + +/// Discover the partitions on the given path and prune out files +/// relative to irrelevant partitions using `filters` expressions +/// TODO for tables with many files (10k+), it will usually more efficient +/// to first list the folders relative to the first partition dimension, +/// prune those, then list only the contain of the remaining folders. +pub async fn pruned_partition_list( + store: &dyn ObjectStore, + table_path: &str, + filters: &[Expr], + file_extension: &str, + table_partition_dims: &[String], +) -> Result<PartitionedFileStream> { + if table_partition_dims.is_empty() { + Ok(Box::pin( + store + .list_file_with_suffix(table_path, file_extension) + .await? + .map(|f| { + Ok(PartitionedFile { + file_meta: f?, + partition_values: vec![], + }) + }), + )) + } else { + let applicable_filters = filters + .iter() + .filter(|f| expr_applicable_for_cols(table_partition_dims, f)); + + let table_partition_dims = table_partition_dims.to_vec(); + let stream_path = table_path.to_owned(); + // TODO avoid collecting but have a streaming memory table instead + let batches: Vec<RecordBatch> = store + .list_file_with_suffix(table_path, file_extension) + .await? + .chunks(64) + .map(|v| v.into_iter().collect::<Result<Vec<_>>>()) + .map(move |metas| { + paths_to_batch(&table_partition_dims, &stream_path, &metas?) + }) + .try_collect() + .await?; + + let mem_table = MemTable::try_new(batches[0].schema(), vec![batches])?; + + // Filter the partitions using a local datafusion context + // TODO having the external context would allow us to resolve `Volatility::Stable` + // scalar functions (`ScalarFunction` & `ScalarUDF`) and `ScalarVariable`s + let mut ctx = ExecutionContext::new(); + let mut df = ctx.read_table(Arc::new(mem_table))?; + for filter in applicable_filters { + df = df.filter(filter.clone())?; + } + let filtered_batches = df.collect().await?; Review comment: datafusion in datafusion is practical, because we have the filters as logical expressions 🙂. But you are right, it might be a bit cheaper to convert the logical expressions into physical ones manually and put together a `MemoryExec` and a `FilterExec` ourselves. In all cases, the solution proposed here is not the final one because we would need a way to avoid materializing the entire list of files (as described in the `// TODO`). When doing that improvement, it will be interesting to re-assess if it makes sense using the high level Datafusion API or not 😉 -- 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]
