|
| 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 create_partitioned_table(table_id): |
| 17 | + your_fully_qualified_table_id = table_id |
| 18 | + |
| 19 | + # [START bigquery_create_table_partitioned] |
| 20 | + from google.cloud import bigquery |
| 21 | + |
| 22 | + client = bigquery.Client() |
| 23 | + |
| 24 | + # Use format "your-project.your_dataset.your_table_name" for table_id |
| 25 | + table_id = your_fully_qualified_table_id |
| 26 | + schema = [ |
| 27 | + bigquery.SchemaField("name", "STRING"), |
| 28 | + bigquery.SchemaField("post_abbr", "STRING"), |
| 29 | + bigquery.SchemaField("date", "DATE"), |
| 30 | + ] |
| 31 | + table = bigquery.Table(table_id, schema=schema) |
| 32 | + table.time_partitioning = bigquery.TimePartitioning( |
| 33 | + type_=bigquery.TimePartitioningType.DAY, |
| 34 | + field="date", # name of column to use for partitioning |
| 35 | + expiration_ms=1000 * 60 * 60 * 24 * 90, |
| 36 | + ) # 90 days |
| 37 | + |
| 38 | + table = client.create_table(table) |
| 39 | + |
| 40 | + print( |
| 41 | + f"Created table {table.project}.{table.dataset_id}.{table.table_id}, " |
| 42 | + f"partitioned on column {table.time_partitioning.field}." |
| 43 | + ) |
| 44 | + # [END bigquery_create_table_partitioned] |
| 45 | + return table |
0 commit comments