Yes, it’s possible to create a partitioned table in BigQuery based on year and month. However, BigQuery itself does not support multi-level partitioning directly (e.g., partitioning by both year and month as separate fields). Instead, you would typically create a partitioned table based on a single date or timestamp column, and then use SQL functions to extract the year and month for querying.
Approach 1: Partitioning by Date or Timestamp Column
If your data includes a date or timestamp column, you can create a partitioned table using that column. You can then use SQL to extract the year and month for queries.
CREATE OR REPLACE TABLE `your_dataset.your_table`
PARTITION BY DATE_TRUNC(your_date_column, MONTH)
AS
SELECT
-- other columns
PARSE_DATE('%Y%m%d', CONCAT(year, month, '01')) AS your_date_column
FROM
`your_dataset.your_source_table`;
Approach 2: Partitioning Using Integer Ranges
If you don’t have a date or timestamp column, but have separate year and month fields, you can create a synthetic column combining these fields and then partition by it. For example:
- Creating the Partitioned Table:
CREATE OR REPLACE TABLE `your_dataset.your_partitioned_table`
PARTITION BY
RANGE_BUCKET(
CAST(CONCAT(year, FORMAT('%02d', month)) AS INT64),
GENERATE_ARRAY(201901, 203012, 1)
)
AS
SELECT
*,
CAST(CONCAT(year, FORMAT('%02d', month)) AS INT64) AS year_month
FROM
`your_dataset.your_source_table`;
- Loading Data:
You can load data from your source bucket into this table by using SQL or a Dataflow job that extracts and transforms the data accordingly.
Approach 3: Using External Tables with Hive Partitioning
If your files are stored in a bucket with a structure like bucket/year=xxxx/month=yy/, you can use an external table and take advantage of Hive-style partitioning:
CREATE OR REPLACE EXTERNAL TABLE `your_dataset.your_external_table`
OPTIONS(
format = 'CSV',
uris = ['gs://your_bucket/year=*/month=*/your_data_files.csv'],
hive_partitioning_mode = 'AUTO',
hive_partitioning_options = [
{mode = 'AUTO', sourceUriPrefix = 'gs://your_bucket/'}
]
);
Querying the Data
Once your table is partitioned, you can easily query it with filters on year and month:
SELECT *
FROM `your_dataset.your_table`
WHERE EXTRACT(YEAR FROM your_date_column) = 2023
AND EXTRACT(MONTH FROM your_date_column) = 07;