Skip to main content

parquet_cli/
sort.rs

1//! Writing a file again, sorted by a key.
2//!
3//! Sorting is the cheapest thing a writer can do for the reader: when the rows
4//! are in order, the min and max of every row group say something, so a
5//! reader can skip the row groups it does not need. It is also worth bytes:
6//! the same values in order compress better.
7//!
8//! The sort happens in memory, so this is for files that fit.
9
10use std::fs::File;
11use std::path::Path;
12
13use anyhow::{Context, Result};
14use arrow_array::RecordBatch;
15use arrow_ord::sort::{lexsort_to_indices, SortColumn, SortOptions};
16use arrow_select::concat::concat_batches;
17use arrow_select::take::take_record_batch;
18use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
19use parquet::arrow::arrow_writer::ArrowWriter;
20
21use crate::plan::Plan;
22
23/// Read a file, sort it by a column, and write it again.
24///
25/// Returns how many bytes the new file takes.
26pub fn sort_file(path: &Path, keys: &[(String, bool)], out: &Path, wanted: &Plan) -> Result<u64> {
27    // The new file starts from the settings the old one was written with.
28    let facts = crate::meta::file_facts(path)?;
29    let mut plan = crate::bench::baseline(&facts);
30    plan.merge(wanted);
31
32    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
33    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
34        .with_context(|| format!("read the footer of {}", path.display()))?;
35    let schema = builder.schema().clone();
36
37    let mut batches: Vec<RecordBatch> = Vec::new();
38    for batch in builder.build()? {
39        batches.push(batch?);
40    }
41    let batch = concat_batches(&schema, &batches)?;
42
43    // The keys, in order: the first one is the primary key.
44    let mut columns = Vec::new();
45    for (name, descending) in keys {
46        let values = batch
47            .column_by_name(name)
48            .cloned()
49            .with_context(|| format!("the file has no column named {name}"))?;
50        columns.push(SortColumn {
51            values,
52            options: Some(SortOptions {
53                descending: *descending,
54                nulls_first: true,
55            }),
56        });
57    }
58    if columns.is_empty() {
59        anyhow::bail!("say what to sort by");
60    }
61
62    let indices = lexsort_to_indices(&columns, None).map_err(|error| anyhow::anyhow!("{error}"))?;
63    let sorted = take_record_batch(&batch, &indices).map_err(|error| anyhow::anyhow!("{error}"))?;
64
65    // The plan may want to know how many different values each column has.
66    let distinct = crate::plan::distinct_of_batch(&sorted);
67    let columns: Vec<crate::plan::Column> = sorted
68        .schema()
69        .fields()
70        .iter()
71        .enumerate()
72        .map(|(index, field)| crate::plan::Column {
73            name: field.name().clone(),
74            distinct: distinct.get(index).map(|count| *count as u64),
75            rows: sorted.num_rows() as i64,
76        })
77        .collect();
78    let properties = plan.writer_properties(&columns)?;
79
80    let output = File::create(out).with_context(|| format!("create {}", out.display()))?;
81    let mut writer =
82        ArrowWriter::try_new(output, schema, Some(properties)).context("open the writer")?;
83    writer.write(&sorted)?;
84    writer.close()?;
85
86    let size = std::fs::metadata(out)?.len();
87    Ok(size)
88}