-
Notifications
You must be signed in to change notification settings - Fork 182
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
Add load_as methods for pyarrow dataset and table #240
Draft
chitralverma
wants to merge
8
commits into
delta-io:main
Choose a base branch
from
chitralverma:delta-sharing-as-arrow
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
e2a5123
Add load_as methods for pyarrow dataset and table
chitralverma f0b88cd
lint fix
chitralverma cb39e86
fix lint for older python versions
chitralverma 08341c4
Optimize load_as_pyarrow_table with limit
chitralverma 96fc160
Add pyarrow examples
chitralverma ab2c387
Added schema converter for pyarrow
chitralverma f258886
Added tests for reader
chitralverma b9e7134
unpin versions for pyarrow and fsspec
chitralverma 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
# | ||
# Copyright (2021) The Delta Lake Project Authors. | ||
# | ||
# 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 os | ||
|
||
import delta_sharing | ||
|
||
# Point to the profile file. It can be a file on the local file system or a file on a remote storage. | ||
profile_file = os.path.dirname(__file__) + "/../open-datasets.share" | ||
|
||
# Create a SharingClient. | ||
client = delta_sharing.SharingClient(profile_file) | ||
|
||
# List all shared tables. | ||
print("########### All Available Tables #############") | ||
print(client.list_all_tables()) | ||
|
||
# Create a url to access a shared table. | ||
# A table path is the profile file path following with `#` and the fully qualified name of a table (`<share-name>.<schema-name>.<table-name>`). | ||
table_url = profile_file + "#delta_sharing.default.owid-covid-data" | ||
|
||
# As PyArrow Dataset. | ||
|
||
# Create a lazy reference for delta sharing table as a PyArrow Dataset. | ||
print( | ||
"########### Create a lazy reference for delta_sharing.default.owid-covid-data as a PyArrow Dataset #############") | ||
data = delta_sharing.load_as_pyarrow_dataset(table_url) | ||
print(data.schema) | ||
|
||
# Create a lazy reference for delta sharing table as a PyArrow Dataset with additional pyarrow options. | ||
print( | ||
"########### Create a lazy reference for delta_sharing.default.owid-covid-data as a PyArrow Dataset with additional options #############") | ||
delta_sharing.load_as_pyarrow_dataset(table_url, pyarrow_ds_options={"partitioning": "hive"}) | ||
|
||
# As PyArrow Table. | ||
|
||
# Fetch 10 rows from a delta sharing table as a PyArrow Table. This can be used to read sample data from a table that cannot fit in the memory. | ||
print("########### Loading 10 rows from delta_sharing.default.owid-covid-data as a PyArrow Table #############") | ||
data = delta_sharing.load_as_pyarrow_table(table_url, limit=10) | ||
|
||
# Print the sample. | ||
print("########### Show the number of fetched rows #############") | ||
print(data.num_rows) | ||
|
||
# Load full table as a PyArrow Table. This can be used to process tables that can fit in the memory. | ||
print("########### Loading all data from delta_sharing.default.owid-covid-data as a PyArrow Table #############") | ||
data = delta_sharing.load_as_pyarrow_table(table_url) | ||
print(data.num_rows) | ||
|
||
# Load full table as a PyArrow Table with additional pyarrow options. | ||
print( | ||
"########### Loading all data from delta_sharing.default.owid-covid-data as a PyArrow Table with additional pyarrow options #############") | ||
import pyarrow.dataset as ds | ||
|
||
data = delta_sharing.load_as_pyarrow_table( | ||
table_url, | ||
pyarrow_ds_options={"exclude_invalid_files": False}, | ||
pyarrow_tbl_options={ | ||
"columns": ["date", "location", "total_cases"], | ||
"filter": ds.field("date") == "2020-02-24" | ||
} | ||
) | ||
print(data) | ||
|
||
# Convert PyArrow Table to Pandas DataFrame. | ||
print("########### Converting delta_sharing.default.owid-covid-data PyArrow Table to a Pandas DataFrame #############") | ||
pdf = data.to_pandas() | ||
print(pdf) |
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 |
---|---|---|
|
@@ -18,6 +18,11 @@ | |
|
||
import numpy as np | ||
import pandas as pd | ||
import pyarrow as pa | ||
from pyarrow import Schema as PyArrowSchema | ||
from pyarrow import Table as PyArrowTable | ||
from pyarrow.dataset import Dataset as PyArrowDataset | ||
from pyarrow.dataset import dataset | ||
|
||
|
||
def _get_dummy_column(schema_type): | ||
|
@@ -57,7 +62,157 @@ def _get_dummy_column(schema_type): | |
raise ValueError(f"Could not parse datatype: {schema_type}") | ||
|
||
|
||
def get_empty_table(schema_json: dict) -> pd.DataFrame: | ||
def _to_pyarrow_schema(schema_value: dict) -> PyArrowSchema: | ||
""" | ||
Converts delta table schema to a valid PyArrow Schema with | ||
field metadata and nullability preserved. | ||
This implementation closely follows PySpark and supports columns | ||
with complex data types like `struct`, `map` and `array`. | ||
|
||
:param schema_value: Representation of delta table schema as a dict | ||
:return: pyarrow.Schema | ||
""" | ||
assert schema_value is not None and schema_value["type"] == "struct", "Invalid schema found." | ||
|
||
def _to_arrow_type(f_type) -> pa.DataType: | ||
is_nested = isinstance(f_type, dict) | ||
|
||
if not is_nested: | ||
f_type = f_type.lower() | ||
|
||
if not is_nested and f_type == "boolean": | ||
return pa.bool_() | ||
|
||
elif not is_nested and f_type == "byte": | ||
return pa.int8() | ||
|
||
elif not is_nested and f_type == "short": | ||
return pa.int16() | ||
|
||
elif not is_nested and f_type == "integer": | ||
return pa.int32() | ||
|
||
elif not is_nested and f_type == "long": | ||
return pa.int64() | ||
|
||
elif not is_nested and f_type == "float": | ||
return pa.float32() | ||
|
||
elif not is_nested and f_type == "double": | ||
return pa.float64() | ||
|
||
elif not is_nested and f_type.startswith("decimal"): | ||
try: | ||
import re | ||
|
||
decimal_pattern = re.compile(r"(\([^\)]+\))") | ||
res = [ | ||
int(v.strip()) | ||
for v in decimal_pattern.findall(f_type)[0].lstrip("(").rstrip(")").split(",") | ||
] | ||
precision = res[0] | ||
scale = res[1] | ||
except: | ||
precision = 10 | ||
scale = 0 | ||
return pa.decimal128(precision, scale) | ||
|
||
elif not is_nested and f_type == "string": | ||
return pa.string() | ||
|
||
elif not is_nested and f_type == "binary": | ||
return pa.binary() | ||
|
||
elif not is_nested and f_type == "date": | ||
return pa.date32() | ||
|
||
elif not is_nested and f_type == "timestamp": | ||
return pa.timestamp("us") | ||
|
||
elif not is_nested and f_type in ["void", "null"]: | ||
return pa.null() | ||
|
||
elif is_nested and f_type["type"] == "array": | ||
element_type = f_type["elementType"] | ||
if isinstance(element_type, str) and element_type == "timestamp": | ||
raise TypeError( | ||
f"Could not parse map field types: array<timestamp> to PyArrow type." | ||
) | ||
elif isinstance(element_type, dict) and element_type["type"] == "struct": | ||
if any( | ||
isinstance(struct_field["type"], dict) | ||
and struct_field["type"]["type"] == "struct" | ||
for struct_field in element_type["fields"] | ||
): | ||
raise TypeError("Nested StructType cannot be converted to PyArrow type.") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "Double Nested cannot ..."? |
||
return pa.list_(_to_arrow_type(element_type)) | ||
|
||
elif is_nested and f_type["type"] == "map": | ||
key_type = f_type["keyType"] | ||
value_type = f_type["valueType"] | ||
if (isinstance(key_type, str) and key_type == "timestamp") or ( | ||
isinstance(value_type, str) and value_type == "timestamp" | ||
): | ||
raise TypeError( | ||
f"Could not parse map field with timestamp key or value types to PyArrow type." | ||
) | ||
elif (isinstance(key_type, dict) and key_type["type"] == "struct") or ( | ||
isinstance(value_type, dict) and value_type["type"] == "struct" | ||
): | ||
raise TypeError( | ||
f"Could not parse map field with struct key or value types to PyArrow type." | ||
) | ||
return pa.map_(_to_arrow_type(key_type), _to_arrow_type(value_type)) | ||
|
||
elif is_nested and f_type["type"] == "struct": | ||
if any( | ||
isinstance(struct_field["type"], dict) and struct_field["type"]["type"] == "struct" | ||
for struct_field in f_type["fields"] | ||
): | ||
raise TypeError("Nested StructType cannot be converted to PyArrow type.") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. double nested? |
||
struct_fields = [ | ||
pa.field( | ||
struct_field["name"], | ||
_to_arrow_type(struct_field["type"]), | ||
nullable=(str(struct_field["nullable"]).lower() == "true"), | ||
metadata=struct_field["metadata"], | ||
) | ||
for struct_field in f_type["fields"] | ||
] | ||
return pa.struct(struct_fields) | ||
else: | ||
raise TypeError(f"Could not parse type: {f_type} to PyArrow type.") | ||
|
||
fields = [] | ||
for field in schema_value["fields"]: | ||
field_name = str(field["name"]) | ||
field_type = field["type"] | ||
field_nullable = str(field["nullable"]).lower() == "true" | ||
field_metadata = field["metadata"] | ||
|
||
fields.append( | ||
pa.field( | ||
field_name, | ||
_to_arrow_type(field_type), | ||
nullable=field_nullable, | ||
metadata=field_metadata, | ||
) | ||
) | ||
|
||
return pa.schema(fields) | ||
|
||
|
||
def get_empty_pyarrow_table(schema_json: dict) -> PyArrowTable: | ||
schema = _to_pyarrow_schema(schema_json) | ||
return schema.empty_table() | ||
|
||
|
||
def get_empty_pyarrow_dataset(schema_json: dict) -> PyArrowDataset: | ||
schema = _to_pyarrow_schema(schema_json) | ||
return dataset([], schema=schema) | ||
|
||
|
||
def get_empty_pandas_table(schema_json: dict) -> pd.DataFrame: | ||
""" | ||
For empty tables, we use dummy columns from `_get_dummy_column` and then | ||
drop all rows to generate a table with the correct column names and | ||
|
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.
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.
nit: add comment with examples that this pattern could handle and not?