Skip to content

Apache DataFusion SQL Query Engine

Optionally skip metadata from schema when merging parquet files (#2985)

Andrew Lamb833f588c26bc
diff --git a/datafusion-cli/Cargo.lock b/datafusion-cli/Cargo.lock
index b0ece3f922..5bfafe2c09 100644
--- a/datafusion-cli/Cargo.lock
+++ b/datafusion-cli/Cargo.lock
@@ -57,9 +57,9 @@ checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6"
[[package]]
name = "arrow"
-version = "18.0.0"
+version = "19.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a5f89d2bc04fa746ee395d20c4cbfa508e4cce5c00bae816f0fae434fcfb9853"
+checksum = "89b7e88e4739c3616cae75adce6660c9c1a80f2660545eb77afbe0e4a0f048a0"
dependencies = [
"ahash",
"bitflags",
@@ -1251,9 +1251,9 @@ dependencies = [
[[package]]
name = "parquet"
-version = "18.0.0"
+version = "19.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "65f61759af307fad711e7656c705218402a8a79b776c893c20fef96e8ffd2a7d"
+checksum = "2cfcf237362047888b342e4f0e213a9b303133b085853e447f2c58e65e00099d"
dependencies = [
"arrow",
"base64",
@@ -1535,7 +1535,6 @@ version = "1.0.81"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c"
dependencies = [
- "indexmap",
"itoa 1.0.2",
"ryu",
"serde",
@@ -1594,9 +1593,9 @@ checksum = "45456094d1983e2ee2a18fdfebce3189fa451699d0502cb8e3b49dba5ba41451"
[[package]]
name = "sqlparser"
-version = "0.18.0"
+version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f531637a13132fa3d38c54d4cd8f115905e5dc3e72f6e77bd6160481f482e25d"
+checksum = "d8ec7ef1bad82a2453dbaef7218b6f036e545edcce1ffd55f6e7af7bea43cce2"
dependencies = [
"log",
]
diff --git a/datafusion/core/src/datasource/file_format/parquet.rs b/datafusion/core/src/datasource/file_format/parquet.rs
index abff811c2e..dfd08352df 100644
--- a/datafusion/core/src/datasource/file_format/parquet.rs
+++ b/datafusion/core/src/datasource/file_format/parquet.rs
@@ -54,6 +54,7 @@ pub const DEFAULT_PARQUET_EXTENSION: &str = ".parquet";
pub struct ParquetFormat {
enable_pruning: bool,
metadata_size_hint: Option<usize>,
+ skip_metadata: bool,
}
impl Default for ParquetFormat {
@@ -61,6 +62,7 @@ impl Default for ParquetFormat {
Self {
enable_pruning: true,
metadata_size_hint: None,
+ skip_metadata: true,
}
}
}
@@ -90,6 +92,37 @@ impl ParquetFormat {
pub fn metadata_size_hint(&self) -> Option<usize> {
self.metadata_size_hint
}
+
+ /// Tell the parquet reader to skip any metadata that may be in
+ /// the file Schema. This can help avoid schema conflicts due to
+ /// metadata. Defaults to true.
+ pub fn with_skip_metadata(mut self, skip_metadata: bool) -> Self {
+ self.skip_metadata = skip_metadata;
+ self
+ }
+
+ /// returns true if schema metadata will be cleared prior to
+ /// schema merging.
+ pub fn skip_metadata(&self) -> bool {
+ self.skip_metadata
+ }
+}
+
+/// Clears all metadata (Schema level and field level) on an iterator
+/// of Schemas
+fn clear_metadata(
+ schemas: impl IntoIterator<Item = Schema>,
+) -> impl Iterator<Item = Schema> {
+ schemas.into_iter().map(|schema| {
+ let fields = schema
+ .fields()
+ .iter()
+ .map(|field| {
+ field.clone().with_metadata(None) // clear meta
+ })
+ .collect::<Vec<_>>();
+ Schema::new(fields)
+ })
}
#[async_trait]
@@ -109,7 +142,13 @@ impl FileFormat for ParquetFormat {
fetch_schema(store.as_ref(), object, self.metadata_size_hint).await?;
schemas.push(schema)
}
- let schema = Schema::try_merge(schemas)?;
+
+ let schema = if self.skip_metadata {
+ Schema::try_merge(clear_metadata(schemas))
+ } else {
+ Schema::try_merge(schemas)
+ }?;
+
Ok(Arc::new(schema))
}
diff --git a/datafusion/core/src/execution/options.rs b/datafusion/core/src/execution/options.rs
index a87ae77120..e296d18b6f 100644
--- a/datafusion/core/src/execution/options.rs
+++ b/datafusion/core/src/execution/options.rs
@@ -142,17 +142,23 @@ pub struct ParquetReadOptions<'a> {
pub file_extension: &'a str,
/// Partition Columns
pub table_partition_cols: Vec<String>,
- /// Should DataFusion parquet reader using the predicate to prune data,
+ /// Should DataFusion parquet reader use the predicate to prune data,
/// overridden by value on execution::context::SessionConfig
pub parquet_pruning: bool,
+ /// Tell the parquet reader to skip any metadata that may be in
+ /// the file Schema. This can help avoid schema conflicts due to
+ /// metadata. Defaults to true.
+ pub skip_metadata: bool,
}
impl<'a> Default for ParquetReadOptions<'a> {
fn default() -> Self {
+ let format_default = ParquetFormat::default();
Self {
file_extension: DEFAULT_PARQUET_EXTENSION,
table_partition_cols: vec![],
- parquet_pruning: ParquetFormat::default().enable_pruning(),
+ parquet_pruning: format_default.enable_pruning(),
+ skip_metadata: format_default.skip_metadata(),
}
}
}
@@ -164,6 +170,14 @@ impl<'a> ParquetReadOptions<'a> {
self
}
+ /// Tell the parquet reader to skip any metadata that may be in
+ /// the file Schema. This can help avoid schema conflicts due to
+ /// metadata. Defaults to true.
+ pub fn skip_metadata(mut self, skip_metadata: bool) -> Self {
+ self.skip_metadata = skip_metadata;
+ self
+ }
+
/// Specify table_partition_cols for partition pruning
pub fn table_partition_cols(mut self, table_partition_cols: Vec<String>) -> Self {
self.table_partition_cols = table_partition_cols;
@@ -172,8 +186,9 @@ impl<'a> ParquetReadOptions<'a> {
/// Helper to convert these user facing options to `ListingTable` options
pub fn to_listing_options(&self, target_partitions: usize) -> ListingOptions {
- let file_format =
- ParquetFormat::default().with_enable_pruning(self.parquet_pruning);
+ let file_format = ParquetFormat::default()
+ .with_enable_pruning(self.parquet_pruning)
+ .with_skip_metadata(self.skip_metadata);
ListingOptions {
format: Arc::new(file_format),
diff --git a/datafusion/core/src/physical_plan/file_format/mod.rs b/datafusion/core/src/physical_plan/file_format/mod.rs
index c26b2d760a..d7d70cd4b8 100644
--- a/datafusion/core/src/physical_plan/file_format/mod.rs
+++ b/datafusion/core/src/physical_plan/file_format/mod.rs
@@ -130,7 +130,9 @@ impl FileScanConfig {
column_statistics: Some(table_cols_stats),
};
- let table_schema = Arc::new(Schema::new(table_fields));
+ let table_schema = Arc::new(
+ Schema::new(table_fields).with_metadata(self.file_schema.metadata().clone()),
+ );
(table_schema, table_stats)
}
diff --git a/datafusion/core/tests/sql/mod.rs b/datafusion/core/tests/sql/mod.rs
index f4153757ff..4dd8750c84 100644
--- a/datafusion/core/tests/sql/mod.rs
+++ b/datafusion/core/tests/sql/mod.rs
@@ -109,6 +109,7 @@ pub mod decimal;
mod explain;
mod idenfifers;
pub mod information_schema;
+mod parquet_schema;
mod partitioned_csv;
mod subqueries;
#[cfg(feature = "unicode_expressions")]
diff --git a/datafusion/core/tests/sql/parquet.rs b/datafusion/core/tests/sql/parquet.rs
index 69d83858a1..51304f6087 100644
--- a/datafusion/core/tests/sql/parquet.rs
+++ b/datafusion/core/tests/sql/parquet.rs
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-use std::{collections::HashMap, fs, path::Path};
+use std::{fs, path::Path};
use ::parquet::arrow::ArrowWriter;
use tempfile::TempDir;
@@ -173,58 +173,6 @@ async fn parquet_list_columns() {
assert_eq!(result.value(3), "xyz");
}
-#[tokio::test]
-async fn schema_merge_ignores_metadata() {
- // Create two parquet files in same table with same schema but different metadata
- let tmp_dir = TempDir::new().unwrap();
- let table_dir = tmp_dir.path().join("parquet_test");
- let table_path = Path::new(&table_dir);
-
- let mut non_empty_metadata: HashMap<String, String> = HashMap::new();
- non_empty_metadata.insert("testing".to_string(), "metadata".to_string());
-
- let fields = vec![
- Field::new("id", DataType::Int32, true),
- Field::new("name", DataType::Utf8, true),
- ];
- let schemas = vec![
- Arc::new(Schema::new_with_metadata(
- fields.clone(),
- non_empty_metadata.clone(),
- )),
- Arc::new(Schema::new(fields.clone())),
- ];
-
- if let Ok(()) = fs::create_dir(table_path) {
- for (i, schema) in schemas.iter().enumerate().take(2) {
- let filename = format!("part-{}.parquet", i);
- let path = table_path.join(&filename);
- let file = fs::File::create(path).unwrap();
- let mut writer = ArrowWriter::try_new(file, schema.clone(), None).unwrap();
-
- // create mock record batch
- let ids = Arc::new(Int32Array::from_slice(&[i as i32]));
- let names = Arc::new(StringArray::from_slice(&["test"]));
- let rec_batch =
- RecordBatch::try_new(schema.clone(), vec![ids, names]).unwrap();
-
- writer.write(&rec_batch).unwrap();
- writer.close().unwrap();
- }
- }
-
- // Read the parquet files into a dataframe to confirm results
- // (no errors)
- let ctx = SessionContext::new();
- let df = ctx
- .read_parquet(table_dir.to_str().unwrap(), ParquetReadOptions::default())
- .await
- .unwrap();
- let result = df.collect().await.unwrap();
-
- assert_eq!(result[0].schema().metadata(), result[1].schema().metadata());
-}
-
#[tokio::test]
async fn parquet_query_with_max_min() {
let tmp_dir = TempDir::new().unwrap();
diff --git a/datafusion/core/tests/sql/parquet_schema.rs b/datafusion/core/tests/sql/parquet_schema.rs
new file mode 100644
index 0000000000..b5a891268d
--- /dev/null
+++ b/datafusion/core/tests/sql/parquet_schema.rs
@@ -0,0 +1,219 @@
+// 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.
+
+//! Tests for parquet schema handling
+use std::{
+ collections::{BTreeMap, HashMap},
+ fs,
+ path::Path,
+};
+
+use ::parquet::arrow::ArrowWriter;
+use tempfile::TempDir;
+
+use super::*;
+
+#[tokio::test]
+async fn schema_merge_ignores_metadata_by_default() {
+ // Create several parquet files in same directoty / table with
+ // same schema but different metadata
+ let tmp_dir = TempDir::new().unwrap();
+ let table_dir = tmp_dir.path().join("parquet_test");
+
+ let options = ParquetReadOptions::default();
+
+ let f1 = Field::new("id", DataType::Int32, true);
+ let f2 = Field::new("name", DataType::Utf8, true);
+
+ let schemas = vec![
+ // schema level metadata
+ Schema::new(vec![f1.clone(), f2.clone()]).with_metadata(make_meta("foo", "bar")),
+ // schema different (incompatible) metadata
+ Schema::new(vec![f1.clone(), f2.clone()]).with_metadata(make_meta("foo", "baz")),
+ // schema with no meta
+ Schema::new(vec![f1.clone(), f2.clone()]),
+ // field level metadata
+ Schema::new(vec![
+ f1.clone().with_metadata(make_b_meta("blarg", "bar")),
+ f2.clone(),
+ ]),
+ // incompatible field level metadata
+ Schema::new(vec![
+ f1.clone().with_metadata(make_b_meta("blarg", "baz")),
+ f2.clone(),
+ ]),
+ // schema with no meta
+ Schema::new(vec![f1, f2]),
+ ];
+ write_files(table_dir.as_path(), schemas);
+
+ // can be any order
+ let expected = vec![
+ "+----+------+",
+ "| id | name |",
+ "+----+------+",
+ "| 1 | test |",
+ "| 2 | test |",
+ "| 3 | test |",
+ "| 0 | test |",
+ "| 5 | test |",
+ "| 4 | test |",
+ "+----+------+",
+ ];
+
+ // Read the parquet files into a dataframe to confirm results
+ // (no errors)
+ let table_path = table_dir.to_str().unwrap().to_string();
+
+ let ctx = SessionContext::new();
+ let df = ctx
+ .read_parquet(&table_path, options.clone())
+ .await
+ .unwrap();
+ let actual = df.collect().await.unwrap();
+
+ assert_batches_sorted_eq!(expected, &actual);
+ assert_no_metadata(&actual);
+
+ // also validate it works via SQL interface as well
+ ctx.register_parquet("t", &table_path, options)
+ .await
+ .unwrap();
+
+ let actual = execute_to_batches(&ctx, "SELECT * from t").await;
+ assert_batches_sorted_eq!(expected, &actual);
+ assert_no_metadata(&actual);
+}
+
+#[tokio::test]
+async fn schema_merge_can_preserve_metadata() {
+ // Create several parquet files in same directoty / table with
+ // same schema but different metadata
+ let tmp_dir = TempDir::new().unwrap();
+ let table_dir = tmp_dir.path().join("parquet_test");
+
+ // explicitly disable schema clearing
+ let options = ParquetReadOptions::default().skip_metadata(false);
+
+ let f1 = Field::new("id", DataType::Int32, true);
+ let f2 = Field::new("name", DataType::Utf8, true);
+
+ let schemas = vec![
+ // schema level metadata
+ Schema::new(vec![f1.clone(), f2.clone()]).with_metadata(make_meta("foo", "bar")),
+ // schema different (compatible) metadata
+ Schema::new(vec![f1.clone(), f2.clone()]).with_metadata(make_meta("foo2", "baz")),
+ // schema with no meta
+ Schema::new(vec![f1.clone(), f2.clone()]),
+ ];
+ write_files(table_dir.as_path(), schemas);
+
+ // can be any order
+ let expected = vec![
+ "+----+------+",
+ "| id | name |",
+ "+----+------+",
+ "| 1 | test |",
+ "| 2 | test |",
+ "| 0 | test |",
+ "+----+------+",
+ ];
+
+ let mut expected_metadata = make_meta("foo", "bar");
+ expected_metadata.insert("foo2".into(), "baz".into());
+
+ // Read the parquet files into a dataframe to confirm results
+ // (no errors)
+ let table_path = table_dir.to_str().unwrap().to_string();
+
+ let ctx = SessionContext::new();
+ let df = ctx
+ .read_parquet(&table_path, options.clone())
+ .await
+ .unwrap();
+ let actual = df.collect().await.unwrap();
+
+ assert_batches_sorted_eq!(expected, &actual);
+ assert_metadata(&actual, &expected_metadata);
+
+ // also validate it works via SQL interface as well
+ ctx.register_parquet("t", &table_path, options)
+ .await
+ .unwrap();
+
+ let actual = execute_to_batches(&ctx, "SELECT * from t").await;
+ assert_batches_sorted_eq!(expected, &actual);
+ assert_metadata(&actual, &expected_metadata);
+}
+
+fn make_meta(k: impl Into<String>, v: impl Into<String>) -> HashMap<String, String> {
+ let mut meta = HashMap::new();
+ meta.insert(k.into(), v.into());
+ meta
+}
+
+/// Make btree version (field and schema level metadata are
+/// different for some reason in Arrow :shrug:)
+fn make_b_meta(
+ k: impl Into<String>,
+ v: impl Into<String>,
+) -> Option<BTreeMap<String, String>> {
+ let mut meta = BTreeMap::new();
+ meta.insert(k.into(), v.into());
+ Some(meta)
+}
+
+/// Writes individual files with the specified schemas to temp_path)
+///
+/// Assumes each schema has an int32 and a string column
+fn write_files(table_path: &Path, schemas: Vec<Schema>) {
+ fs::create_dir(table_path).expect("Error creating temp dir");
+
+ for (i, schema) in schemas.into_iter().enumerate() {
+ let schema = Arc::new(schema);
+ let filename = format!("part-{}.parquet", i);
+ let path = table_path.join(&filename);
+ let file = fs::File::create(path).unwrap();
+ let mut writer = ArrowWriter::try_new(file, schema.clone(), None).unwrap();
+
+ // create mock record batch
+ let ids = Arc::new(Int32Array::from_slice(&[i as i32]));
+ let names = Arc::new(StringArray::from_slice(&["test"]));
+ let rec_batch = RecordBatch::try_new(schema.clone(), vec![ids, names]).unwrap();
+
+ writer.write(&rec_batch).unwrap();
+ writer.close().unwrap();
+ }
+}
+
+fn assert_no_metadata(batches: &[RecordBatch]) {
+ // all batches should have no metadata
+ for batch in batches {
+ assert!(
+ batch.schema().metadata().is_empty(),
+ "schema had metadata: {:?}",
+ batch.schema()
+ );
+ }
+}
+
+fn assert_metadata(batches: &[RecordBatch], expected_metadata: &HashMap<String, String>) {
+ // all batches should have no metadata
+ for batch in batches {
+ assert_eq!(batch.schema().metadata(), expected_metadata,);
+ }
+}