-
Notifications
You must be signed in to change notification settings - Fork 246
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
feat: add python bindings for the v2 reader/writer #2158
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
ffcc140
Add python bindings for reading and writing lance v2 files
westonpace fe777b9
Apply clippy suggestions
westonpace 1b03be2
rust fmt
westonpace 0ef20f1
Adding debugging information to debug windows CI failure. DO NOT MERGE
westonpace ef6f54e
Fix windows error. Remove redundant method from object_store.rs. Re…
westonpace dec777a
Apply clippy suggestion
westonpace f8ca99c
Update copyright year as per code review
westonpace 2aa6c84
Apply clippy suggestions
westonpace 7d8b83a
Check metadata method instead of file size
westonpace 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 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 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 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,188 @@ | ||
# Copyright (c) 2024. Lance Developers | ||
# | ||
# Licensed 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 Union | ||
|
||
import pyarrow as pa | ||
|
||
from .lance import ( | ||
LanceBufferDescriptor, | ||
LanceColumnMetadata, | ||
LanceFileMetadata, | ||
LancePageMetadata, | ||
) | ||
from .lance import ( | ||
LanceFileReader as _LanceFileReader, | ||
) | ||
from .lance import ( | ||
LanceFileWriter as _LanceFileWriter, | ||
) | ||
|
||
|
||
class ReaderResults: | ||
""" | ||
Utility class for converting results from Lance's internal | ||
format (RecordBatchReader) to a desired format such | ||
as a pyarrow Table, etc. | ||
""" | ||
|
||
def __init__(self, reader: pa.RecordBatchReader): | ||
""" | ||
Creates a new instance, not meant for external use | ||
""" | ||
self.reader = reader | ||
|
||
def to_batches(self) -> pa.RecordBatchReader: | ||
""" | ||
Return the results as a pyarrow RecordBatchReader | ||
""" | ||
return self.reader | ||
|
||
def to_table(self) -> pa.Table: | ||
""" | ||
Return the results as a pyarrow Table | ||
""" | ||
return self.reader.read_all() | ||
|
||
|
||
class LanceFileReader: | ||
""" | ||
A file reader for reading Lance files | ||
|
||
This class is used to read Lance data files, a low level structure | ||
optimized for storing multi-modal tabular data. If you are working with | ||
Lance datasets then you should use the LanceDataset class instead. | ||
""" | ||
|
||
# TODO: make schema optional | ||
def __init__(self, path: str, schema: pa.Schema): | ||
""" | ||
Creates a new file reader to read the given file | ||
|
||
Parameters | ||
---------- | ||
|
||
path: str | ||
The path to read, can be a pathname for local storage | ||
or a URI to read from cloud storage. | ||
schema: pa.Schema | ||
The desired projection schema | ||
""" | ||
self._reader = _LanceFileReader(path, schema) | ||
|
||
def read_all(self, *, batch_size: int = 1024) -> ReaderResults: | ||
""" | ||
Reads the entire file | ||
|
||
Parameters | ||
---------- | ||
batch_size: int, default 1024 | ||
The file will be read in batches. This parameter controls | ||
how many rows will be in each batch (except the final batch) | ||
|
||
Smaller batches will use less memory but might be slightly | ||
slower because there is more per-batch overhead | ||
""" | ||
return ReaderResults(self._reader.read_all(batch_size)) | ||
|
||
def read_range( | ||
self, start: int, num_rows: int, *, batch_size: int = 1024 | ||
) -> ReaderResults: | ||
""" | ||
Read a range of rows from the file | ||
|
||
Parameters | ||
---------- | ||
start: int | ||
The offset of the first row to start reading | ||
num_rows: int | ||
The number of rows to read from the file | ||
batch_size: int, default 1024 | ||
The file will be read in batches. This parameter controls | ||
how many rows will be in each batch (except the final batch) | ||
|
||
Smaller batches will use less memory but might be slightly | ||
slower because there is more per-batch overhead | ||
""" | ||
return ReaderResults(self._reader.read_range(start, num_rows, batch_size)) | ||
|
||
def metadata(self) -> LanceFileMetadata: | ||
""" | ||
Return metadata describing the file contents | ||
""" | ||
return self._reader.metadata() | ||
|
||
|
||
class LanceFileWriter: | ||
""" | ||
A file writer for writing Lance data files | ||
|
||
This class is used to write Lance data files, a low level structure | ||
optimized for storing multi-modal tabular data. If you are working with | ||
Lance datasets then you should use the LanceDataset class instead. | ||
""" | ||
|
||
def __init__(self, path: str, schema: pa.Schema, **kwargs): | ||
""" | ||
Create a new LanceFileWriter to write to the given path | ||
|
||
Parameters | ||
---------- | ||
path: str | ||
The path to write to. Can be a pathname for local storage | ||
or a URI for remote storage. | ||
schema: pa.Schema | ||
The schema of data that will be written | ||
""" | ||
self._writer = _LanceFileWriter(path, schema, **kwargs) | ||
self.closed = False | ||
|
||
def write_batch(self, batch: Union[pa.RecordBatch, pa.Table]) -> None: | ||
""" | ||
Write a batch of data to the file | ||
|
||
parameters | ||
---------- | ||
batch: Union[pa.RecordBatch, pa.Table] | ||
The data to write to the file | ||
""" | ||
if isinstance(batch, pa.Table): | ||
for batch in batch.to_batches(): | ||
self._writer.write_batch(batch) | ||
else: | ||
self._writer.write_batch(batch) | ||
|
||
def close(self) -> None: | ||
""" | ||
Write the file metadata and close the file | ||
""" | ||
if self.closed: | ||
return | ||
self.closed = True | ||
self._writer.finish() | ||
|
||
def __enter__(self) -> "LanceFileWriter": | ||
return self | ||
|
||
def __exit__(self, exc_type, exc_val, exc_tb) -> None: | ||
self.close() | ||
|
||
|
||
__all__ = [ | ||
"LanceFileReader", | ||
"LanceFileWriter", | ||
"LanceFileMetadata", | ||
"LanceColumnMetadata", | ||
"LancePageMetadata", | ||
"LanceBufferDescriptor", | ||
] |
This file contains 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 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,90 @@ | ||
# Copyright (c) 2024. Lance Developers | ||
# | ||
# Licensed 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. | ||
|
||
import pyarrow as pa | ||
from lance.file import LanceFileReader, LanceFileWriter | ||
|
||
|
||
def test_file_writer(tmp_path): | ||
path = tmp_path / "foo.lance" | ||
schema = pa.schema([pa.field("a", pa.int64())]) | ||
with LanceFileWriter(str(path), schema) as writer: | ||
writer.write_batch(pa.table({"a": [1, 2, 3]})) | ||
reader = LanceFileReader(str(path), schema) | ||
metadata = reader.metadata() | ||
assert metadata.num_rows == 3 | ||
|
||
|
||
def test_aborted_write(tmp_path): | ||
path = tmp_path / "foo.lance" | ||
schema = pa.schema([pa.field("a", pa.int64())]) | ||
writer = LanceFileWriter(str(path), schema) | ||
writer.write_batch(pa.table({"a": [1, 2, 3]})) | ||
del writer | ||
assert not path.exists() | ||
|
||
|
||
def test_multiple_close(tmp_path): | ||
path = tmp_path / "foo.lance" | ||
schema = pa.schema([pa.field("a", pa.int64())]) | ||
writer = LanceFileWriter(str(path), schema) | ||
writer.write_batch(pa.table({"a": [1, 2, 3]})) | ||
writer.close() | ||
writer.close() | ||
|
||
|
||
def test_round_trip(tmp_path): | ||
path = tmp_path / "foo.lance" | ||
schema = pa.schema([pa.field("a", pa.int64())]) | ||
data = pa.table({"a": [1, 2, 3]}) | ||
with LanceFileWriter(str(path), schema) as writer: | ||
writer.write_batch(data) | ||
reader = LanceFileReader(str(path), schema) | ||
result = reader.read_all().to_table() | ||
assert result == data | ||
|
||
# TODO: Currently fails, need to fix reader | ||
# result = reader.read_range(1, 1).to_table() | ||
# assert result == pa.table({"a": [2]}) | ||
|
||
# TODO: Test reading invalid ranges | ||
# TODO: Test invalid batch sizes | ||
|
||
|
||
def test_metadata(tmp_path): | ||
path = tmp_path / "foo.lance" | ||
schema = pa.schema([pa.field("a", pa.int64())]) | ||
data = pa.table({"a": [1, 2, 3]}) | ||
with LanceFileWriter(str(path), schema) as writer: | ||
writer.write_batch(data) | ||
reader = LanceFileReader(str(path), schema) | ||
metadata = reader.metadata() | ||
|
||
assert metadata.schema == schema | ||
assert metadata.num_rows == 3 | ||
assert metadata.num_global_buffer_bytes > 0 | ||
assert metadata.num_column_metadata_bytes > 0 | ||
assert metadata.num_data_bytes == 24 | ||
assert len(metadata.columns) == 1 | ||
|
||
column = metadata.columns[0] | ||
assert len(column.column_buffers) == 0 | ||
assert len(column.pages) == 1 | ||
|
||
page = column.pages[0] | ||
assert len(page.buffers) == 1 | ||
assert page.buffers[0].position == 0 | ||
assert page.buffers[0].size == 24 | ||
|
||
assert len(page.encoding) > 0 |
This file contains 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.
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.
Is this interface mostly internal utility? The public main interface is still
pyarrow.Dataset
?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.
Yes. This is mainly for benchmarking / advanced use cases.