-
Notifications
You must be signed in to change notification settings - Fork 1.3k
[python] Support random sample for append table #7014
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 9 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| # 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. | ||
| from typing import Optional | ||
|
|
||
| from pyarrow import RecordBatch | ||
|
|
||
| from pypaimon.read.reader.format_blob_reader import FormatBlobReader | ||
| from pypaimon.read.reader.iface.record_batch_reader import RecordBatchReader | ||
|
|
||
|
|
||
| class SampleBatchReader(RecordBatchReader): | ||
| """ | ||
| A reader that reads a subset of rows from a data file based on specified sample positions. | ||
|
|
||
| This reader wraps another RecordBatchReader and only returns rows at the specified | ||
| sample positions, enabling efficient random sampling of data without reading all rows. | ||
|
|
||
| The reader supports two modes: | ||
| 1. For blob readers: Directly reads specific rows by index | ||
| 2. For other readers: Reads batches sequentially and extracts only the sampled rows | ||
|
|
||
| Attributes: | ||
| reader: The underlying RecordBatchReader to read data from | ||
| sample_positions: A sorted list of row indices to sample (0-based) | ||
| sample_idx: Current index in the sample_positions list | ||
| current_pos: Current absolute row position in the data file | ||
| """ | ||
|
|
||
| def __init__(self, reader, sample_positions): | ||
| """ | ||
| Initialize the SampleBatchReader. | ||
|
|
||
| Args: | ||
| reader: The underlying RecordBatchReader to read data from | ||
| sample_positions: A bitmap of row indices to sample (0-based). | ||
| Must be sorted in ascending order for correct behavior. | ||
| """ | ||
| self.reader = reader | ||
| self.sample_positions = sample_positions | ||
| self.sample_idx = 0 | ||
| self.current_pos = 0 | ||
|
|
||
| def read_arrow_batch(self) -> Optional[RecordBatch]: | ||
| """ | ||
| Read the next batch containing sampled rows. | ||
|
|
||
| This method reads data from the underlying reader and returns only the rows | ||
| at the specified sample positions. The behavior differs based on reader type: | ||
|
|
||
| - For FormatBlobReader: Directly reads individual rows by index | ||
| - For other readers: Reads batches sequentially and extracts sampled rows | ||
| using PyArrow's take() method | ||
| """ | ||
| if self.sample_idx >= len(self.sample_positions): | ||
| return None | ||
| if isinstance(self.reader.format_reader, FormatBlobReader): | ||
| # For blob reader, pass begin_idx and end_idx parameters | ||
| batch = self.reader.read_arrow_batch(start_idx=self.sample_positions[self.sample_idx], | ||
| end_idx=self.sample_positions[self.sample_idx] + 1) | ||
| self.sample_idx += 1 | ||
| return batch | ||
| else: | ||
| batch = self.reader.read_arrow_batch() | ||
| if batch is None: | ||
| return None | ||
|
|
||
| batch_begin = self.current_pos | ||
| self.current_pos += batch.num_rows | ||
| take_idxes = [] | ||
|
|
||
| sample_pos = self.sample_positions[self.sample_idx] | ||
| while batch_begin <= sample_pos < self.current_pos: | ||
| take_idxes.append(sample_pos - batch_begin) | ||
| self.sample_idx += 1 | ||
| if self.sample_idx >= len(self.sample_positions): | ||
| break | ||
| sample_pos = self.sample_positions[self.sample_idx] | ||
|
|
||
| if take_idxes: | ||
| return batch.take(take_idxes) | ||
| else: # batch is outside the desired range | ||
| return self.read_arrow_batch() | ||
|
|
||
| def close(self): | ||
| self.reader.close() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| # 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. | ||
| from typing import Dict, List | ||
|
|
||
| from pyroaring import BitMap | ||
|
|
||
| from pypaimon.read.split import Split | ||
|
|
||
|
|
||
| class SampledSplit(Split): | ||
| """ | ||
| A Split wrapper that contains sampled row indexes for each file. | ||
|
|
||
| This class wraps a data split and maintains a mapping from file names to | ||
| lists of sampled row indexes. It is used for random sampling scenarios where | ||
| only specific rows from each file need to be read. | ||
|
|
||
| Attributes: | ||
| _data_split: The underlying data split being wrapped. | ||
| _sampled_file_idx_map: A dictionary mapping file names to lists of | ||
| sampled row indexes within each file. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| data_split: 'Split', | ||
| sampled_file_idx_map: Dict[str, BitMap] | ||
| ): | ||
| self._data_split = data_split | ||
| self._sampled_file_idx_map = sampled_file_idx_map | ||
|
|
||
| def data_split(self) -> 'Split': | ||
| return self._data_split | ||
|
|
||
| def sampled_file_idx_map(self) -> Dict[str, BitMap]: | ||
| return self._sampled_file_idx_map | ||
|
|
||
| @property | ||
| def files(self) -> List['DataFileMeta']: | ||
| return self._data_split.files | ||
|
|
||
| @property | ||
| def partition(self) -> 'GenericRow': | ||
| return self._data_split.partition | ||
|
|
||
| @property | ||
| def bucket(self) -> int: | ||
| return self._data_split.bucket | ||
|
|
||
| @property | ||
| def row_count(self) -> int: | ||
| if not self._sampled_file_idx_map: | ||
| return self._data_split.row_count | ||
|
|
||
| total_rows = 0 | ||
| for file in self._data_split.files: | ||
| positions = self._sampled_file_idx_map[file.file_name] | ||
| total_rows += len(positions) | ||
|
|
||
| return total_rows | ||
|
|
||
| @property | ||
| def file_paths(self): | ||
| return self._data_split.file_paths | ||
|
|
||
| @property | ||
| def file_size(self): | ||
| return self._data_split.file_size | ||
|
|
||
| @property | ||
| def raw_convertible(self): | ||
| return self._data_split.raw_convertible | ||
|
|
||
| @property | ||
| def data_deletion_files(self): | ||
| return self._data_split.data_deletion_files | ||
|
|
||
| def __eq__(self, other): | ||
| if not isinstance(other, SampledSplit): | ||
| return False | ||
| return (self._data_split == other._data_split and | ||
| self._sampled_file_idx_map == other._sampled_file_idx_map) | ||
|
|
||
| def __hash__(self): | ||
| return hash((id(self._data_split), tuple(sorted(self._sampled_file_idx_map.items())))) | ||
|
|
||
| def __repr__(self): | ||
| return (f"SampledSplit(data_split={self._data_split}, " | ||
| f"sampled_file_idx_map={self._sampled_file_idx_map})") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm afraid RecursionError will be raised when many batches are outside the sample range in production with large files and sparse sampling.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
changed.