parquet/arrow/array_reader/mod.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Logic for reading into arrow arrays: [`ArrayReader`] and [`RowGroups`]
19
20use crate::errors::Result;
21use arrow_array::ArrayRef;
22use arrow_schema::DataType as ArrowType;
23use std::any::Any;
24use std::sync::Arc;
25
26use crate::arrow::record_reader::GenericRecordReader;
27use crate::arrow::record_reader::buffer::ValuesBuffer;
28use crate::column::page::PageIterator;
29use crate::column::reader::decoder::ColumnValueDecoder;
30use crate::file::metadata::ParquetMetaData;
31use crate::file::reader::{FilePageIterator, FileReader};
32
33mod builder;
34mod byte_array;
35mod byte_array_dictionary;
36mod byte_view_array;
37mod cached_array_reader;
38mod empty_array;
39mod fixed_len_byte_array;
40mod fixed_size_list_array;
41mod list_array;
42mod map_array;
43mod null_array;
44mod primitive_array;
45mod row_group_cache;
46mod row_number;
47mod struct_array;
48
49#[cfg(test)]
50mod test_util;
51
52// Note that this crate is public under the `experimental` feature flag.
53use crate::file::metadata::RowGroupMetaData;
54pub use builder::{ArrayReaderBuilder, CacheOptions, CacheOptionsBuilder};
55pub use byte_array::make_byte_array_reader;
56pub use byte_array_dictionary::make_byte_array_dictionary_reader;
57#[allow(unused_imports)] // Only used for benchmarks
58pub use byte_view_array::make_byte_view_array_reader;
59#[allow(unused_imports)] // Only used for benchmarks
60pub use fixed_len_byte_array::make_fixed_len_byte_array_reader;
61pub use fixed_size_list_array::FixedSizeListArrayReader;
62pub use list_array::ListArrayReader;
63pub use map_array::MapArrayReader;
64pub use null_array::NullArrayReader;
65pub use primitive_array::PrimitiveArrayReader;
66pub use row_group_cache::RowGroupCache;
67pub use struct_array::StructArrayReader;
68
69/// Reads Parquet data into Arrow Arrays.
70///
71/// This is an internal implementation detail of the Parquet reader, and is not
72/// intended for public use.
73///
74/// This is the core trait for reading encoded Parquet data directly into Arrow
75/// Arrays efficiently. There are various specializations of this trait for
76/// different combinations of encodings and arrays, such as
77/// [`PrimitiveArrayReader`], [`ListArrayReader`], etc.
78///
79/// Each `ArrayReader` logically contains the following state
80/// 1. A handle to the encoded Parquet data
81/// 2. An in progress buffered Array
82///
83/// Data can either be read in batches using [`ArrayReader::next_batch`] or
84/// incrementally using [`ArrayReader::read_records`] and [`ArrayReader::skip_records`].
85pub trait ArrayReader: Send {
86 // TODO: this function is never used, and the trait is not public. Perhaps this should be
87 // removed.
88 #[allow(dead_code)]
89 fn as_any(&self) -> &dyn Any;
90
91 /// Returns the arrow type of this array reader.
92 fn get_data_type(&self) -> &ArrowType;
93
94 /// Reads at most `batch_size` records into an arrow array and return it.
95 #[cfg(any(feature = "experimental", test))]
96 fn next_batch(&mut self, batch_size: usize) -> Result<ArrayRef> {
97 self.read_records(batch_size)?;
98 self.consume_batch()
99 }
100
101 /// Reads at most `batch_size` records' bytes into buffer
102 ///
103 /// Returns the number of records read, which can be less than `batch_size` if
104 /// pages is exhausted.
105 fn read_records(&mut self, batch_size: usize) -> Result<usize>;
106
107 /// Consume all currently stored buffer data
108 /// into an arrow array and return it.
109 fn consume_batch(&mut self) -> Result<ArrayRef>;
110
111 /// Skips over `num_records` records, returning the number of rows skipped
112 ///
113 /// Note that calling `skip_records` with large values of `num_records` is
114 /// efficient as it avoids decoding data into the the in-progress array.
115 /// However, there is overhead to calling this function, so for small values of
116 /// `num_records`, it can be more efficient to call read_records and apply
117 /// a filter to the resulting array.
118 fn skip_records(&mut self, num_records: usize) -> Result<usize>;
119
120 /// If this array has a non-zero definition level, i.e. has a nullable parent
121 /// array, returns the definition levels of data from the last call of `next_batch`
122 ///
123 /// Otherwise returns None
124 ///
125 /// This is used by parent [`ArrayReader`] to compute their null bitmaps
126 fn get_def_levels(&self) -> Option<&[i16]>;
127
128 /// If this array has a non-zero repetition level, i.e. has a repeated parent
129 /// array, returns the repetition levels of data from the last call of `next_batch`
130 ///
131 /// Otherwise returns None
132 ///
133 /// This is used by parent [`ArrayReader`] to compute their array offsets
134 fn get_rep_levels(&self) -> Option<&[i16]>;
135}
136
137/// Interface for reading data pages from the columns of one or more RowGroups.
138pub trait RowGroups {
139 /// Get the number of rows in this collection
140 fn num_rows(&self) -> usize;
141
142 /// Returns a [`PageIterator`] for all pages in the specified column chunk
143 /// across all row groups in this collection.
144 fn column_chunks(&self, i: usize) -> Result<Box<dyn PageIterator>>;
145
146 /// Returns an iterator over the row groups in this collection
147 ///
148 /// Note this may not include all row groups in [`Self::metadata`].
149 fn row_groups(&self) -> Box<dyn Iterator<Item = &RowGroupMetaData> + '_>;
150
151 /// Returns the parquet metadata
152 fn metadata(&self) -> &ParquetMetaData;
153}
154
155impl RowGroups for Arc<dyn FileReader> {
156 fn num_rows(&self) -> usize {
157 FileReader::metadata(self.as_ref())
158 .file_metadata()
159 .num_rows() as usize
160 }
161
162 fn column_chunks(&self, column_index: usize) -> Result<Box<dyn PageIterator>> {
163 let iterator = FilePageIterator::new(column_index, Arc::clone(self))?;
164 Ok(Box::new(iterator))
165 }
166
167 fn row_groups(&self) -> Box<dyn Iterator<Item = &RowGroupMetaData> + '_> {
168 Box::new(FileReader::metadata(self.as_ref()).row_groups().iter())
169 }
170
171 fn metadata(&self) -> &ParquetMetaData {
172 FileReader::metadata(self.as_ref())
173 }
174}
175
176/// Uses `record_reader` to read up to `batch_size` records from `pages`
177///
178/// Returns the number of records read, which can be less than `batch_size` if
179/// pages is exhausted.
180fn read_records<V, CV>(
181 record_reader: &mut GenericRecordReader<V, CV>,
182 pages: &mut dyn PageIterator,
183 batch_size: usize,
184) -> Result<usize>
185where
186 V: ValuesBuffer,
187 CV: ColumnValueDecoder<Buffer = V>,
188{
189 let mut records_read = 0usize;
190 while records_read < batch_size {
191 let records_to_read = batch_size - records_read;
192
193 let records_read_once = record_reader.read_records(records_to_read)?;
194 records_read += records_read_once;
195
196 // Record reader exhausted
197 if records_read_once < records_to_read {
198 if let Some(page_reader) = pages.next() {
199 // Read from new page reader (i.e. column chunk)
200 record_reader.set_page_reader(page_reader?)?;
201 } else {
202 // Page reader also exhausted
203 break;
204 }
205 }
206 }
207 Ok(records_read)
208}
209
210/// Uses `record_reader` to skip up to `batch_size` records from `pages`
211///
212/// Returns the number of records skipped, which can be less than `batch_size` if
213/// pages is exhausted
214fn skip_records<V, CV>(
215 record_reader: &mut GenericRecordReader<V, CV>,
216 pages: &mut dyn PageIterator,
217 batch_size: usize,
218) -> Result<usize>
219where
220 V: ValuesBuffer,
221 CV: ColumnValueDecoder<Buffer = V>,
222{
223 let mut records_skipped = 0usize;
224 while records_skipped < batch_size {
225 let records_to_read = batch_size - records_skipped;
226
227 let records_skipped_once = record_reader.skip_records(records_to_read)?;
228 records_skipped += records_skipped_once;
229
230 // Record reader exhausted
231 if records_skipped_once < records_to_read {
232 if let Some(page_reader) = pages.next() {
233 // Read from new page reader (i.e. column chunk)
234 record_reader.set_page_reader(page_reader?)?;
235 } else {
236 // Page reader also exhausted
237 break;
238 }
239 }
240 }
241 Ok(records_skipped)
242}