-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathmod.rs
More file actions
5911 lines (5232 loc) · 218 KB
/
Copy pathmod.rs
File metadata and controls
5911 lines (5232 loc) · 218 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Contains reader which reads parquet data into arrow [`RecordBatch`]
use arrow_array::cast::AsArray;
use arrow_array::{Array, RecordBatch, RecordBatchReader};
use arrow_schema::{ArrowError, DataType as ArrowType, FieldRef, Schema, SchemaRef};
use arrow_select::filter::filter_record_batch;
pub use filter::{ArrowPredicate, ArrowPredicateFn, RowFilter};
pub use selection::{
MaskRunIter, RowSelection, RowSelectionCursor, RowSelectionPolicy, RowSelector,
};
use std::fmt::{Debug, Formatter};
use std::sync::Arc;
pub use crate::arrow::array_reader::RowGroups;
use crate::arrow::array_reader::{ArrayReader, ArrayReaderBuilder};
use crate::arrow::schema::{
ParquetField, parquet_to_arrow_schema_and_fields, virtual_type::is_virtual_column,
};
use crate::arrow::{FieldLevels, ProjectionMask, parquet_to_arrow_field_levels_with_virtual};
use crate::basic::{BloomFilterAlgorithm, BloomFilterCompression, BloomFilterHash};
use crate::bloom_filter::{
SBBF_HEADER_SIZE_ESTIMATE, Sbbf, chunk_read_bloom_filter_header_and_offset,
};
use crate::column::page::{PageIterator, PageReader};
#[cfg(feature = "encryption")]
use crate::encryption::decrypt::FileDecryptionProperties;
use crate::errors::{ParquetError, Result};
use crate::file::metadata::{
PageIndexPolicy, ParquetMetaData, ParquetMetaDataOptions, ParquetMetaDataReader,
ParquetStatisticsPolicy, RowGroupMetaData,
};
use crate::file::reader::{ChunkReader, SerializedPageReader};
use crate::schema::types::SchemaDescriptor;
use crate::arrow::arrow_reader::metrics::ArrowReaderMetrics;
// Exposed so integration tests and benchmarks can temporarily override the threshold.
pub use read_plan::{PredicateOptions, ReadPlan, ReadPlanBuilder};
mod filter;
pub mod metrics;
mod read_plan;
pub(crate) mod selection;
pub mod statistics;
/// Default batch size for reading parquet files
pub const DEFAULT_BATCH_SIZE: usize = 1024;
/// Builder for constructing Parquet readers that decode into [Apache Arrow]
/// arrays.
///
/// Most users should use one of the following specializations:
///
/// * synchronous API: [`ParquetRecordBatchReaderBuilder`]
/// * `async` API: [`ParquetRecordBatchStreamBuilder`]
/// * decoder API: [`ParquetPushDecoderBuilder`]
///
/// # Features
/// * Projection pushdown: [`Self::with_projection`]
/// * Cached metadata: [`ArrowReaderMetadata::load`]
/// * Offset skipping: [`Self::with_offset`] and [`Self::with_limit`]
/// * Row group filtering: [`Self::with_row_groups`]
/// * Range filtering: [`Self::with_row_selection`]
/// * Row level filtering: [`Self::with_row_filter`]
///
/// # Implementing Predicate Pushdown
///
/// [`Self::with_row_filter`] permits filter evaluation *during* the decoding
/// process, which is efficient and allows the most low level optimizations.
///
/// However, most Parquet based systems will apply filters at many steps prior
/// to decoding such as pruning files, row groups and data pages. This crate
/// provides the low level APIs needed to implement such filtering, but does not
/// include any logic to actually evaluate predicates. For example:
///
/// * [`Self::with_row_groups`] for Row Group pruning
/// * [`Self::with_row_selection`] for data page pruning
/// * [`StatisticsConverter`] to convert Parquet statistics to Arrow arrays
///
/// The rationale for this design is that implementing predicate pushdown is a
/// complex topic and varies significantly from system to system. For example
///
/// 1. Predicates supported (do you support predicates like prefix matching, user defined functions, etc)
/// 2. Evaluating predicates on multiple files (with potentially different but compatible schemas)
/// 3. Evaluating predicates using information from an external metadata catalog (e.g. Apache Iceberg or similar)
/// 4. Interleaving fetching metadata, evaluating predicates, and decoding files
///
/// You can read more about this design in the [Querying Parquet with
/// Millisecond Latency] Arrow blog post.
///
/// [`ParquetRecordBatchStreamBuilder`]: crate::arrow::async_reader::ParquetRecordBatchStreamBuilder
/// [`ParquetPushDecoderBuilder`]: crate::arrow::push_decoder::ParquetPushDecoderBuilder
/// [Apache Arrow]: https://arrow.apache.org/
/// [`StatisticsConverter`]: statistics::StatisticsConverter
/// [Querying Parquet with Millisecond Latency]: https://arrow.apache.org/blog/2022/12/26/querying-parquet-with-millisecond-latency/
pub struct ArrowReaderBuilder<T> {
/// The "input" to read parquet data from.
///
/// Note in the case of the [`ParquetPushDecoderBuilder`] there is no
/// underlying reader; the input is instead [`PushDecoderInput`], the buffer that
/// caller-pushed bytes accumulate in.
///
/// [`ParquetPushDecoderBuilder`]: crate::arrow::push_decoder::ParquetPushDecoderBuilder
/// [`PushDecoderInput`]: crate::arrow::push_decoder::PushDecoderInput
pub(crate) input: T,
pub(crate) metadata: Arc<ParquetMetaData>,
pub(crate) schema: SchemaRef,
pub(crate) fields: Option<Arc<ParquetField>>,
pub(crate) batch_size: usize,
pub(crate) row_groups: Option<Vec<usize>>,
pub(crate) projection: ProjectionMask,
pub(crate) filter: Option<RowFilter>,
pub(crate) selection: Option<RowSelection>,
pub(crate) row_selection_policy: RowSelectionPolicy,
pub(crate) limit: Option<usize>,
pub(crate) offset: Option<usize>,
pub(crate) metrics: ArrowReaderMetrics,
pub(crate) max_predicate_cache_size: usize,
}
impl<T: Debug> Debug for ArrowReaderBuilder<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ArrowReaderBuilder<T>")
.field("input", &self.input)
.field("metadata", &self.metadata)
.field("schema", &self.schema)
.field("fields", &self.fields)
.field("batch_size", &self.batch_size)
.field("row_groups", &self.row_groups)
.field("projection", &self.projection)
.field("filter", &self.filter)
.field("selection", &self.selection)
.field("row_selection_policy", &self.row_selection_policy)
.field("limit", &self.limit)
.field("offset", &self.offset)
.field("metrics", &self.metrics)
.finish()
}
}
impl<T> ArrowReaderBuilder<T> {
pub(crate) fn new_builder(input: T, metadata: ArrowReaderMetadata) -> Self {
Self {
input,
metadata: metadata.metadata,
schema: metadata.schema,
fields: metadata.fields,
batch_size: DEFAULT_BATCH_SIZE,
row_groups: None,
projection: ProjectionMask::all(),
filter: None,
selection: None,
row_selection_policy: RowSelectionPolicy::default(),
limit: None,
offset: None,
metrics: ArrowReaderMetrics::Disabled,
max_predicate_cache_size: 100 * 1024 * 1024, // 100MB default cache size
}
}
/// Returns a reference to the [`ParquetMetaData`] for this parquet file
pub fn metadata(&self) -> &Arc<ParquetMetaData> {
&self.metadata
}
/// Returns the parquet [`SchemaDescriptor`] for this parquet file
pub fn parquet_schema(&self) -> &SchemaDescriptor {
self.metadata.file_metadata().schema_descr()
}
/// Returns the arrow [`SchemaRef`] for this parquet file
pub fn schema(&self) -> &SchemaRef {
&self.schema
}
/// Set the size of [`RecordBatch`] to produce. Defaults to [`DEFAULT_BATCH_SIZE`]
/// If the batch_size more than the file row count, use the file row count.
pub fn with_batch_size(self, batch_size: usize) -> Self {
// Try to avoid allocate large buffer
let batch_size = batch_size.min(self.metadata.file_metadata().num_rows() as usize);
Self { batch_size, ..self }
}
/// Only read data from the provided row group indexes
///
/// This is also called row group filtering
pub fn with_row_groups(self, row_groups: Vec<usize>) -> Self {
Self {
row_groups: Some(row_groups),
..self
}
}
/// Only read data from the provided column indexes
pub fn with_projection(self, mask: ProjectionMask) -> Self {
Self {
projection: mask,
..self
}
}
/// Configure how row selections should be materialised during execution
///
/// See [`RowSelectionPolicy`] for more details
pub fn with_row_selection_policy(self, policy: RowSelectionPolicy) -> Self {
Self {
row_selection_policy: policy,
..self
}
}
/// Provide a [`RowSelection`] to filter out rows, and avoid fetching their
/// data into memory.
///
/// This feature is used to restrict which rows are decoded within row
/// groups, skipping ranges of rows that are not needed. Such selections
/// could be determined by evaluating predicates against the parquet page
/// [`Index`] or some other external information available to a query
/// engine.
///
/// # Notes
///
/// Row group filtering (see [`Self::with_row_groups`]) is applied prior to
/// applying the row selection, and therefore rows from skipped row groups
/// should not be included in the [`RowSelection`] (see example below)
///
/// It is recommended to enable writing the page index if using this
/// functionality, to allow more efficient skipping over data pages. See
/// [`ArrowReaderOptions::with_page_index`].
///
/// # Example
///
/// Given a parquet file with 4 row groups, and a row group filter of `[0,
/// 2, 3]`, in order to scan rows 50-100 in row group 2 and rows 200-300 in
/// row group 3:
///
/// ```text
/// Row Group 0, 1000 rows (selected)
/// Row Group 1, 1000 rows (skipped)
/// Row Group 2, 1000 rows (selected, but want to only scan rows 50-100)
/// Row Group 3, 1000 rows (selected, but want to only scan rows 200-300)
/// ```
///
/// You could pass the following [`RowSelection`]:
///
/// ```text
/// Select 1000 (scan all rows in row group 0)
/// Skip 50 (skip the first 50 rows in row group 2)
/// Select 50 (scan rows 50-100 in row group 2)
/// Skip 900 (skip the remaining rows in row group 2)
/// Skip 200 (skip the first 200 rows in row group 3)
/// Select 100 (scan rows 200-300 in row group 3)
/// Skip 700 (skip the remaining rows in row group 3)
/// ```
/// Note there is no entry for the (entirely) skipped row group 1.
///
/// Note you can represent the same selection with fewer entries. Instead of
///
/// ```text
/// Skip 900 (skip the remaining rows in row group 2)
/// Skip 200 (skip the first 200 rows in row group 3)
/// ```
///
/// you could use
///
/// ```text
/// Skip 1100 (skip the remaining 900 rows in row group 2 and the first 200 rows in row group 3)
/// ```
///
/// [`Index`]: crate::file::page_index::column_index::ColumnIndexMetaData
pub fn with_row_selection(self, selection: RowSelection) -> Self {
Self {
selection: Some(selection),
..self
}
}
/// Provide a [`RowFilter`] to skip decoding rows
///
/// Row filters are applied after row group selection and row selection
///
/// It is recommended to enable reading the page index if using this functionality, to allow
/// more efficient skipping over data pages. See [`ArrowReaderOptions::with_page_index`].
///
/// See the [blog post on late materialization] for a more technical explanation.
///
/// [blog post on late materialization]: https://arrow.apache.org/blog/2025/12/11/parquet-late-materialization-deep-dive
///
/// # Example
/// ```rust
/// # use std::fs::File;
/// # use arrow_array::Int32Array;
/// # use parquet::arrow::ProjectionMask;
/// # use parquet::arrow::arrow_reader::{ArrowPredicateFn, ParquetRecordBatchReaderBuilder, RowFilter};
/// # fn main() -> Result<(), parquet::errors::ParquetError> {
/// # let testdata = arrow::util::test_util::parquet_test_data();
/// # let path = format!("{testdata}/alltypes_plain.parquet");
/// # let file = File::open(&path)?;
/// let builder = ParquetRecordBatchReaderBuilder::try_new(file)?;
/// let schema_desc = builder.metadata().file_metadata().schema_descr_ptr();
/// // Create predicate that evaluates `int_col != 1`.
/// // `int_col` column has index 4 (zero based) in the schema
/// let projection = ProjectionMask::leaves(&schema_desc, [4]);
/// // Only the projection columns are passed to the predicate so
/// // int_col is column 0 in the predicate
/// let predicate = ArrowPredicateFn::new(projection, |batch| {
/// let int_col = batch.column(0);
/// arrow::compute::kernels::cmp::neq(int_col, &Int32Array::new_scalar(1))
/// });
/// let row_filter = RowFilter::new(vec![Box::new(predicate)]);
/// // The filter will be invoked during the reading process
/// let reader = builder.with_row_filter(row_filter).build()?;
/// # for b in reader { let _ = b?; }
/// # Ok(())
/// # }
/// ```
pub fn with_row_filter(self, filter: RowFilter) -> Self {
Self {
filter: Some(filter),
..self
}
}
/// Provide a limit to the number of rows to be read
///
/// The limit will be applied after any [`Self::with_row_selection`] and [`Self::with_row_filter`]
/// allowing it to limit the final set of rows decoded after any pushed down predicates
///
/// It is recommended to enable reading the page index if using this functionality, to allow
/// more efficient skipping over data pages. See [`ArrowReaderOptions::with_page_index`]
pub fn with_limit(self, limit: usize) -> Self {
Self {
limit: Some(limit),
..self
}
}
/// Provide an offset to skip over the given number of rows
///
/// The offset will be applied after any [`Self::with_row_selection`] and [`Self::with_row_filter`]
/// allowing it to skip rows after any pushed down predicates
///
/// It is recommended to enable reading the page index if using this functionality, to allow
/// more efficient skipping over data pages. See [`ArrowReaderOptions::with_page_index`]
pub fn with_offset(self, offset: usize) -> Self {
Self {
offset: Some(offset),
..self
}
}
/// Specify metrics collection during reading
///
/// To access the metrics, create an [`ArrowReaderMetrics`] and pass a
/// clone of the provided metrics to the builder.
///
/// For example:
///
/// ```rust
/// # use std::sync::Arc;
/// # use bytes::Bytes;
/// # use arrow_array::{Int32Array, RecordBatch};
/// # use arrow_schema::{DataType, Field, Schema};
/// # use parquet::arrow::arrow_reader::{ParquetRecordBatchReader, ParquetRecordBatchReaderBuilder};
/// use parquet::arrow::arrow_reader::metrics::ArrowReaderMetrics;
/// # use parquet::arrow::ArrowWriter;
/// # let mut file: Vec<u8> = Vec::with_capacity(1024);
/// # let schema = Arc::new(Schema::new(vec![Field::new("i32", DataType::Int32, false)]));
/// # let mut writer = ArrowWriter::try_new(&mut file, schema.clone(), None).unwrap();
/// # let batch = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![1, 2, 3]))]).unwrap();
/// # writer.write(&batch).unwrap();
/// # writer.close().unwrap();
/// # let file = Bytes::from(file);
/// // Create metrics object to pass into the reader
/// let metrics = ArrowReaderMetrics::enabled();
/// let reader = ParquetRecordBatchReaderBuilder::try_new(file).unwrap()
/// // Configure the builder to use the metrics by passing a clone
/// .with_metrics(metrics.clone())
/// // Build the reader
/// .build().unwrap();
/// // .. read data from the reader ..
///
/// // check the metrics
/// assert!(metrics.records_read_from_inner().is_some());
/// ```
pub fn with_metrics(self, metrics: ArrowReaderMetrics) -> Self {
Self { metrics, ..self }
}
/// Set the maximum size (per row group) of the predicate cache in bytes for
/// the async decoder.
///
/// Defaults to 100MB (across all columns). Set to `usize::MAX` to use
/// unlimited cache size.
///
/// This cache is used to store decoded arrays that are used in
/// predicate evaluation ([`Self::with_row_filter`]).
///
/// This cache is only used for the "async" decoder, [`ParquetRecordBatchStream`]. See
/// [this ticket] for more details and alternatives.
///
/// [`ParquetRecordBatchStream`]: https://docs.rs/parquet/latest/parquet/arrow/async_reader/struct.ParquetRecordBatchStream.html
/// [this ticket]: https://github.com/apache/arrow-rs/issues/8000
pub fn with_max_predicate_cache_size(self, max_predicate_cache_size: usize) -> Self {
Self {
max_predicate_cache_size,
..self
}
}
}
/// Options that control how [`ParquetMetaData`] is read when constructing
/// an Arrow reader.
///
/// To use these options, pass them to one of the following methods:
/// * [`ParquetRecordBatchReaderBuilder::try_new_with_options`]
/// * [`ParquetRecordBatchStreamBuilder::new_with_options`]
///
/// For fine-grained control over metadata loading, use
/// [`ArrowReaderMetadata::load`] to load metadata with these options,
///
/// See [`ArrowReaderBuilder`] for how to configure how the column data
/// is then read from the file, including projection and filter pushdown
///
/// [`ParquetRecordBatchStreamBuilder::new_with_options`]: crate::arrow::async_reader::ParquetRecordBatchStreamBuilder::new_with_options
#[derive(Debug, Clone, Default)]
pub struct ArrowReaderOptions {
/// Should the reader strip any user defined metadata from the Arrow schema
skip_arrow_metadata: bool,
/// If provided, used as the schema hint when determining the Arrow schema,
/// otherwise the schema hint is read from the [ARROW_SCHEMA_META_KEY]
///
/// [ARROW_SCHEMA_META_KEY]: crate::arrow::ARROW_SCHEMA_META_KEY
supplied_schema: Option<SchemaRef>,
pub(crate) column_index: PageIndexPolicy,
pub(crate) offset_index: PageIndexPolicy,
/// Options to control reading of Parquet metadata
metadata_options: ParquetMetaDataOptions,
/// If encryption is enabled, the file decryption properties can be provided
#[cfg(feature = "encryption")]
pub(crate) file_decryption_properties: Option<Arc<FileDecryptionProperties>>,
virtual_columns: Vec<FieldRef>,
}
impl ArrowReaderOptions {
/// Create a new [`ArrowReaderOptions`] with the default settings
pub fn new() -> Self {
Self::default()
}
/// Skip decoding the embedded arrow metadata (defaults to `false`)
///
/// Parquet files generated by some writers may contain embedded arrow
/// schema and metadata.
/// This may not be correct or compatible with your system,
/// for example, see [ARROW-16184](https://issues.apache.org/jira/browse/ARROW-16184)
pub fn with_skip_arrow_metadata(self, skip_arrow_metadata: bool) -> Self {
Self {
skip_arrow_metadata,
..self
}
}
/// Provide a schema hint to use when reading the Parquet file.
///
/// If provided, this schema takes precedence over any arrow schema embedded
/// in the metadata (see the [`arrow`] documentation for more details).
///
/// If the provided schema is not compatible with the data stored in the
/// parquet file schema, an error will be returned when constructing the
/// builder.
///
/// This option is only required if you want to explicitly control the
/// conversion of Parquet types to Arrow types, such as casting a column to
/// a different type. For example, if you wanted to read an Int64 in
/// a Parquet file to a [`TimestampMicrosecondArray`] in the Arrow schema.
///
/// [`arrow`]: crate::arrow
/// [`TimestampMicrosecondArray`]: arrow_array::TimestampMicrosecondArray
///
/// # Notes
///
/// The provided schema must have the same number of columns as the parquet schema and
/// the column names must be the same.
///
/// # Example
/// ```
/// # use std::sync::Arc;
/// # use bytes::Bytes;
/// # use arrow_array::{ArrayRef, Int32Array, RecordBatch};
/// # use arrow_schema::{DataType, Field, Schema, TimeUnit};
/// # use parquet::arrow::arrow_reader::{ArrowReaderOptions, ParquetRecordBatchReaderBuilder};
/// # use parquet::arrow::ArrowWriter;
/// // Write data - schema is inferred from the data to be Int32
/// let mut file = Vec::new();
/// let batch = RecordBatch::try_from_iter(vec![
/// ("col_1", Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef),
/// ]).unwrap();
/// let mut writer = ArrowWriter::try_new(&mut file, batch.schema(), None).unwrap();
/// writer.write(&batch).unwrap();
/// writer.close().unwrap();
/// let file = Bytes::from(file);
///
/// // Read the file back.
/// // Supply a schema that interprets the Int32 column as a Timestamp.
/// let supplied_schema = Arc::new(Schema::new(vec![
/// Field::new("col_1", DataType::Timestamp(TimeUnit::Nanosecond, None), false)
/// ]));
/// let options = ArrowReaderOptions::new().with_schema(supplied_schema.clone());
/// let mut builder = ParquetRecordBatchReaderBuilder::try_new_with_options(
/// file.clone(),
/// options
/// ).expect("Error if the schema is not compatible with the parquet file schema.");
///
/// // Create the reader and read the data using the supplied schema.
/// let mut reader = builder.build().unwrap();
/// let _batch = reader.next().unwrap().unwrap();
/// ```
///
/// # Example: Preserving Dictionary Encoding
///
/// By default, Parquet string columns are read as `Utf8Array` (or `LargeUtf8Array`),
/// even if the underlying Parquet data uses dictionary encoding. You can preserve
/// the dictionary encoding by specifying a `Dictionary` type in the schema hint:
///
/// ```
/// # use std::sync::Arc;
/// # use bytes::Bytes;
/// # use arrow_array::{ArrayRef, RecordBatch, StringArray};
/// # use arrow_schema::{DataType, Field, Schema};
/// # use parquet::arrow::arrow_reader::{ArrowReaderOptions, ParquetRecordBatchReaderBuilder};
/// # use parquet::arrow::ArrowWriter;
/// // Write a Parquet file with string data
/// let mut file = Vec::new();
/// let schema = Arc::new(Schema::new(vec![
/// Field::new("city", DataType::Utf8, false)
/// ]));
/// let cities = StringArray::from(vec!["Berlin", "Berlin", "Paris", "Berlin", "Paris"]);
/// let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(cities)]).unwrap();
///
/// let mut writer = ArrowWriter::try_new(&mut file, batch.schema(), None).unwrap();
/// writer.write(&batch).unwrap();
/// writer.close().unwrap();
/// let file = Bytes::from(file);
///
/// // Read the file back, requesting dictionary encoding preservation
/// let dict_schema = Arc::new(Schema::new(vec![
/// Field::new("city", DataType::Dictionary(
/// Box::new(DataType::Int32),
/// Box::new(DataType::Utf8)
/// ), false)
/// ]));
/// let options = ArrowReaderOptions::new().with_schema(dict_schema);
/// let builder = ParquetRecordBatchReaderBuilder::try_new_with_options(
/// file.clone(),
/// options
/// ).unwrap();
///
/// let mut reader = builder.build().unwrap();
/// let batch = reader.next().unwrap().unwrap();
///
/// // The column is now a DictionaryArray
/// assert!(matches!(
/// batch.column(0).data_type(),
/// DataType::Dictionary(_, _)
/// ));
/// ```
///
/// **Note**: Dictionary encoding preservation works best when:
/// 1. The original column was dictionary encoded (the default for string columns)
/// 2. There are a small number of distinct values
pub fn with_schema(self, schema: SchemaRef) -> Self {
Self {
supplied_schema: Some(schema),
skip_arrow_metadata: true,
..self
}
}
#[deprecated(since = "57.2.0", note = "Use `with_page_index_policy` instead")]
/// Enable reading the [`PageIndex`] from the metadata, if present (defaults to `false`)
///
/// The `PageIndex` can be used to push down predicates to the parquet scan,
/// potentially eliminating unnecessary IO, by some query engines.
///
/// If this is enabled, [`ParquetMetaData::column_index`] and
/// [`ParquetMetaData::offset_index`] will be populated if the corresponding
/// information is present in the file.
///
/// [`PageIndex`]: https://github.com/apache/parquet-format/blob/master/PageIndex.md
/// [`ParquetMetaData::column_index`]: crate::file::metadata::ParquetMetaData::column_index
/// [`ParquetMetaData::offset_index`]: crate::file::metadata::ParquetMetaData::offset_index
pub fn with_page_index(self, page_index: bool) -> Self {
self.with_page_index_policy(PageIndexPolicy::from(page_index))
}
/// Sets the [`PageIndexPolicy`] for both the column and offset indexes.
///
/// The `PageIndex` consists of two structures: the `ColumnIndex` and `OffsetIndex`.
/// This method sets the same policy for both. For fine-grained control, use
/// [`Self::with_column_index_policy`] and [`Self::with_offset_index_policy`].
///
/// See [`Self::with_page_index`] for more details on page indexes.
pub fn with_page_index_policy(self, policy: PageIndexPolicy) -> Self {
self.with_column_index_policy(policy)
.with_offset_index_policy(policy)
}
/// Sets the [`PageIndexPolicy`] for the Parquet [ColumnIndex] structure.
///
/// The `ColumnIndex` contains min/max statistics for each page, which can be used
/// for predicate pushdown and page-level pruning.
///
/// [ColumnIndex]: https://github.com/apache/parquet-format/blob/master/PageIndex.md
pub fn with_column_index_policy(mut self, policy: PageIndexPolicy) -> Self {
self.column_index = policy;
self
}
/// Sets the [`PageIndexPolicy`] for the Parquet [OffsetIndex] structure.
///
/// The `OffsetIndex` contains the locations and sizes of each page, which enables
/// efficient page-level skipping and random access within column chunks.
///
/// [OffsetIndex]: https://github.com/apache/parquet-format/blob/master/PageIndex.md
pub fn with_offset_index_policy(mut self, policy: PageIndexPolicy) -> Self {
self.offset_index = policy;
self
}
/// Provide a Parquet schema to use when decoding the metadata. The schema in the Parquet
/// footer will be skipped.
///
/// This can be used to avoid reparsing the schema from the file when it is
/// already known.
pub fn with_parquet_schema(mut self, schema: Arc<SchemaDescriptor>) -> Self {
self.metadata_options.set_schema(schema);
self
}
/// Set whether to convert the [`encoding_stats`] in the Parquet `ColumnMetaData` to a bitmask
/// (defaults to `false`).
///
/// See [`ColumnChunkMetaData::page_encoding_stats_mask`] for an explanation of why this
/// might be desirable.
///
/// [`ColumnChunkMetaData::page_encoding_stats_mask`]:
/// crate::file::metadata::ColumnChunkMetaData::page_encoding_stats_mask
/// [`encoding_stats`]:
/// https://github.com/apache/parquet-format/blob/786142e26740487930ddc3ec5e39d780bd930907/src/main/thrift/parquet.thrift#L917
pub fn with_encoding_stats_as_mask(mut self, val: bool) -> Self {
self.metadata_options.set_encoding_stats_as_mask(val);
self
}
/// Sets the decoding policy for [`encoding_stats`] in the Parquet `ColumnMetaData`.
///
/// [`encoding_stats`]:
/// https://github.com/apache/parquet-format/blob/786142e26740487930ddc3ec5e39d780bd930907/src/main/thrift/parquet.thrift#L917
pub fn with_encoding_stats_policy(mut self, policy: ParquetStatisticsPolicy) -> Self {
self.metadata_options.set_encoding_stats_policy(policy);
self
}
/// Sets the decoding policy for [`statistics`] in the Parquet `ColumnMetaData`.
///
/// [`statistics`]:
/// https://github.com/apache/parquet-format/blob/786142e26740487930ddc3ec5e39d780bd930907/src/main/thrift/parquet.thrift#L912
pub fn with_column_stats_policy(mut self, policy: ParquetStatisticsPolicy) -> Self {
self.metadata_options.set_column_stats_policy(policy);
self
}
/// Sets the decoding policy for [`size_statistics`] in the Parquet `ColumnMetaData`.
///
/// [`size_statistics`]:
/// https://github.com/apache/parquet-format/blob/786142e26740487930ddc3ec5e39d780bd930907/src/main/thrift/parquet.thrift#L936
pub fn with_size_stats_policy(mut self, policy: ParquetStatisticsPolicy) -> Self {
self.metadata_options.set_size_stats_policy(policy);
self
}
/// Provide the file decryption properties to use when reading encrypted parquet files.
///
/// If encryption is enabled and the file is encrypted, the `file_decryption_properties` must be provided.
#[cfg(feature = "encryption")]
pub fn with_file_decryption_properties(
self,
file_decryption_properties: Arc<FileDecryptionProperties>,
) -> Self {
Self {
file_decryption_properties: Some(file_decryption_properties),
..self
}
}
/// Include virtual columns in the output.
///
/// Virtual columns are columns that are not part of the Parquet schema, but are added to the output by the reader such as row numbers and row group indices.
///
/// # Example
/// ```
/// # use std::sync::Arc;
/// # use bytes::Bytes;
/// # use arrow_array::{ArrayRef, Int64Array, RecordBatch};
/// # use arrow_schema::{DataType, Field, Schema};
/// # use parquet::arrow::{ArrowWriter, RowNumber};
/// # use parquet::arrow::arrow_reader::{ArrowReaderOptions, ParquetRecordBatchReaderBuilder};
/// #
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a simple record batch with some data
/// let values = Arc::new(Int64Array::from(vec![1, 2, 3])) as ArrayRef;
/// let batch = RecordBatch::try_from_iter(vec![("value", values)])?;
///
/// // Write the batch to an in-memory buffer
/// let mut file = Vec::new();
/// let mut writer = ArrowWriter::try_new(
/// &mut file,
/// batch.schema(),
/// None
/// )?;
/// writer.write(&batch)?;
/// writer.close()?;
/// let file = Bytes::from(file);
///
/// // Create a virtual column for row numbers
/// let row_number_field = Arc::new(Field::new("row_number", DataType::Int64, false)
/// .with_extension_type(RowNumber));
///
/// // Configure options with virtual columns
/// let options = ArrowReaderOptions::new()
/// .with_virtual_columns(vec![row_number_field])?;
///
/// // Create a reader with the options
/// let mut reader = ParquetRecordBatchReaderBuilder::try_new_with_options(
/// file,
/// options
/// )?
/// .build()?;
///
/// // Read the batch - it will include both the original column and the virtual row_number column
/// let result_batch = reader.next().unwrap()?;
/// assert_eq!(result_batch.num_columns(), 2); // "value" + "row_number"
/// assert_eq!(result_batch.num_rows(), 3);
/// #
/// # Ok(())
/// # }
/// ```
pub fn with_virtual_columns(self, virtual_columns: Vec<FieldRef>) -> Result<Self> {
// Validate that all fields are virtual columns
for field in &virtual_columns {
if !is_virtual_column(field) {
return Err(ParquetError::General(format!(
"Field '{}' is not a virtual column. Virtual columns must have extension type names starting with 'arrow.virtual.'",
field.name()
)));
}
}
Ok(Self {
virtual_columns,
..self
})
}
#[deprecated(
since = "57.2.0",
note = "Use `column_index_policy` or `offset_index_policy` instead"
)]
/// Returns whether page index reading is enabled.
///
/// This returns `true` if both the column index and offset index policies are not [`PageIndexPolicy::Skip`].
///
/// This can be set via [`with_page_index`][Self::with_page_index] or
/// [`with_page_index_policy`][Self::with_page_index_policy].
pub fn page_index(&self) -> bool {
self.offset_index != PageIndexPolicy::Skip && self.column_index != PageIndexPolicy::Skip
}
/// Retrieve the currently set [`PageIndexPolicy`] for the offset index.
///
/// This can be set via [`with_offset_index_policy`][Self::with_offset_index_policy]
/// or [`with_page_index_policy`][Self::with_page_index_policy].
pub fn offset_index_policy(&self) -> PageIndexPolicy {
self.offset_index
}
/// Retrieve the currently set [`PageIndexPolicy`] for the column index.
///
/// This can be set via [`with_column_index_policy`][Self::with_column_index_policy]
/// or [`with_page_index_policy`][Self::with_page_index_policy].
pub fn column_index_policy(&self) -> PageIndexPolicy {
self.column_index
}
/// Retrieve the currently set metadata decoding options.
pub fn metadata_options(&self) -> &ParquetMetaDataOptions {
&self.metadata_options
}
/// Retrieve the currently set file decryption properties.
///
/// This can be set via
/// [`file_decryption_properties`][Self::with_file_decryption_properties].
#[cfg(feature = "encryption")]
pub fn file_decryption_properties(&self) -> Option<&Arc<FileDecryptionProperties>> {
self.file_decryption_properties.as_ref()
}
}
/// The metadata necessary to construct a [`ArrowReaderBuilder`]
///
/// Note this structure is cheaply clone-able as it consists of several arcs.
///
/// This structure allows
///
/// 1. Loading metadata for a file once and then using that same metadata to
/// construct multiple separate readers, for example, to distribute readers
/// across multiple threads
///
/// 2. Using a cached copy of the [`ParquetMetadata`] rather than reading it
/// from the file each time a reader is constructed.
///
/// [`ParquetMetadata`]: crate::file::metadata::ParquetMetaData
#[derive(Debug, Clone)]
pub struct ArrowReaderMetadata {
/// The Parquet Metadata, if known aprior
pub(crate) metadata: Arc<ParquetMetaData>,
/// The Arrow Schema
pub(crate) schema: SchemaRef,
/// The Parquet schema (root field)
pub(crate) fields: Option<Arc<ParquetField>>,
}
impl ArrowReaderMetadata {
/// Create [`ArrowReaderMetadata`] from the provided [`ArrowReaderOptions`]
/// and [`ChunkReader`]
///
/// See [`ParquetRecordBatchReaderBuilder::new_with_metadata`] for an
/// example of how this can be used
///
/// # Notes
///
/// If `options` has [`ArrowReaderOptions::with_page_index`] true, but
/// `Self::metadata` is missing the page index, this function will attempt
/// to load the page index by making an object store request.
pub fn load<T: ChunkReader>(reader: &T, options: ArrowReaderOptions) -> Result<Self> {
let metadata = ParquetMetaDataReader::new()
.with_column_index_policy(options.column_index)
.with_offset_index_policy(options.offset_index)
.with_metadata_options(Some(options.metadata_options.clone()));
#[cfg(feature = "encryption")]
let metadata = metadata.with_decryption_properties(
options.file_decryption_properties.as_ref().map(Arc::clone),
);
let metadata = metadata.parse_and_finish(reader)?;
Self::try_new(Arc::new(metadata), options)
}
/// Create a new [`ArrowReaderMetadata`] from a pre-existing
/// [`ParquetMetaData`] and [`ArrowReaderOptions`].
///
/// # Notes
///
/// This function will not attempt to load the PageIndex if not present in the metadata, regardless
/// of the settings in `options`. See [`Self::load`] to load metadata including the page index if needed.
pub fn try_new(metadata: Arc<ParquetMetaData>, options: ArrowReaderOptions) -> Result<Self> {
match options.supplied_schema {
Some(supplied_schema) => Self::with_supplied_schema(
metadata,
supplied_schema.clone(),
&options.virtual_columns,
),
None => {
let kv_metadata = match options.skip_arrow_metadata {
true => None,
false => metadata.file_metadata().key_value_metadata(),
};
let (schema, fields) = parquet_to_arrow_schema_and_fields(
metadata.file_metadata().schema_descr(),
ProjectionMask::all(),
kv_metadata,
&options.virtual_columns,
)?;
Ok(Self {
metadata,
schema: Arc::new(schema),
fields: fields.map(Arc::new),
})
}
}
}
fn with_supplied_schema(
metadata: Arc<ParquetMetaData>,
supplied_schema: SchemaRef,
virtual_columns: &[FieldRef],
) -> Result<Self> {
let parquet_schema = metadata.file_metadata().schema_descr();
let field_levels = parquet_to_arrow_field_levels_with_virtual(
parquet_schema,
ProjectionMask::all(),
Some(supplied_schema.fields()),
virtual_columns,
)?;
let fields = field_levels.fields;
let inferred_len = fields.len();
let supplied_len = supplied_schema.fields().len() + virtual_columns.len();
// Ensure the supplied schema has the same number of columns as the parquet schema.
// parquet_to_arrow_field_levels is expected to throw an error if the schemas have
// different lengths, but we check here to be safe.
if inferred_len != supplied_len {
return Err(arrow_err!(format!(
"Incompatible supplied Arrow schema: expected {} columns received {}",
inferred_len, supplied_len
)));
}
let mut errors = Vec::new();
let field_iter = supplied_schema.fields().iter().zip(fields.iter());
for (field1, field2) in field_iter {
if field1.data_type() != field2.data_type() {
errors.push(format!(
"data type mismatch for field {}: requested {} but found {}",
field1.name(),
field1.data_type(),
field2.data_type()
));
}
if field1.is_nullable() != field2.is_nullable() {
errors.push(format!(
"nullability mismatch for field {}: expected {:?} but found {:?}",
field1.name(),
field1.is_nullable(),
field2.is_nullable()
));
}
if field1.metadata() != field2.metadata() {
errors.push(format!(
"metadata mismatch for field {}: expected {:?} but found {:?}",
field1.name(),
field1.metadata(),
field2.metadata()
));
}
}
if !errors.is_empty() {
let message = errors.join(", ");
return Err(ParquetError::ArrowError(format!(
"Incompatible supplied Arrow schema: {message}",
)));
}
Ok(Self {
metadata,
schema: supplied_schema,
fields: field_levels.levels.map(Arc::new),
})
}
/// Returns a reference to the [`ParquetMetaData`] for this parquet file
pub fn metadata(&self) -> &Arc<ParquetMetaData> {
&self.metadata
}