|
| 1 | +# Copyright 2022 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 | +import pathlib |
| 16 | + |
| 17 | + |
| 18 | +def load_table(table_id: str) -> None: |
| 19 | + orig_uri = "gs://cloud-samples-data/bigquery/us-states/us-states.csv" |
| 20 | + orig_table_id = table_id |
| 21 | + current_directory = pathlib.Path(__file__).parent |
| 22 | + orig_schema_path = str(current_directory / "schema_us_states.json") |
| 23 | + # [START bigquery_schema_file_load] |
| 24 | + from google.cloud import bigquery |
| 25 | + |
| 26 | + client = bigquery.Client() |
| 27 | + |
| 28 | + # TODO(dev): Change uri variable to the path of your data file. |
| 29 | + uri = "gs://your-bucket/path/to/your-file.csv" |
| 30 | + # TODO(dev): Change table_id to the full name of the table you want to create. |
| 31 | + table_id = "your-project.your_dataset.your_table" |
| 32 | + # TODO(dev): Change schema_path variable to the path of your schema file. |
| 33 | + schema_path = "path/to/schema.json" |
| 34 | + # [END bigquery_schema_file_load] |
| 35 | + uri = orig_uri |
| 36 | + table_id = orig_table_id |
| 37 | + schema_path = orig_schema_path |
| 38 | + # [START bigquery_schema_file_load] |
| 39 | + # To load a schema file use the schema_from_json method. |
| 40 | + schema = client.schema_from_json(schema_path) |
| 41 | + |
| 42 | + job_config = bigquery.LoadJobConfig( |
| 43 | + # To use the schema you loaded pass it into the |
| 44 | + # LoadJobConfig constructor. |
| 45 | + schema=schema, |
| 46 | + skip_leading_rows=1, |
| 47 | + ) |
| 48 | + |
| 49 | + # Pass the job_config object to the load_table_from_file, |
| 50 | + # load_table_from_json, or load_table_from_uri method |
| 51 | + # to use the schema on a new table. |
| 52 | + load_job = client.load_table_from_uri( |
| 53 | + uri, table_id, job_config=job_config |
| 54 | + ) # Make an API request. |
| 55 | + |
| 56 | + load_job.result() # Waits for the job to complete. |
| 57 | + |
| 58 | + destination_table = client.get_table(table_id) # Make an API request. |
| 59 | + print(f"Loaded {destination_table.num_rows} rows to {table_id}.") |
| 60 | + # [END bigquery_schema_file_load] |
0 commit comments