Skip to main content

polars_io/parquet/write/
writer.rs

1use std::io::Write;
2use std::sync::Mutex;
3
4use polars_buffer::Buffer;
5use polars_core::frame::chunk_df_for_writing;
6use polars_core::prelude::*;
7use polars_parquet::arrow::geo::{GEO_KEY, validate_geo_schema};
8use polars_parquet::write::{
9    CompressionOptions, Encoding, FileWriter, StatisticsOptions, Version, WriteOptions,
10    get_dtype_encoding, to_parquet_schema,
11};
12
13use super::batched_writer::BatchedWriter;
14use super::options::ParquetCompression;
15use super::{KeyValueMetadata, ParquetWriteOptions};
16use crate::parquet::encryption::ParquetEncryption;
17use crate::shared::schema_to_arrow_checked;
18
19impl ParquetWriteOptions {
20    pub fn to_writer<F>(&self, f: F) -> ParquetWriter<F>
21    where
22        F: Write,
23    {
24        ParquetWriter::new(f)
25            .with_compression(self.compression)
26            .with_statistics(self.statistics)
27            .with_row_group_size(self.row_group_size)
28            .with_data_page_size(self.data_page_size)
29            .with_key_value_metadata(self.key_value_metadata.clone())
30            .with_encryption(self.encryption.clone())
31    }
32}
33
34/// Write a DataFrame to Parquet format.
35#[must_use]
36pub struct ParquetWriter<W> {
37    writer: W,
38    /// Data page compression
39    compression: CompressionOptions,
40    /// Compute and write column statistics.
41    statistics: StatisticsOptions,
42    /// if `None` will be 512^2 rows
43    row_group_size: Option<usize>,
44    /// if `None` will be 1024^2 bytes
45    data_page_size: Option<usize>,
46    /// Serialize columns in parallel
47    parallel: bool,
48    /// Custom file-level key value metadata
49    key_value_metadata: Option<KeyValueMetadata>,
50    /// Context info for the Parquet file being written.
51    context_info: Option<PlHashMap<String, String>>,
52    /// How to encrypt the file with Parquet modular encryption
53    encryption: Option<ParquetEncryption>,
54}
55
56impl<W> ParquetWriter<W>
57where
58    W: Write,
59{
60    /// Create a new writer
61    pub fn new(writer: W) -> Self
62    where
63        W: Write,
64    {
65        ParquetWriter {
66            writer,
67            compression: ParquetCompression::default().into(),
68            statistics: StatisticsOptions::default(),
69            row_group_size: None,
70            data_page_size: None,
71            parallel: true,
72            key_value_metadata: None,
73            context_info: None,
74            encryption: None,
75        }
76    }
77
78    /// Set the compression used. Defaults to `Zstd`.
79    ///
80    /// The default compression `Zstd` has very good performance, but may not yet been supported
81    /// by older readers. If you want more compatibility guarantees, consider using `Snappy`.
82    pub fn with_compression(mut self, compression: ParquetCompression) -> Self {
83        self.compression = compression.into();
84        self
85    }
86
87    /// Compute and write statistic
88    pub fn with_statistics(mut self, statistics: StatisticsOptions) -> Self {
89        self.statistics = statistics;
90        self
91    }
92
93    /// Set the row group size (in number of rows) during writing. This can reduce memory pressure and improve
94    /// writing performance.
95    pub fn with_row_group_size(mut self, size: Option<usize>) -> Self {
96        self.row_group_size = size;
97        self
98    }
99
100    /// Sets the maximum bytes size of a data page. If `None` will be 1024^2 bytes.
101    pub fn with_data_page_size(mut self, limit: Option<usize>) -> Self {
102        self.data_page_size = limit;
103        self
104    }
105
106    /// Serialize columns in parallel
107    pub fn set_parallel(mut self, parallel: bool) -> Self {
108        self.parallel = parallel;
109        self
110    }
111
112    /// Set custom file-level key value metadata for the Parquet file
113    pub fn with_key_value_metadata(mut self, key_value_metadata: Option<KeyValueMetadata>) -> Self {
114        self.key_value_metadata = key_value_metadata;
115        self
116    }
117
118    /// Set context information for the writer
119    pub fn with_context_info(mut self, context_info: Option<PlHashMap<String, String>>) -> Self {
120        self.context_info = context_info;
121        self
122    }
123
124    /// Set how to encrypt the file with Parquet modular encryption.
125    pub fn with_encryption(mut self, encryption: Option<ParquetEncryption>) -> Self {
126        self.encryption = encryption;
127        self
128    }
129
130    pub fn batched(self, schema: &Schema) -> PolarsResult<BatchedWriter<W>> {
131        let schema = schema_to_arrow_checked(schema, CompatLevel::newest(), "parquet")?;
132        // Metadata that may set its own `geo` key skips the early checks.
133        // errors are only emitted at file end, because that's when the callable's keys are known.
134        if !self
135            .key_value_metadata
136            .as_ref()
137            .is_some_and(|kv| kv.may_contain(GEO_KEY))
138        {
139            validate_geo_schema(&schema)?;
140        }
141        let parquet_schema = to_parquet_schema(&schema)?;
142        let encodings = get_encodings(&schema);
143        let options = self.materialize_options();
144        let encryption_properties = self
145            .encryption
146            .as_ref()
147            .map(ParquetEncryption::file_properties)
148            .transpose()?;
149        let writer = Mutex::new(FileWriter::try_new(
150            self.writer,
151            schema,
152            options,
153            encryption_properties,
154        )?);
155
156        Ok(BatchedWriter {
157            writer,
158            parquet_schema,
159            encodings,
160            options,
161            parallel: self.parallel,
162            key_value_metadata: self.key_value_metadata,
163        })
164    }
165
166    fn materialize_options(&self) -> WriteOptions {
167        WriteOptions {
168            statistics: self.statistics,
169            compression: self.compression,
170            version: Version::V1,
171            data_page_size: self.data_page_size,
172        }
173    }
174
175    /// Write the given DataFrame in the writer `W`.
176    /// Returns the total size of the file.
177    pub fn finish(self, df: &mut DataFrame) -> PolarsResult<u64> {
178        let chunked_df = chunk_df_for_writing(df, self.row_group_size.unwrap_or(512 * 512))?;
179        let mut batched = self.batched(chunked_df.schema())?;
180        batched.write_batch(&chunked_df)?;
181        batched.finish()
182    }
183}
184
185pub fn get_encodings(schema: &ArrowSchema) -> Buffer<Vec<Encoding>> {
186    schema
187        .iter_values()
188        .map(|f| get_dtype_encoding(&f.dtype))
189        .collect()
190}