Skip to main content

parquet_cli/
meta.rs

1//! What is in the file: its facts, its schema, and its columns' statistics.
2
3use std::collections::{BTreeMap, BTreeSet, HashSet};
4use std::fs::File;
5use std::path::Path;
6use std::sync::Arc;
7
8use anyhow::{Context, Result};
9use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
10use parquet::data_type::AsBytes;
11use parquet::file::metadata::ParquetMetaData;
12use parquet::file::statistics::Statistics;
13use serde_json::{json, Map, Value};
14
15use crate::value::{data_type_name, field_json};
16
17/// Open a Parquet file and read its footer.
18pub fn open(path: &Path) -> Result<Arc<ParquetMetaData>> {
19    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
20    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
21        .with_context(|| format!("read the footer of {}", path.display()))?;
22    Ok(builder.metadata().clone())
23}
24
25/// What the footer says about the file as a whole.
26#[derive(Clone, Debug)]
27pub struct FileFacts {
28    /// The path, as it was given.
29    pub path: String,
30    /// How many bytes the file is.
31    pub size_bytes: u64,
32    /// How many rows it holds.
33    pub rows: i64,
34    /// How many row groups it has.
35    pub row_groups: usize,
36    /// How many leaf columns it has.
37    pub columns: usize,
38    /// How many rows each row group holds.
39    pub row_group_rows: Vec<i64>,
40    /// The bytes the column chunks take.
41    pub column_bytes: i64,
42    /// The bytes after the data: the metadata, the page index, and the
43    /// magic. This is what a reader fetches before it can read anything.
44    pub footer_bytes: i64,
45    /// The bytes the metadata itself takes (the tail of the file).
46    pub metadata_bytes: i64,
47    /// The bytes each row group takes.
48    pub row_group_bytes: Vec<i64>,
49    /// What one lookup reads, typically: the footer plus one row group.
50    pub lookup_reads_typical: i64,
51    /// What one lookup reads at worst: the footer plus the largest row group.
52    pub lookup_reads_worst: i64,
53    /// Who wrote the file.
54    pub created_by: Option<String>,
55    /// The Parquet format version.
56    pub format_version: i32,
57    /// The compressions the columns use.
58    pub compressions: Vec<String>,
59    /// The encodings the pages use.
60    pub encodings: Vec<String>,
61    /// The key-value metadata the writer left behind.
62    pub key_value_metadata: Vec<Value>,
63}
64
65/// What the footer says about one column.
66#[derive(Clone, Debug)]
67pub struct ColumnFacts {
68    /// The name of the leaf column (its path, when it is nested).
69    pub name: String,
70    /// The type a person reads: the logical type when the file has one, the
71    /// Arrow type when it does not but the Arrow schema is there, the physical
72    /// type when there is nothing better.
73    pub data_type: String,
74    /// The physical type (`INT64`, `BYTE_ARRAY`, …).
75    pub physical_type: String,
76    /// The logical type, when the file carries one.
77    pub logical_type: String,
78    /// The compression the column was written with.
79    pub compression: String,
80    /// The encodings its pages use.
81    pub encodings: Vec<String>,
82    /// How many values there are (nulls included).
83    pub num_values: i64,
84    /// How many of them are null.
85    pub null_count: u64,
86    /// The smallest value, when the footer has it.
87    pub min: Option<Value>,
88    /// The largest value, when the footer has it.
89    pub max: Option<Value>,
90    /// How many bytes the column takes in the file.
91    pub compressed_size: i64,
92    /// How many bytes the values take before compression.
93    pub uncompressed_size: i64,
94    /// The distinct values, when the file was read to count them.
95    pub distinct_count: Option<u64>,
96    /// The statistics of each row group: what a reader uses to skip one.
97    pub row_groups: Vec<GroupStat>,
98}
99
100/// What one row group holds of one column.
101#[derive(Clone, Debug)]
102pub struct GroupStat {
103    /// Which row group this is.
104    pub index: usize,
105    /// How many rows it holds.
106    pub rows: i64,
107    /// The smallest value in it.
108    pub min: Option<Value>,
109    /// The largest value in it.
110    pub max: Option<Value>,
111}
112
113/// File-level facts: size, rows, row groups, who wrote it.
114pub fn facts(path: &Path) -> Result<Value> {
115    let file = file_facts(path)?;
116    Ok(json!({
117        "file": file.path,
118        "size_bytes": file.size_bytes,
119        "rows": file.rows,
120        "row_groups": file.row_groups,
121        "columns": file.columns,
122        "format_version": file.format_version,
123        "created_by": file.created_by,
124        "bytes_per_row": if file.rows > 0 {
125            file.size_bytes as f64 / file.rows as f64
126        } else {
127            0.0
128        },
129        "column_bytes": file.column_bytes,
130        "footer_bytes": file.footer_bytes,
131        "metadata_bytes": file.metadata_bytes,
132        "row_group_bytes": file.row_group_bytes,
133        "lookup_reads_typical": file.lookup_reads_typical,
134        "lookup_reads_worst": file.lookup_reads_worst,
135        "rows_per_group": {
136            "min": file.row_group_rows.iter().copied().min().unwrap_or(0),
137            "max": file.row_group_rows.iter().copied().max().unwrap_or(0),
138            "average": if file.row_group_rows.is_empty() {
139                0
140            } else {
141                file.rows / file.row_groups as i64
142            },
143            "even": file
144                .row_group_rows
145                .iter()
146                .all(|rows| *rows == file.row_group_rows[0]),
147        },
148        "compressions": file.compressions,
149        "encodings": file.encodings,
150        "key_value_metadata": file.key_value_metadata,
151        "row_group_rows": file.row_group_rows,
152    }))
153}
154
155/// The footer, read as facts.
156pub fn file_facts(path: &Path) -> Result<FileFacts> {
157    let metadata = open(path)?;
158    let file = metadata.file_metadata();
159    let size_bytes = std::fs::metadata(path)?.len();
160    let rows = file.num_rows();
161
162    let mut compressions = BTreeSet::new();
163    let mut encodings = BTreeSet::new();
164    let mut column_bytes = 0i64;
165    let mut row_group_bytes = Vec::new();
166    for group in metadata.row_groups() {
167        let mut group_bytes = 0i64;
168        for chunk in group.columns() {
169            compressions.insert(format!("{}", chunk.compression_codec()));
170            encodings.extend(chunk.encodings().map(|encoding| format!("{encoding}")));
171            group_bytes += chunk.compressed_size();
172        }
173        column_bytes += group_bytes;
174        row_group_bytes.push(group_bytes);
175    }
176
177    let key_value_metadata: Vec<Value> = file
178        .key_value_metadata()
179        .map(|entries| {
180            entries
181                .iter()
182                .map(|entry| {
183                    json!({
184                        "key": entry.key,
185                        "value": entry.value,
186                    })
187                })
188                .collect()
189        })
190        .unwrap_or_default();
191
192    let footer_bytes = size_bytes as i64 - column_bytes;
193    let metadata_bytes = metadata_size(path).unwrap_or(footer_bytes);
194    let typical_group = if row_group_bytes.is_empty() {
195        0
196    } else {
197        row_group_bytes.iter().sum::<i64>() / row_group_bytes.len() as i64
198    };
199    let largest_group = row_group_bytes.iter().copied().max().unwrap_or(0);
200
201    Ok(FileFacts {
202        path: path.display().to_string(),
203        size_bytes,
204        rows,
205        row_groups: metadata.row_groups().len(),
206        columns: metadata.file_metadata().schema_descr().num_columns(),
207        row_group_rows: metadata
208            .row_groups()
209            .iter()
210            .map(|group| group.num_rows())
211            .collect(),
212        column_bytes,
213        footer_bytes,
214        metadata_bytes,
215        row_group_bytes,
216        lookup_reads_typical: footer_bytes + typical_group,
217        lookup_reads_worst: footer_bytes + largest_group,
218        created_by: file.created_by().map(|text| text.to_string()),
219        format_version: file.version(),
220        compressions: compressions.into_iter().collect(),
221        encodings: encodings.into_iter().collect(),
222        key_value_metadata,
223    })
224}
225
226/// How many bytes the metadata at the end of the file takes.
227///
228/// A Parquet file ends with the metadata, its length as four little-endian
229/// bytes, and the magic `PAR1`.
230fn metadata_size(path: &Path) -> Option<i64> {
231    use std::io::{Read, Seek, SeekFrom};
232    let mut file = File::open(path).ok()?;
233    let size = file.metadata().ok()?.len();
234    if size < 8 {
235        return None;
236    }
237    file.seek(SeekFrom::Start(size - 8)).ok()?;
238    let mut tail = [0u8; 8];
239    file.read_exact(&mut tail).ok()?;
240    if &tail[4..8] != b"PAR1" {
241        return None;
242    }
243    let length = u32::from_le_bytes([tail[0], tail[1], tail[2], tail[3]]) as i64;
244    Some(length + 8)
245}
246
247/// The schema, as Arrow sees it.
248pub fn schema(path: &Path) -> Result<Value> {
249    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
250    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
251        .with_context(|| format!("read the footer of {}", path.display()))?;
252    let arrow_schema = builder.schema().clone();
253    let fields: Vec<Value> = arrow_schema
254        .fields()
255        .iter()
256        .map(|field| field_json(field.as_ref()))
257        .collect();
258    Ok(json!({
259        "file": path.display().to_string(),
260        "fields": fields,
261    }))
262}
263
264/// The schema as flat lines: `name  type  nullable`.
265pub fn schema_lines(path: &Path) -> Result<Vec<(String, String, bool)>> {
266    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
267    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
268        .with_context(|| format!("read the footer of {}", path.display()))?;
269    let arrow_schema = builder.schema().clone();
270    let mut lines = Vec::new();
271    for field in arrow_schema.fields().iter() {
272        lines.push((
273            field.name().clone(),
274            data_type_name(field.data_type()),
275            field.is_nullable(),
276        ));
277    }
278    Ok(lines)
279}
280
281/// Per-column statistics, taken from the footer.
282///
283/// With `scan`, the file is also read so the distinct counts are exact.
284pub fn column_facts(path: &Path, scan: bool) -> Result<Vec<ColumnFacts>> {
285    let metadata = open(path)?;
286    let arrow_types = arrow_leaf_types(path)?;
287
288    let distinct_counts: Option<Vec<HashSet<String>>> = if scan {
289        Some(scan_distinct(path)?)
290    } else {
291        None
292    };
293
294    // The columns of the footer are leaves: a struct column shows up as one
295    // leaf per field, named by its path.
296    let leaf_names: Vec<String> = metadata
297        .file_metadata()
298        .schema_descr()
299        .columns()
300        .iter()
301        .map(|column| column.path().string())
302        .collect();
303
304    let mut per_column: BTreeMap<usize, ColumnStats> = BTreeMap::new();
305    for (group_index, group) in metadata.row_groups().iter().enumerate() {
306        for (position, chunk) in group.columns().iter().enumerate() {
307            let stats = per_column.entry(position).or_insert_with(|| ColumnStats {
308                path: chunk.column_path().string(),
309                physical_type: format!("{}", chunk.column_type()),
310                logical_type: chunk
311                    .column_descr()
312                    .logical_type_ref()
313                    .map(|logical| format!("{logical:?}"))
314                    .unwrap_or_else(|| "-".into()),
315                compression: format!("{}", chunk.compression_codec()),
316                encodings: BTreeSet::new(),
317                num_values: 0,
318                null_count: 0,
319                min: None,
320                max: None,
321                compressed_size: 0,
322                uncompressed_size: 0,
323                row_groups: Vec::new(),
324            });
325            stats
326                .encodings
327                .extend(chunk.encodings().map(|encoding| format!("{encoding}")));
328            stats.num_values += chunk.num_values();
329            stats.compressed_size += chunk.compressed_size();
330            stats.uncompressed_size += chunk.uncompressed_size();
331            let mut group_min = Value::Null;
332            let mut group_max = Value::Null;
333            if let Some(statistics) = chunk.statistics() {
334                stats.null_count += statistics.null_count_opt().unwrap_or(0);
335                let (min, max) = bounds(statistics);
336                group_min = min.clone().unwrap_or(Value::Null);
337                group_max = max.clone().unwrap_or(Value::Null);
338                stats.min = merge_min(stats.min.take(), min);
339                stats.max = merge_max(stats.max.take(), max);
340            }
341            stats.row_groups.push(GroupStat {
342                index: group_index,
343                rows: group.num_rows(),
344                min: if group_min.is_null() {
345                    None
346                } else {
347                    Some(group_min)
348                },
349                max: if group_max.is_null() {
350                    None
351                } else {
352                    Some(group_max)
353                },
354            });
355        }
356    }
357
358    let mut facts = Vec::new();
359    for (position, stats) in per_column.iter() {
360        let name = leaf_names
361            .get(*position)
362            .cloned()
363            .unwrap_or_else(|| stats.path.clone());
364        // The Arrow type reads best (`utf8`, `decimal128(21,1)`); the logical
365        // type is the writer's own wording, and the physical type is the
366        // fallback when there is no Arrow schema to go by.
367        let data_type = arrow_types
368            .get(&stats.path)
369            .cloned()
370            .or_else(|| {
371                if stats.logical_type != "-" {
372                    Some(stats.logical_type.clone())
373                } else {
374                    None
375                }
376            })
377            .unwrap_or_else(|| stats.physical_type.clone());
378        facts.push(ColumnFacts {
379            name,
380            data_type,
381            physical_type: stats.physical_type.clone(),
382            logical_type: stats.logical_type.clone(),
383            compression: stats.compression.clone(),
384            encodings: stats.encodings.iter().cloned().collect(),
385            num_values: stats.num_values,
386            null_count: stats.null_count,
387            min: stats.min.clone(),
388            max: stats.max.clone(),
389            compressed_size: stats.compressed_size,
390            uncompressed_size: stats.uncompressed_size,
391            distinct_count: distinct_counts
392                .as_ref()
393                .and_then(|sets| sets.get(*position))
394                .map(|set| set.len() as u64),
395            row_groups: stats.row_groups.clone(),
396        });
397    }
398    Ok(facts)
399}
400
401/// Per-column statistics as JSON.
402pub fn columns(path: &Path, scan: bool) -> Result<Value> {
403    let file = file_facts(path)?;
404    let facts = column_facts(path, scan)?;
405
406    let mut out = Vec::new();
407    for column in facts {
408        let mut object = Map::new();
409        object.insert("name".into(), Value::String(column.name.clone()));
410        object.insert("type".into(), Value::String(column.data_type.clone()));
411        object.insert(
412            "physical_type".into(),
413            Value::String(column.physical_type.clone()),
414        );
415        object.insert(
416            "logical_type".into(),
417            Value::String(column.logical_type.clone()),
418        );
419        object.insert(
420            "compression".into(),
421            Value::String(column.compression.clone()),
422        );
423        object.insert(
424            "encodings".into(),
425            Value::Array(
426                column
427                    .encodings
428                    .iter()
429                    .map(|encoding| Value::String(encoding.clone()))
430                    .collect(),
431            ),
432        );
433        object.insert("num_values".into(), json!(column.num_values));
434        object.insert("null_count".into(), json!(column.null_count));
435        object.insert("min".into(), column.min.clone().unwrap_or(Value::Null));
436        object.insert("max".into(), column.max.clone().unwrap_or(Value::Null));
437        object.insert("compressed_size".into(), json!(column.compressed_size));
438        // The same number, under the name a script would reach for.
439        object.insert("bytes".into(), json!(column.compressed_size));
440        object.insert("uncompressed_size".into(), json!(column.uncompressed_size));
441        object.insert(
442            "share".into(),
443            json!(if file.size_bytes > 0 {
444                column.compressed_size as f64 / file.size_bytes as f64
445            } else {
446                0.0
447            }),
448        );
449        object.insert(
450            "ratio".into(),
451            json!(if column.uncompressed_size > 0 {
452                column.compressed_size as f64 / column.uncompressed_size as f64
453            } else {
454                0.0
455            }),
456        );
457        object.insert(
458            "bytes_per_value".into(),
459            json!(if column.num_values > 0 {
460                column.compressed_size as f64 / column.num_values as f64
461            } else {
462                0.0
463            }),
464        );
465        if let Some(distinct) = column.distinct_count {
466            object.insert("distinct_count".into(), json!(distinct));
467        }
468        let row_groups: Vec<Value> = column
469            .row_groups
470            .iter()
471            .map(|group| {
472                json!({
473                    "index": group.index,
474                    "rows": group.rows,
475                    "min": group.min.clone().unwrap_or(Value::Null),
476                    "max": group.max.clone().unwrap_or(Value::Null),
477                })
478            })
479            .collect();
480        object.insert("row_groups".into(), Value::Array(row_groups));
481        out.push(Value::Object(object));
482    }
483
484    Ok(json!({
485        "file": path.display().to_string(),
486        "size_bytes": file.size_bytes,
487        "column_bytes": file.column_bytes,
488        "footer_bytes": file.footer_bytes,
489        "metadata_bytes": file.metadata_bytes,
490        "row_group_bytes": file.row_group_bytes,
491        "lookup_reads_typical": file.lookup_reads_typical,
492        "lookup_reads_worst": file.lookup_reads_worst,
493        "rows_per_group": {
494            "min": file.row_group_rows.iter().copied().min().unwrap_or(0),
495            "max": file.row_group_rows.iter().copied().max().unwrap_or(0),
496            "average": if file.row_group_rows.is_empty() {
497                0
498            } else {
499                file.rows / file.row_groups as i64
500            },
501            "even": file
502                .row_group_rows
503                .iter()
504                .all(|rows| *rows == file.row_group_rows[0]),
505        },
506        "columns": out,
507    }))
508}
509
510/// The Arrow type of every leaf of a file, keyed by the leaf's path.
511///
512/// The Arrow schema of a file is a friendlier name for a column than the
513/// physical type is: `BYTE_ARRAY` is what the bytes are, `utf8` is what they
514/// mean.
515fn arrow_leaf_types(path: &Path) -> Result<BTreeMap<String, String>> {
516    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
517    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
518        .with_context(|| format!("read the footer of {}", path.display()))?;
519    let arrow_schema = builder.schema().clone();
520
521    let mut types = BTreeMap::new();
522    for field in arrow_schema.fields().iter() {
523        collect_leaves(field, "", &mut types);
524    }
525    Ok(types)
526}
527
528/// Walk a field down to its leaves.
529fn collect_leaves(field: &arrow_schema::Field, prefix: &str, types: &mut BTreeMap<String, String>) {
530    let path = if prefix.is_empty() {
531        field.name().clone()
532    } else {
533        format!("{prefix}.{}", field.name())
534    };
535    match field.data_type() {
536        arrow_schema::DataType::Struct(fields) => {
537            for inner in fields.iter() {
538                collect_leaves(inner, &path, types);
539            }
540        }
541        arrow_schema::DataType::List(inner)
542        | arrow_schema::DataType::LargeList(inner)
543        | arrow_schema::DataType::FixedSizeList(inner, _)
544        | arrow_schema::DataType::Map(inner, _) => collect_leaves(inner, &path, types),
545        other => {
546            types.insert(path, data_type_name(other));
547        }
548    }
549}
550
551struct ColumnStats {
552    path: String,
553    physical_type: String,
554    logical_type: String,
555    compression: String,
556    encodings: BTreeSet<String>,
557    num_values: i64,
558    null_count: u64,
559    min: Option<Value>,
560    max: Option<Value>,
561    compressed_size: i64,
562    uncompressed_size: i64,
563    row_groups: Vec<GroupStat>,
564}
565
566/// Read the file and count the distinct values of every column.
567pub fn scan_distinct(path: &Path) -> Result<Vec<HashSet<String>>> {
568    let file = File::open(path)?;
569    let reader = ParquetRecordBatchReaderBuilder::try_new(file)?
570        .with_batch_size(8192)
571        .build()?;
572    let mut sets: Vec<HashSet<String>> = Vec::new();
573    for batch in reader {
574        let batch = batch?;
575        if sets.is_empty() {
576            sets = (0..batch.num_columns()).map(|_| HashSet::new()).collect();
577        }
578        for (index, column) in batch.columns().iter().enumerate() {
579            let set = &mut sets[index];
580            for row in 0..batch.num_rows() {
581                let value = crate::value::cell(column, row);
582                set.insert(value.to_string());
583            }
584        }
585    }
586    Ok(sets)
587}
588
589/// The smallest of two bounds, comparing as JSON numbers when possible.
590fn merge_min(left: Option<Value>, right: Option<Value>) -> Option<Value> {
591    match (left, right) {
592        (None, other) | (other, None) => other,
593        (Some(a), Some(b)) => {
594            let take_a = match (&a, &b) {
595                (Value::Number(x), Value::Number(y)) => {
596                    x.as_f64().unwrap_or(f64::MAX) <= y.as_f64().unwrap_or(f64::MAX)
597                }
598                _ => {
599                    let (a, b) = (a.to_string(), b.to_string());
600                    a <= b
601                }
602            };
603            Some(if take_a { a } else { b })
604        }
605    }
606}
607
608/// The largest of two bounds, comparing as JSON numbers when possible.
609fn merge_max(left: Option<Value>, right: Option<Value>) -> Option<Value> {
610    match (left, right) {
611        (None, other) | (other, None) => other,
612        (Some(a), Some(b)) => {
613            let take_a = match (&a, &b) {
614                (Value::Number(x), Value::Number(y)) => {
615                    x.as_f64().unwrap_or(f64::MIN) >= y.as_f64().unwrap_or(f64::MIN)
616                }
617                _ => {
618                    let (a, b) = (a.to_string(), b.to_string());
619                    a >= b
620                }
621            };
622            Some(if take_a { a } else { b })
623        }
624    }
625}
626
627/// The min and max of a column's statistics.
628fn bounds(statistics: &Statistics) -> (Option<Value>, Option<Value>) {
629    match statistics {
630        Statistics::Boolean(values) => (
631            values.min_opt().map(|v| Value::Bool(*v)),
632            values.max_opt().map(|v| Value::Bool(*v)),
633        ),
634        Statistics::Int32(values) => (
635            values.min_opt().map(|v| json!(v)),
636            values.max_opt().map(|v| json!(v)),
637        ),
638        Statistics::Int64(values) => (
639            values.min_opt().map(|v| json!(v)),
640            values.max_opt().map(|v| json!(v)),
641        ),
642        Statistics::Int96(values) => (
643            values.min_opt().map(|v| json!(v.to_string())),
644            values.max_opt().map(|v| json!(v.to_string())),
645        ),
646        Statistics::Float(values) => (
647            values.min_opt().map(|v| json!(v)),
648            values.max_opt().map(|v| json!(v)),
649        ),
650        Statistics::Double(values) => (
651            values.min_opt().map(|v| json!(v)),
652            values.max_opt().map(|v| json!(v)),
653        ),
654        Statistics::ByteArray(values) => (
655            values.min_opt().map(|v| bytes_value(v.as_bytes())),
656            values.max_opt().map(|v| bytes_value(v.as_bytes())),
657        ),
658        Statistics::FixedLenByteArray(values) => (
659            values.min_opt().map(|v| bytes_value(v.as_bytes())),
660            values.max_opt().map(|v| bytes_value(v.as_bytes())),
661        ),
662    }
663}
664
665/// Bytes as text when they are text, as hex when they are not.
666fn bytes_value(bytes: &[u8]) -> Value {
667    match std::str::from_utf8(bytes) {
668        Ok(text) => Value::String(text.to_string()),
669        Err(_) => Value::String(bytes.iter().map(|b| format!("{b:02x}")).collect()),
670    }
671}