-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
BigQuery Storage: Add support for arrow format in BQ Read API #8644
Merged
Merged
Changes from 9 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
9553d8d
BQ Storage: Add basic arrow stream parser
TheNeuralBit 4873562
BQ Storage: Add tests for to_dataframe with arrow data
TheNeuralBit 45bd1e9
Use Arrow format in client.list_rows(..).to_dataframe(..) with BQ Sto…
TheNeuralBit 552fc1e
Merge remote-tracking branch 'upstream/master' into bq-storage-arrow
tswast 06f990e
Add system test for arrow wire format.
tswast 5e7a403
Add pyarrow to system tests deps.
tswast 5155ac9
Add to_arrow with BQ Storage API.
tswast 5a5edd5
Revert changes to bigquery so that bigquery_storage can be released
tswast 4986bd1
Add tests for to_arrow.
tswast f647062
Remove parameterized error messages.
tswast 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 |
---|---|---|
|
@@ -27,16 +27,27 @@ | |
import pandas | ||
except ImportError: # pragma: NO COVER | ||
pandas = None | ||
try: | ||
import pyarrow | ||
except ImportError: # pragma: NO COVER | ||
pyarrow = None | ||
import six | ||
|
||
try: | ||
import pyarrow | ||
except ImportError: # pragma: NO COVER | ||
pyarrow = None | ||
|
||
from google.cloud.bigquery_storage_v1beta1 import types | ||
|
||
|
||
_STREAM_RESUMPTION_EXCEPTIONS = (google.api_core.exceptions.ServiceUnavailable,) | ||
_FASTAVRO_REQUIRED = ( | ||
"fastavro is required to parse ReadRowResponse messages with Avro bytes." | ||
) | ||
|
||
_AVRO_BYTES_OPERATION = "parse ReadRowResponse messages with Avro bytes" | ||
_ARROW_BYTES_OPERATION = "parse ReadRowResponse messages with Arrow bytes" | ||
_FASTAVRO_REQUIRED = "fastavro is required to {operation}." | ||
_PANDAS_REQUIRED = "pandas is required to create a DataFrame" | ||
_PYARROW_REQUIRED = "pyarrow is required to {operation}." | ||
|
||
|
||
class ReadRowsStream(object): | ||
|
@@ -113,7 +124,7 @@ def __iter__(self): | |
while True: | ||
try: | ||
for message in self._wrapped: | ||
rowcount = message.avro_rows.row_count | ||
rowcount = message.row_count | ||
self._position.offset += rowcount | ||
yield message | ||
|
||
|
@@ -152,11 +163,28 @@ def rows(self, read_session): | |
Iterable[Mapping]: | ||
A sequence of rows, represented as dictionaries. | ||
""" | ||
if fastavro is None: | ||
raise ImportError(_FASTAVRO_REQUIRED) | ||
|
||
return ReadRowsIterable(self, read_session) | ||
|
||
def to_arrow(self, read_session): | ||
"""Create a :class:`pyarrow.Table` of all rows in the stream. | ||
|
||
This method requires the pyarrow library and a stream using the Arrow | ||
format. | ||
|
||
Args: | ||
read_session ( \ | ||
~google.cloud.bigquery_storage_v1beta1.types.ReadSession \ | ||
): | ||
The read session associated with this read rows stream. This | ||
contains the schema, which is required to parse the data | ||
messages. | ||
|
||
Returns: | ||
pyarrow.Table: | ||
A table of all rows in the stream. | ||
""" | ||
return self.rows(read_session).to_arrow() | ||
|
||
def to_dataframe(self, read_session, dtypes=None): | ||
"""Create a :class:`pandas.DataFrame` of all rows in the stream. | ||
|
||
|
@@ -186,8 +214,6 @@ def to_dataframe(self, read_session, dtypes=None): | |
pandas.DataFrame: | ||
A data frame of all rows in the stream. | ||
""" | ||
if fastavro is None: | ||
raise ImportError(_FASTAVRO_REQUIRED) | ||
if pandas is None: | ||
raise ImportError(_PANDAS_REQUIRED) | ||
|
||
|
@@ -212,6 +238,7 @@ def __init__(self, reader, read_session): | |
self._status = None | ||
self._reader = reader | ||
self._read_session = read_session | ||
self._stream_parser = _StreamParser.from_read_session(self._read_session) | ||
|
||
@property | ||
def total_rows(self): | ||
|
@@ -231,17 +258,31 @@ def pages(self): | |
""" | ||
# Each page is an iterator of rows. But also has num_items, remaining, | ||
# and to_dataframe. | ||
stream_parser = _StreamParser(self._read_session) | ||
for message in self._reader: | ||
self._status = message.status | ||
yield ReadRowsPage(stream_parser, message) | ||
yield ReadRowsPage(self._stream_parser, message) | ||
|
||
def __iter__(self): | ||
"""Iterator for each row in all pages.""" | ||
for page in self.pages: | ||
for row in page: | ||
yield row | ||
|
||
def to_arrow(self): | ||
"""Create a :class:`pyarrow.Table` of all rows in the stream. | ||
|
||
This method requires the pyarrow library and a stream using the Arrow | ||
format. | ||
|
||
Returns: | ||
pyarrow.Table: | ||
A table of all rows in the stream. | ||
""" | ||
record_batches = [] | ||
for page in self.pages: | ||
record_batches.append(page.to_arrow()) | ||
return pyarrow.Table.from_batches(record_batches) | ||
|
||
def to_dataframe(self, dtypes=None): | ||
"""Create a :class:`pandas.DataFrame` of all rows in the stream. | ||
|
||
|
@@ -291,8 +332,8 @@ def __init__(self, stream_parser, message): | |
self._stream_parser = stream_parser | ||
self._message = message | ||
self._iter_rows = None | ||
self._num_items = self._message.avro_rows.row_count | ||
self._remaining = self._message.avro_rows.row_count | ||
self._num_items = self._message.row_count | ||
self._remaining = self._message.row_count | ||
|
||
def _parse_rows(self): | ||
"""Parse rows from the message only once.""" | ||
|
@@ -326,6 +367,15 @@ def next(self): | |
# Alias needed for Python 2/3 support. | ||
__next__ = next | ||
|
||
def to_arrow(self): | ||
"""Create an :class:`pyarrow.RecordBatch` of rows in the page. | ||
|
||
Returns: | ||
pyarrow.RecordBatch: | ||
Rows from the message, as an Arrow record batch. | ||
""" | ||
return self._stream_parser.to_arrow(self._message) | ||
|
||
def to_dataframe(self, dtypes=None): | ||
"""Create a :class:`pandas.DataFrame` of rows in the page. | ||
|
||
|
@@ -355,21 +405,61 @@ def to_dataframe(self, dtypes=None): | |
|
||
|
||
class _StreamParser(object): | ||
def to_arrow(self, message): | ||
raise NotImplementedError("Not implemented.") | ||
|
||
def to_dataframe(self, message, dtypes=None): | ||
raise NotImplementedError("Not implemented.") | ||
|
||
def to_rows(self, message): | ||
raise NotImplementedError("Not implemented.") | ||
|
||
@staticmethod | ||
def from_read_session(read_session): | ||
schema_type = read_session.WhichOneof("schema") | ||
if schema_type == "avro_schema": | ||
return _AvroStreamParser(read_session) | ||
elif schema_type == "arrow_schema": | ||
return _ArrowStreamParser(read_session) | ||
else: | ||
raise TypeError( | ||
"Unsupported schema type in read_session: {0}".format(schema_type) | ||
) | ||
|
||
|
||
class _AvroStreamParser(_StreamParser): | ||
"""Helper to parse Avro messages into useful representations.""" | ||
|
||
def __init__(self, read_session): | ||
"""Construct a _StreamParser. | ||
"""Construct an _AvroStreamParser. | ||
|
||
Args: | ||
read_session (google.cloud.bigquery_storage_v1beta1.types.ReadSession): | ||
A read session. This is required because it contains the schema | ||
used in the stream messages. | ||
""" | ||
if fastavro is None: | ||
raise ImportError(_FASTAVRO_REQUIRED) | ||
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. does this need to be parameterized as well? 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. Removed the |
||
|
||
self._read_session = read_session | ||
self._avro_schema_json = None | ||
self._fastavro_schema = None | ||
self._column_names = None | ||
|
||
def to_arrow(self, message): | ||
"""Create an :class:`pyarrow.RecordBatch` of rows in the page. | ||
|
||
Args: | ||
message (google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse): | ||
Protocol buffer from the read rows stream, to convert into an | ||
Arrow record batch. | ||
|
||
Returns: | ||
pyarrow.RecordBatch: | ||
Rows from the message, as an Arrow record batch. | ||
""" | ||
raise NotImplementedError("to_arrow not implemented for Avro streams.") | ||
|
||
def to_dataframe(self, message, dtypes=None): | ||
"""Create a :class:`pandas.DataFrame` of rows in the page. | ||
|
||
|
@@ -447,6 +537,58 @@ def to_rows(self, message): | |
break # Finished with message | ||
|
||
|
||
class _ArrowStreamParser(_StreamParser): | ||
def __init__(self, read_session): | ||
if pyarrow is None: | ||
raise ImportError( | ||
_PYARROW_REQUIRED.format(operation=_ARROW_BYTES_OPERATION) | ||
) | ||
|
||
self._read_session = read_session | ||
self._schema = None | ||
|
||
def to_arrow(self, message): | ||
return self._parse_arrow_message(message) | ||
|
||
def to_rows(self, message): | ||
record_batch = self._parse_arrow_message(message) | ||
|
||
# Iterate through each column simultaneously, and make a dict from the | ||
# row values | ||
for row in zip(*record_batch.columns): | ||
yield dict(zip(self._column_names, row)) | ||
|
||
def to_dataframe(self, message, dtypes=None): | ||
record_batch = self._parse_arrow_message(message) | ||
|
||
if dtypes is None: | ||
dtypes = {} | ||
|
||
df = record_batch.to_pandas() | ||
|
||
for column in dtypes: | ||
df[column] = pandas.Series(df[column], dtype=dtypes[column]) | ||
|
||
return df | ||
|
||
def _parse_arrow_message(self, message): | ||
self._parse_arrow_schema() | ||
|
||
return pyarrow.read_record_batch( | ||
pyarrow.py_buffer(message.arrow_record_batch.serialized_record_batch), | ||
self._schema, | ||
) | ||
|
||
def _parse_arrow_schema(self): | ||
if self._schema: | ||
return | ||
|
||
self._schema = pyarrow.read_schema( | ||
pyarrow.py_buffer(self._read_session.arrow_schema.serialized_schema) | ||
) | ||
self._column_names = [field.name for field in self._schema] | ||
|
||
|
||
def _copy_stream_position(position): | ||
"""Copy a StreamPosition. | ||
|
||
|
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
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 assume these parameterized errors are for when you do things like to_arrow with avro bytes?
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.
Yeah, this is vestigial from when I was planning to implement
to_arrow
for Avro streams. Removed for now.