zhuqi-lucas commented on code in PR #16395: URL: https://github.com/apache/datafusion/pull/16395#discussion_r2153573700
########## datafusion-examples/examples/embedding_parquet_indexes.rs: ########## @@ -0,0 +1,243 @@ +// 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. + +//! Example: embedding a "distinct values" index in a Parquet file's metadata +//! +//! 1. Read existing Parquet files +//! 2. Compute distinct values for a target column using DataFusion +//! 3. Serialize the distinct index to bytes and write to the new Parquet file +//! with these encoded bytes appended as a custom metadata entry +//! 4. Read each new parquet file, extract and deserialize the index from footer +//! 5. Use the distinct index to prune files when querying + +use arrow::array::{ArrayRef, StringArray}; +use arrow::record_batch::RecordBatch; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use async_trait::async_trait; +use base64::engine::general_purpose; +use base64::Engine; +use datafusion::catalog::{Session, TableProvider}; +use datafusion::common::{HashMap, HashSet, Result}; +use datafusion::datasource::listing::PartitionedFile; +use datafusion::datasource::memory::DataSourceExec; +use datafusion::datasource::physical_plan::{FileScanConfigBuilder, ParquetSource}; +use datafusion::datasource::TableType; +use datafusion::execution::object_store::ObjectStoreUrl; +use datafusion::logical_expr::{Operator, TableProviderFilterPushDown}; +use datafusion::parquet::arrow::ArrowWriter; +use datafusion::parquet::file::metadata::KeyValue; +use datafusion::parquet::file::properties::WriterProperties; +use datafusion::parquet::file::reader::{FileReader, SerializedFileReader}; +use datafusion::physical_plan::ExecutionPlan; +use datafusion::prelude::*; +use datafusion::scalar::ScalarValue; +use std::fs::{create_dir_all, read_dir, File}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use tempfile::TempDir; + +/// Example creating parquet file that +/// contains specialized indexes that +/// are ignored by other readers +/// +/// ```text +/// ┌──────────────────────┐ +/// │┌───────────────────┐ │ +/// ││ DataPage │ │ Standard Parquet +/// │└───────────────────┘ │ Data / pages +/// │┌───────────────────┐ │ +/// ││ DataPage │ │ +/// │└───────────────────┘ │ +/// │ ... │ +/// │ │ +/// │┌───────────────────┐ │ +/// ││ DataPage │ │ +/// │└───────────────────┘ │ +/// │┏━━━━━━━━━━━━━━━━━━━┓ │ +/// │┃ ┃ │ key/value metadata +/// │┃ Special Index ┃◀┼──── that points at the +/// │┃ ┃ │ │ special index +/// │┗━━━━━━━━━━━━━━━━━━━┛ │ +/// │╔═══════════════════╗ │ │ +/// │║ ║ │ +/// │║ Parquet Footer ║ │ │ Footer includes +/// │║ ║ ┼────── thrift-encoded +/// │║ ║ │ ParquetMetadata +/// │╚═══════════════════╝ │ +/// └──────────────────────┘ +/// +/// Parquet File +/// ``` +/// DistinctIndexTable is a custom TableProvider that reads Parquet files +#[derive(Debug)] +struct DistinctIndexTable { + schema: SchemaRef, + index: HashMap<String, HashSet<String>>, + dir: PathBuf, +} + +impl DistinctIndexTable { + /// Scan a directory, read each file's footer metadata into a map + fn try_new(dir: impl Into<PathBuf>, schema: SchemaRef) -> Result<Self> { + let dir = dir.into(); + let mut index = HashMap::new(); + for entry in read_dir(&dir)? { + let p = entry?.path(); + if p.extension().and_then(|s| s.to_str()) != Some("parquet") { + continue; + } + let name = p.file_name().unwrap().to_string_lossy().into_owned(); + let reader = SerializedFileReader::new(File::open(&p)?)?; + if let Some(kv) = reader.metadata().file_metadata().key_value_metadata() { + if let Some(e) = kv.iter().find(|kv| kv.key == "distinct_index_data") { + let raw = general_purpose::STANDARD_NO_PAD + .decode(e.value.as_deref().unwrap()) + .unwrap(); + let s = String::from_utf8(raw).unwrap(); + let set = s.lines().map(|l| l.to_string()).collect(); + println!("Inserting File: {name}, Distinct Values: {set:?}"); + index.insert(name, set); + } + } + } + Ok(Self { schema, index, dir }) + } +} + +// Write a Parquet file and embed its distinct "category" values in footer metadata +fn write_file_with_index(path: &Path, values: &[&str]) -> Result<()> { + let field = Field::new("category", DataType::Utf8, false); + let schema = Arc::new(Schema::new(vec![field.clone()])); + let arr: ArrayRef = Arc::new(StringArray::from(values.to_vec())); + let batch = RecordBatch::try_new(schema.clone(), vec![arr])?; + + // Compute distinct values, serialize & Base64‑encode + let distinct: HashSet<_> = values.iter().copied().collect(); + let serialized = distinct.iter().cloned().collect::<Vec<_>>().join("\n"); + let b64 = general_purpose::STANDARD_NO_PAD.encode(serialized.as_bytes()); Review Comment: Thank you @alamb , updated the code without page index using low level API, i will continue debugging the case that our self defined index with page index. -- 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: github-unsubscr...@datafusion.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org For additional commands, e-mail: github-h...@datafusion.apache.org