Skip to main content

polars_io/parquet/read/
mmap.rs

1use std::io::Cursor;
2
3use polars_arrow::array::{Array, DictionaryArray};
4use polars_arrow::bitmap::Bitmap;
5use polars_arrow::datatypes::Field;
6use polars_buffer::Buffer;
7use polars_error::PolarsResult;
8use polars_parquet::read::{
9    BasicDecompressor, ColumnChunkMetadata, Filter, PageReader, PhysicalType,
10    column_iter_to_arrays, decode_dictionary_codes,
11};
12use polars_utils::mem::prefetch::prefetch_l2;
13
14/// Store columns data in two scenarios:
15/// 1. a local memory mapped file
16/// 2. data fetched from cloud storage on demand, in this case
17///    a. the key in the hashmap is the start in the file
18///    b. the value in the hashmap is the actual data.
19///
20/// For the fetched case we use a two phase approach:
21///   a. identify all the needed columns
22///   b. asynchronously fetch them in parallel, for example using object_store
23///   c. store the data in this data structure
24///   d. when all the data is available deserialize on multiple threads, for example using rayon
25pub enum ColumnStore {
26    Local(Buffer<u8>),
27}
28
29/// For local files memory maps all columns that are part of the parquet field `field_name`.
30/// For cloud files the relevant memory regions should have been prefetched.
31pub(super) fn mmap_columns<'a>(
32    store: &'a ColumnStore,
33    field_columns: &'a [&ColumnChunkMetadata],
34) -> PolarsResult<Vec<(&'a ColumnChunkMetadata, Buffer<u8>)>> {
35    field_columns
36        .iter()
37        .map(|meta| _mmap_single_column(store, meta))
38        .collect()
39}
40
41fn _mmap_single_column<'a>(
42    store: &'a ColumnStore,
43    meta: &'a ColumnChunkMetadata,
44) -> PolarsResult<(&'a ColumnChunkMetadata, Buffer<u8>)> {
45    let byte_range = meta.byte_range()?;
46    let chunk = match store {
47        ColumnStore::Local(mem_slice) => mem_slice
48            .clone()
49            .sliced(byte_range.start as usize..byte_range.end as usize),
50    };
51    Ok((meta, chunk))
52}
53
54// similar to arrow2 serializer, except this accepts a slice instead of a vec.
55// this allows us to memory map
56pub fn to_deserializer(
57    columns: Vec<(&ColumnChunkMetadata, Buffer<u8>)>,
58    field: Field,
59    filter: Option<Filter>,
60) -> PolarsResult<(Vec<Box<dyn Array>>, Bitmap)> {
61    let (columns, types) = columns
62        .into_iter()
63        .map(|(column_meta, chunk)| {
64            // Advise fetching the data for the column chunk
65            prefetch_l2(&chunk);
66
67            let pages = PageReader::new(Cursor::new(chunk), column_meta, vec![], usize::MAX)?;
68            PolarsResult::Ok((
69                BasicDecompressor::new(pages, vec![]),
70                &column_meta.descriptor().descriptor.primitive_type,
71            ))
72        })
73        .collect::<PolarsResult<(Vec<_>, Vec<_>)>>()?;
74
75    column_iter_to_arrays(columns, types, field, filter)
76}
77
78/// Decodes a flat String column chunk as codes into its dictionary, if it has a dictionary page,
79/// every data page is dictionary-encoded and `accept(num_rows, dict_len, dict_bytes)` holds for
80/// the number of rows the filter keeps (all of the chunk's for a predicate, whose result isn't
81/// known yet) and the number and uncompressed size of the dictionary values.
82/// Returns `None` otherwise, without decoding anything.
83pub fn to_dictionary_codes(
84    column_meta: &ColumnChunkMetadata,
85    chunk: Buffer<u8>,
86    field_name: &str,
87    filter: Option<Filter>,
88    accept: impl FnOnce(usize, usize, usize) -> bool,
89) -> PolarsResult<Option<(Vec<DictionaryArray<u32>>, Bitmap)>> {
90    // Only a BYTE_ARRAY column's dictionary holds length-prefixed strings.
91    if column_meta
92        .descriptor()
93        .descriptor
94        .primitive_type
95        .physical_type
96        != PhysicalType::ByteArray
97    {
98        return Ok(None);
99    }
100    let pages = PageReader::new(Cursor::new(chunk.clone()), column_meta, vec![], usize::MAX)?;
101    let num_rows = match &filter {
102        Some(Filter::Range(range)) => range.len().min(pages.total_num_values()),
103        Some(Filter::Mask(mask)) => mask.set_bits(),
104        Some(Filter::Predicate(_)) | None => pages.total_num_values(),
105    };
106    match pages.dictionary_only_len()? {
107        Some((dict_len, dict_bytes)) if accept(num_rows, dict_len, dict_bytes) => {},
108        _ => return Ok(None),
109    }
110
111    prefetch_l2(&chunk);
112    let pages = PageReader::new(Cursor::new(chunk), column_meta, vec![], usize::MAX)?;
113    let decoded =
114        decode_dictionary_codes(field_name, BasicDecompressor::new(pages, vec![]), filter)?;
115    Ok(Some(decoded))
116}