parquet-cli 0.3.0

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
Documentation
//! Writing a file again, sorted by a key.
//!
//! Sorting is the cheapest thing a writer can do for the reader: when the rows
//! are in order, the min and max of every row group say something, so a
//! reader can skip the row groups it does not need. It is also worth bytes:
//! the same values in order compress better.
//!
//! The sort happens in memory, so this is for files that fit.

use std::fs::File;
use std::path::Path;

use anyhow::{Context, Result};
use arrow_array::RecordBatch;
use arrow_ord::sort::{lexsort_to_indices, SortColumn, SortOptions};
use arrow_select::concat::concat_batches;
use arrow_select::take::take_record_batch;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::arrow::arrow_writer::ArrowWriter;

use crate::plan::Plan;

/// Read a file, sort it by a column, and write it again.
///
/// Returns how many bytes the new file takes.
pub fn sort_file(path: &Path, keys: &[(String, bool)], out: &Path, wanted: &Plan) -> Result<u64> {
    // The new file starts from the settings the old one was written with.
    let facts = crate::meta::file_facts(path)?;
    let mut plan = crate::bench::baseline(&facts);
    plan.merge(wanted);

    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
        .with_context(|| format!("read the footer of {}", path.display()))?;
    let schema = builder.schema().clone();

    let mut batches: Vec<RecordBatch> = Vec::new();
    for batch in builder.build()? {
        batches.push(batch?);
    }
    let batch = concat_batches(&schema, &batches)?;

    // The keys, in order: the first one is the primary key.
    let mut columns = Vec::new();
    for (name, descending) in keys {
        let values = batch
            .column_by_name(name)
            .cloned()
            .with_context(|| format!("the file has no column named {name}"))?;
        columns.push(SortColumn {
            values,
            options: Some(SortOptions {
                descending: *descending,
                nulls_first: true,
            }),
        });
    }
    if columns.is_empty() {
        anyhow::bail!("say what to sort by");
    }

    let indices = lexsort_to_indices(&columns, None).map_err(|error| anyhow::anyhow!("{error}"))?;
    let sorted = take_record_batch(&batch, &indices).map_err(|error| anyhow::anyhow!("{error}"))?;

    // The plan may want to know how many different values each column has.
    let distinct = crate::plan::distinct_of_batch(&sorted);
    let columns: Vec<crate::plan::Column> = sorted
        .schema()
        .fields()
        .iter()
        .enumerate()
        .map(|(index, field)| crate::plan::Column {
            name: field.name().clone(),
            distinct: distinct.get(index).map(|count| *count as u64),
            rows: sorted.num_rows() as i64,
        })
        .collect();
    let properties = plan.writer_properties(&columns)?;

    let output = File::create(out).with_context(|| format!("create {}", out.display()))?;
    let mut writer =
        ArrowWriter::try_new(output, schema, Some(properties)).context("open the writer")?;
    writer.write(&sorted)?;
    writer.close()?;

    let size = std::fs::metadata(out)?.len();
    Ok(size)
}