|
| 1 | +# Copyright 2019 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +def browse_table_data(table_id: str) -> None: |
| 17 | + # [START bigquery_browse_table] |
| 18 | + |
| 19 | + from google.cloud import bigquery |
| 20 | + |
| 21 | + # Construct a BigQuery client object. |
| 22 | + client = bigquery.Client() |
| 23 | + |
| 24 | + # TODO(developer): Set table_id to the ID of the table to browse data rows. |
| 25 | + # table_id = "your-project.your_dataset.your_table_name" |
| 26 | + |
| 27 | + # Download all rows from a table. |
| 28 | + rows_iter = client.list_rows(table_id) # Make an API request. |
| 29 | + |
| 30 | + # Iterate over rows to make the API requests to fetch row data. |
| 31 | + rows = list(rows_iter) |
| 32 | + print("Downloaded {} rows from table {}".format(len(rows), table_id)) |
| 33 | + |
| 34 | + # Download at most 10 rows. |
| 35 | + rows_iter = client.list_rows(table_id, max_results=10) |
| 36 | + rows = list(rows_iter) |
| 37 | + print("Downloaded {} rows from table {}".format(len(rows), table_id)) |
| 38 | + |
| 39 | + # Specify selected fields to limit the results to certain columns. |
| 40 | + table = client.get_table(table_id) # Make an API request. |
| 41 | + fields = table.schema[:2] # First two columns. |
| 42 | + rows_iter = client.list_rows(table_id, selected_fields=fields, max_results=10) |
| 43 | + print("Selected {} columns from table {}.".format(len(rows_iter.schema), table_id)) |
| 44 | + |
| 45 | + rows = list(rows_iter) |
| 46 | + print("Downloaded {} rows from table {}".format(len(rows), table_id)) |
| 47 | + |
| 48 | + # Print row data in tabular format. |
| 49 | + rows_iter = client.list_rows(table_id, max_results=10) |
| 50 | + format_string = "{!s:<16} " * len(rows_iter.schema) |
| 51 | + field_names = [field.name for field in rows_iter.schema] |
| 52 | + print(format_string.format(*field_names)) # Prints column headers. |
| 53 | + |
| 54 | + for row in rows_iter: |
| 55 | + print(format_string.format(*row)) # Prints row data. |
| 56 | + # [END bigquery_browse_table] |
0 commit comments