|
| 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 | + |
| 16 | +def nested_schema(table_id: str) -> None: |
| 17 | + orig_table_id = table_id |
| 18 | + # [START bigquery_nested_repeated_schema] |
| 19 | + from google.cloud import bigquery |
| 20 | + |
| 21 | + client = bigquery.Client() |
| 22 | + |
| 23 | + # TODO(dev): Change table_id to the full name of the table you want to create. |
| 24 | + table_id = "your-project.your_dataset.your_table_name" |
| 25 | + |
| 26 | + schema = [ |
| 27 | + bigquery.SchemaField("id", "STRING", mode="NULLABLE"), |
| 28 | + bigquery.SchemaField("first_name", "STRING", mode="NULLABLE"), |
| 29 | + bigquery.SchemaField("last_name", "STRING", mode="NULLABLE"), |
| 30 | + bigquery.SchemaField("dob", "DATE", mode="NULLABLE"), |
| 31 | + bigquery.SchemaField( |
| 32 | + "addresses", |
| 33 | + "RECORD", |
| 34 | + mode="REPEATED", |
| 35 | + fields=[ |
| 36 | + bigquery.SchemaField("status", "STRING", mode="NULLABLE"), |
| 37 | + bigquery.SchemaField("address", "STRING", mode="NULLABLE"), |
| 38 | + bigquery.SchemaField("city", "STRING", mode="NULLABLE"), |
| 39 | + bigquery.SchemaField("state", "STRING", mode="NULLABLE"), |
| 40 | + bigquery.SchemaField("zip", "STRING", mode="NULLABLE"), |
| 41 | + bigquery.SchemaField("numberOfYears", "STRING", mode="NULLABLE"), |
| 42 | + ], |
| 43 | + ), |
| 44 | + ] |
| 45 | + # [END bigquery_nested_repeated_schema] |
| 46 | + |
| 47 | + table_id = orig_table_id |
| 48 | + |
| 49 | + # [START bigquery_nested_repeated_schema] |
| 50 | + table = bigquery.Table(table_id, schema=schema) |
| 51 | + table = client.create_table(table) # API request |
| 52 | + |
| 53 | + print(f"Created table {table.project}.{table.dataset_id}.{table.table_id}.") |
| 54 | + # [END bigquery_nested_repeated_schema] |
0 commit comments