-
Notifications
You must be signed in to change notification settings - Fork 1.8k
samples(bigquery-storage): add Arrow query results samples for query_and_wait and read_rows #18126
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
Open
alextolpin
wants to merge
2
commits into
googleapis:main
Choose a base branch
from
alextolpin:arrow_samples
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.
Open
Changes from all commits
Commits
Show all changes
2 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
58 changes: 58 additions & 0 deletions
58
packages/google-cloud-bigquery-storage/samples/snippets/query_and_wait_arrow.py
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,58 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # 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 | ||
| # | ||
| # https://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. | ||
|
|
||
| # [START bigquerystorage_query_and_wait_arrow] | ||
| from typing import Iterable, Optional | ||
|
|
||
| from google.cloud import bigquery | ||
| from google.cloud.bigquery import enums | ||
| import pyarrow | ||
|
|
||
|
|
||
| def query_and_wait_arrow( | ||
| project_id: Optional[str] = None, | ||
| ) -> Iterable[pyarrow.RecordBatch]: | ||
| """Queries BigQuery and returns results as an iterable of Apache Arrow RecordBatches. | ||
|
|
||
| Args: | ||
| project_id (Optional[str]): The Google Cloud project ID to bill for the query. | ||
| If not specified, the project is inferred from the environment. | ||
|
|
||
| Returns: | ||
| Iterable[pyarrow.RecordBatch]: An iterable of Apache Arrow RecordBatch objects. | ||
| """ | ||
| # Initialize a BigQuery client. | ||
| client = bigquery.Client(project=project_id) if project_id else bigquery.Client() | ||
|
|
||
| query = """ | ||
| SELECT name, number, state | ||
| FROM `bigquery-public-data.usa_names.usa_1910_current` | ||
| LIMIT 100000 | ||
| """ | ||
|
|
||
| # Run the query and wait for results returned directly in Arrow format | ||
| # compressed with LZ4_FRAME. | ||
| results = client.query_and_wait( | ||
| query, | ||
| query_results_format=enums.QueryResultsFormat.ARROW, | ||
| compression_codec=enums.QueryResultsCompressionCodec.LZ4_FRAME, | ||
| ) | ||
|
|
||
| # Return results as an iterable of pyarrow.RecordBatch objects. | ||
| # Each batch contains a slice of the rows in Apache Arrow format. | ||
| batches = results.to_arrow_iterable() | ||
| return batches | ||
|
|
||
|
|
||
| # [END bigquerystorage_query_and_wait_arrow] |
35 changes: 35 additions & 0 deletions
35
packages/google-cloud-bigquery-storage/samples/snippets/query_and_wait_arrow_test.py
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,35 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # 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 | ||
| # | ||
| # https://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 | ||
|
|
||
| from . import query_and_wait_arrow | ||
|
|
||
|
|
||
| def test_query_and_wait_arrow(project_id: str): | ||
| batches = query_and_wait_arrow.query_and_wait_arrow(project_id=project_id) | ||
|
|
||
| total_rows = 0 | ||
| batch_count = 0 | ||
| for batch in batches: | ||
| assert isinstance(batch, pyarrow.RecordBatch) | ||
| assert batch.schema.names == ["name", "number", "state"] | ||
| assert batch.schema.field("name").type == pyarrow.string() | ||
| assert batch.schema.field("number").type == pyarrow.int64() | ||
| assert batch.schema.field("state").type == pyarrow.string() | ||
| total_rows += batch.num_rows | ||
| batch_count += 1 | ||
|
|
||
| assert total_rows == 100000 | ||
| assert batch_count > 0 |
77 changes: 77 additions & 0 deletions
77
packages/google-cloud-bigquery-storage/samples/snippets/read_rows_query_job.py
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,77 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # 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 | ||
| # | ||
| # https://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. | ||
|
|
||
| # [START bigquerystorage_read_rows_query_job] | ||
| from typing import Iterable, Optional | ||
|
|
||
| from google.cloud import bigquery | ||
| from google.cloud import bigquery_storage_v1 | ||
| import pyarrow | ||
|
|
||
|
|
||
| def read_rows_query_job( | ||
| project_id: Optional[str] = None, | ||
| ) -> Iterable[pyarrow.RecordBatch]: | ||
| """Queries BigQuery and yields batches directly via BigQueryReadClient using a job stream. | ||
|
|
||
| Args: | ||
| project_id (Optional[str]): The Google Cloud project ID to bill for the query. | ||
| If not specified, the project is inferred from the environment. | ||
|
|
||
| Yields: | ||
| pyarrow.RecordBatch: Apache Arrow RecordBatch objects streamed from BigQuery. | ||
| """ | ||
| # Initialize BigQuery and BigQuery Storage clients. | ||
| client = bigquery.Client(project=project_id) if project_id else bigquery.Client() | ||
| read_client = bigquery_storage_v1.BigQueryReadClient() | ||
|
|
||
| query = """ | ||
| SELECT name, number, state | ||
| FROM `bigquery-public-data.usa_names.usa_1910_current` | ||
| LIMIT 20000 | ||
| """ | ||
|
|
||
| # Start the query job. | ||
| job = client.query(query) | ||
|
|
||
| # Construct the job default stream name. | ||
| # Format: projects/{project_id}/locations/{location}/jobs/{job_id}/streams/_default | ||
| stream = f"projects/{job.project}/locations/{job.location}/jobs/{job.job_id}/streams/_default" | ||
|
|
||
| # Read rows directly from the stream using the Storage Read API. | ||
| schema: Optional[pyarrow.Schema] = None | ||
|
|
||
| for chunk in read_client.read_rows(name=stream, offset=0): | ||
| # Extract the schema from the first chunk that provides it. | ||
| if ( | ||
| schema is None | ||
| and chunk.arrow_schema | ||
| and chunk.arrow_schema.serialized_schema | ||
| ): | ||
| schema = pyarrow.ipc.read_schema( | ||
| pyarrow.py_buffer(chunk.arrow_schema.serialized_schema) | ||
| ) | ||
|
|
||
| # Deserialize and yield each record batch using the schema. | ||
| if ( | ||
| chunk.arrow_record_batch | ||
| and chunk.arrow_record_batch.serialized_record_batch | ||
| ): | ||
| yield pyarrow.ipc.read_record_batch( | ||
| pyarrow.py_buffer(chunk.arrow_record_batch.serialized_record_batch), | ||
| schema, | ||
| ) | ||
|
|
||
|
|
||
| # [END bigquerystorage_read_rows_query_job] | ||
35 changes: 35 additions & 0 deletions
35
packages/google-cloud-bigquery-storage/samples/snippets/read_rows_query_job_test.py
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,35 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # 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 | ||
| # | ||
| # https://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 | ||
|
|
||
| from . import read_rows_query_job | ||
|
|
||
|
|
||
| def test_read_rows_query_job(project_id: str): | ||
| batches = read_rows_query_job.read_rows_query_job(project_id=project_id) | ||
|
|
||
| total_rows = 0 | ||
| batch_count = 0 | ||
| for batch in batches: | ||
| assert isinstance(batch, pyarrow.RecordBatch) | ||
| assert batch.schema.names == ["name", "number", "state"] | ||
| assert batch.schema.field("name").type == pyarrow.string() | ||
| assert batch.schema.field("number").type == pyarrow.int64() | ||
| assert batch.schema.field("state").type == pyarrow.string() | ||
| total_rows += batch.num_rows | ||
| batch_count += 1 | ||
|
|
||
| assert total_rows == 20000 | ||
| assert batch_count > 0 |
3 changes: 3 additions & 0 deletions
3
packages/google-cloud-bigquery-storage/samples/snippets/requirements.txt
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 |
|---|---|---|
| @@ -1,6 +1,9 @@ | ||
| google-cloud-bigquery-storage==2.38.0 | ||
| google-cloud-bigquery===3.30.0; python_version <= '3.8' | ||
| google-cloud-bigquery==3.41.0; python_version >= '3.9' | ||
| pyarrow===12.0.1; python_version == '3.7' | ||
| pyarrow===17.0.0; python_version == '3.8' | ||
| pyarrow==24.0.0; python_version >= '3.9' | ||
| pytest===7.4.3; python_version == '3.7' | ||
| pytest===8.3.5; python_version == '3.8' | ||
| pytest==9.0.3; python_version >= '3.9' |
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.
The
client.query(query)method starts an asynchronous query job and returns immediately. Because the job runs asynchronously, attempting to construct the stream name and read from it immediately will fail since the job is still pending or running, and its results are not yet available (additionally,job.locationmay not be populated yet).To ensure the query has finished and the results are ready to be read from the stream, you must wait for the job to complete by calling
job.result().