nautilus_serialization/
parquet.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::{error::Error, fs::File, path::Path};
17
18use arrow::record_batch::RecordBatch;
19use parquet::{arrow::ArrowWriter, file::properties::WriterProperties};
20
21/// Writes a `RecordBatch` to a Parquet file at the specified `filepath`, with optional compression.
22pub fn write_batch_to_parquet(
23    batch: RecordBatch,
24    filepath: &Path,
25    compression: Option<parquet::basic::Compression>,
26) -> Result<(), Box<dyn Error>> {
27    write_batches_to_parquet(&[batch], filepath, compression, None)
28}
29
30/// Writes a `RecordBatch` to a Parquet file at the specified `filepath`, with optional compression.
31pub fn write_batches_to_parquet(
32    batches: &[RecordBatch],
33    filepath: &Path,
34    compression: Option<parquet::basic::Compression>,
35    max_row_group_size: Option<usize>,
36) -> Result<(), Box<dyn Error>> {
37    // Ensure the parent directory exists
38    if let Some(parent) = filepath.parent() {
39        std::fs::create_dir_all(parent)?;
40    }
41
42    let file = File::create(filepath)?;
43
44    // Configure writer properties, defaulting to Zstandard compression if not specified
45    let default_compression = parquet::basic::Compression::SNAPPY;
46    let writer_props = WriterProperties::builder()
47        .set_compression(compression.unwrap_or(default_compression))
48        .set_max_row_group_size(max_row_group_size.unwrap_or(5000))
49        .build();
50
51    let mut writer = ArrowWriter::try_new(file, batches[0].schema(), Some(writer_props))?;
52    for batch in batches {
53        writer.write(batch)?;
54    }
55    writer.close()?;
56
57    Ok(())
58}