abedegno commented on issue #12366:
URL: https://github.com/apache/arrow-rs/issues/12366#issuecomment-7379171521

   Thanks for taking a look, and sorry for the slow reply.  I'm using the 
parquet crate in a log search project where many queries search for a rare term 
in large row groups. Here is a reproducer that uses only the released crate 
(parquet 60.1.0).
   
   It writes one `Int64` column of 1,048,576 rows in one row group, with 8,192 
down to 128 rows per page, and reads a single row with a `RowSelection`: the 
first, the middle or the last. The metadata and page index are loaded once, 
outside the timing. Only one row is read each time, so the time should not 
depend on the number of pages.
   
   <details>
   <summary>Cargo.toml dependencies and src/main.rs</summary>
   
   ```toml
   [dependencies]
   parquet = { version = "=60.1.0", default-features = false, features = 
["arrow"] }
   arrow-array = "=60.1.0"
   bytes = "1"
   ```
   
   ```rust
   //! Reads one row of a 1,048,576-row row group, selected with a RowSelection 
over the page index.
   //! The time grows with the number of pages in the column chunk, although 
the rows read do not change.
   
   use std::sync::Arc;
   use std::time::Instant;
   
   use arrow_array::{ArrayRef, Int64Array, RecordBatch};
   use bytes::Bytes;
   use parquet::arrow::ArrowWriter;
   use parquet::arrow::arrow_reader::{
       ArrowReaderMetadata, ArrowReaderOptions, 
ParquetRecordBatchReaderBuilder, RowSelection,
       RowSelector,
   };
   use parquet::file::metadata::PageIndexPolicy;
   use parquet::file::properties::WriterProperties;
   
   const ROWS: usize = 1 << 20;
   
   fn write(page_rows: usize) -> Bytes {
       let ids: ArrayRef = Arc::new(Int64Array::from_iter_values(0..ROWS as 
i64));
       let batch = RecordBatch::try_from_iter([("id", ids)]).unwrap();
       let props = WriterProperties::builder()
           .set_dictionary_enabled(false)
           .set_data_page_row_count_limit(page_rows)
           .set_write_batch_size(page_rows)
           .set_max_row_group_row_count(Some(ROWS))
           .build();
       let mut out = Vec::new();
       let mut writer = ArrowWriter::try_new(&mut out, batch.schema(), 
Some(props)).unwrap();
       writer.write(&batch).unwrap();
       writer.close().unwrap();
       Bytes::from(out)
   }
   
   /// Reads the single row `row` and returns the median time of `runs` reads, 
in microseconds.
   /// The metadata, with the page index, is loaded once outside the timing.
   fn read_one(file: &Bytes, row: usize, runs: usize) -> f64 {
       let options = 
ArrowReaderOptions::new().with_page_index_policy(PageIndexPolicy::Required);
       let metadata = ArrowReaderMetadata::load(file, options).unwrap();
       let mut times = Vec::with_capacity(runs);
       for _ in 0..runs {
           let start = Instant::now();
           // Rows after the selection are not read, so only the pages before 
`row` are skipped.
           let selection = RowSelection::from(vec![RowSelector::skip(row), 
RowSelector::select(1)]);
           let reader =
               ParquetRecordBatchReaderBuilder::new_with_metadata(file.clone(), 
metadata.clone())
                   .with_row_selection(selection)
                   .build()
                   .unwrap();
           let mut got = 0;
           for batch in reader {
               let batch = batch.unwrap();
               let ids = batch
                   .column(0)
                   .as_any()
                   .downcast_ref::<Int64Array>()
                   .unwrap();
               assert_eq!(ids.value(0), row as i64);
               got += batch.num_rows();
           }
           assert_eq!(got, 1);
           times.push(start.elapsed().as_secs_f64() * 1e6);
       }
       times.sort_by(|a, b| a.partial_cmp(b).unwrap());
       times[runs / 2]
   }
   
   fn main() {
       println!("rows per page | pages | first row (us) | middle row (us) | 
last row (us)");
       for page_rows in [8192, 2048, 512, 128] {
           let file = write(page_rows);
           let pages = ROWS / page_rows;
           let first = read_one(&file, 0, 201);
           let middle = read_one(&file, ROWS / 2, 201);
           let last = read_one(&file, ROWS - 1, 201);
           println!("{page_rows:>13} | {pages:>5} | {first:>14.1} | 
{middle:>15.1} | {last:>13.1}");
       }
   }
   ```
   
   </details>
   
   Median of 201 reads in µs on an Apple M4 Pro, parquet 60.1.0 from crates.io. 
Main as of 20 November gave about the same results.
   
   | Pages per column chunk | First row | Middle row | Last row |
   |---|---|---|---|
   | 128 | 1.3 | 1.8 | 2.0 |
   | 512 | 1.8 | 2.7 | 3.7 |
   | 2,048 | 2.5 | 7.2 | 11.8 |
   | 8,192 | 10.0 | 53.8 | 51.0 |
   
   Two things grow with the page count:
   - Reading the first row skips nothing and still goes from 1.3 to 10 µs. That 
is the copy of the page locations into each column chunk's page reader (the 
`TODO(ets)` mentioned in the issue).
   - The middle and last rows add the page-by-page skip loop, up to about 44 µs 
more - which is this issue.
   
   Both costs are per column chunk, so a query over several columns and many 
row groups pays them many, many times, which is how the skip loop alone reached 
7.6% of CPU in my workload.
   
   I have a fix ready in two parts, and will open a PR for the first part 
shortly:
   
   1. **Skip whole pages with one good old fashioned binary search.** The 
offset index already stores each page's first row. So when `skip_records` has 
rows to skip, it can find how many whole pages fit with one binary search over 
`first_row_index`, instead of stepping through the pages one in turn. In my 
runs this brings the middle and last rows at 8,192 pages down to about the cost 
of the first row.
   2. **Read the page locations in place instead of copying them.** The page 
reader would read the locations from the page index that is already in memory, 
as the TODO note suggests, instead of cloning them for each column chunk. With 
both parts, every case in the table is about 2 µs.
   
   The second part builds on the first, so I would open it after the first is 
reviewed.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to