parquet-cli 0.1.9

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,
    by: &str,
    descending: 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)?;

    let key = batch
        .column_by_name(by)
        .cloned()
        .with_context(|| format!("the file has no column named {by}"))?;

    let indices = lexsort_to_indices(
        &[SortColumn {
            values: key,
            options: Some(SortOptions {
                descending,
                nulls_first: true,
            }),
        }],
        None,
    )
    .map_err(|error| anyhow::anyhow!("{error}"))?;
    let sorted = take_record_batch(&batch, &indices).map_err(|error| anyhow::anyhow!("{error}"))?;

    let columns = crate::plan::columns_of(path, &plan, 0)?;
    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)
}