airflow.providers.google.cloud.operators.bigquery
¶
This module contains Google BigQuery operators.
Module Contents¶
Classes¶
Hex colors for BigQuery operators. |
|
Action to take if the resource exist. |
|
Helper class for constructing BigQuery link. |
|
Helper class for constructing BigQuery link. |
|
Performs checks against BigQuery. |
|
Perform a simple value check using sql code. |
|
Check that the values of metrics given as SQL expressions are within a tolerance of the older ones. |
|
Subclasses the SQLColumnCheckOperator in order to provide a job id for OpenLineage to parse. |
|
Subclasses the SQLTableCheckOperator in order to provide a job id for OpenLineage to parse. |
|
Fetches the data from a BigQuery table (alternatively fetch data for selected columns) and returns data. |
|
Executes BigQuery SQL queries in a specific BigQuery database. |
|
Creates a new table in the specified BigQuery dataset, optionally with schema. |
|
Create a new external table with data from Google Cloud Storage. |
|
Delete an existing dataset from your Project in BigQuery. |
|
Create a new dataset for your Project in BigQuery. |
|
Get the dataset specified by ID. |
|
Retrieve the list of tables in the specified dataset. |
|
Patch a dataset for your Project in BigQuery. |
|
Update a table for your Project in BigQuery. |
|
Update a dataset for your Project in BigQuery. |
|
Delete a BigQuery table. |
|
Upsert to a BigQuery table. |
|
Update BigQuery Table Schema. |
|
Execute a BigQuery job. |
Attributes¶
- airflow.providers.google.cloud.operators.bigquery.BIGQUERY_JOB_DETAILS_LINK_FMT = 'https://console.cloud.google.com/bigquery?j={job_id}'[source]¶
- class airflow.providers.google.cloud.operators.bigquery.BigQueryUIColors[source]¶
Bases:
enum.Enum
Hex colors for BigQuery operators.
- class airflow.providers.google.cloud.operators.bigquery.IfExistAction[source]¶
Bases:
enum.Enum
Action to take if the resource exist.
- class airflow.providers.google.cloud.operators.bigquery.BigQueryConsoleLink[source]¶
Bases:
airflow.models.BaseOperatorLink
Helper class for constructing BigQuery link.
- get_link(operator, *, ti_key)[source]¶
Link to external system.
Note: The old signature of this function was
(self, operator, dttm: datetime)
. That is still supported at runtime but is deprecated.- Parameters
operator (airflow.models.BaseOperator) – The Airflow operator object this link is associated to.
ti_key (airflow.models.taskinstancekey.TaskInstanceKey) – TaskInstance ID to return link for.
- Returns
link to external system
- class airflow.providers.google.cloud.operators.bigquery.BigQueryConsoleIndexableLink[source]¶
Bases:
airflow.models.BaseOperatorLink
Helper class for constructing BigQuery link.
- get_link(operator, *, ti_key)[source]¶
Link to external system.
Note: The old signature of this function was
(self, operator, dttm: datetime)
. That is still supported at runtime but is deprecated.- Parameters
operator (airflow.models.BaseOperator) – The Airflow operator object this link is associated to.
ti_key (airflow.models.taskinstancekey.TaskInstanceKey) – TaskInstance ID to return link for.
- Returns
link to external system
- class airflow.providers.google.cloud.operators.bigquery.BigQueryCheckOperator(*, sql, gcp_conn_id='google_cloud_default', use_legacy_sql=True, location=None, impersonation_chain=None, labels=None, deferrable=conf.getboolean('operators', 'default_deferrable', fallback=False), poll_interval=4.0, **kwargs)[source]¶
Bases:
_BigQueryDbHookMixin
,airflow.providers.common.sql.operators.sql.SQLCheckOperator
Performs checks against BigQuery.
This operator expects a SQL query that returns a single row. Each value on that row is evaluated using a Python
bool
cast. If any of the values is falsy, the check errors out.See also
For more information on how to use this operator, take a look at the guide: Check if query result has data
Note that Python bool casting evals the following as False:
False
0
Empty string (
""
)Empty list (
[]
)Empty dictionary or set (
{}
)
Given a query like
SELECT COUNT(*) FROM foo
, it will fail only if the count equals to zero. You can craft much more complex query that could, for instance, check that the table has the same number of rows as the source table upstream, or that the count of today’s partition is greater than yesterday’s partition, or that a set of metrics are less than three standard deviation for the 7-day average.This operator can be used as a data quality check in your pipeline. Depending on where you put it in your DAG, you have the choice to stop the critical path, preventing from publishing dubious data, or on the side and receive email alerts without stopping the progress of the DAG.
- Parameters
sql (str) – SQL to execute.
gcp_conn_id (str) – Connection ID for Google Cloud.
use_legacy_sql (bool) – Whether to use legacy SQL (true) or standard SQL (false).
location (str | None) – The geographic location of the job. See details at: https://cloud.google.com/bigquery/docs/locations#specifying_your_location
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account. (templated)
labels (dict | None) – a dictionary containing labels for the table, passed to BigQuery.
deferrable (bool) – Run operator in the deferrable mode.
poll_interval (float) – (Deferrable mode only) polling period in seconds to check for the status of job.
- class airflow.providers.google.cloud.operators.bigquery.BigQueryValueCheckOperator(*, sql, pass_value, tolerance=None, gcp_conn_id='google_cloud_default', use_legacy_sql=True, location=None, impersonation_chain=None, labels=None, deferrable=conf.getboolean('operators', 'default_deferrable', fallback=False), poll_interval=4.0, **kwargs)[source]¶
Bases:
_BigQueryDbHookMixin
,airflow.providers.common.sql.operators.sql.SQLValueCheckOperator
Perform a simple value check using sql code.
See also
For more information on how to use this operator, take a look at the guide: Compare query result to pass value
- Parameters
sql (str) – SQL to execute.
use_legacy_sql (bool) – Whether to use legacy SQL (true) or standard SQL (false).
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
location (str | None) – The geographic location of the job. See details at: https://cloud.google.com/bigquery/docs/locations#specifying_your_location
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account. (templated)
labels (dict | None) – a dictionary containing labels for the table, passed to BigQuery.
deferrable (bool) – Run operator in the deferrable mode.
poll_interval (float) – (Deferrable mode only) polling period in seconds to check for the status of job.
- template_fields: Sequence[str] = ('sql', 'gcp_conn_id', 'pass_value', 'impersonation_chain', 'labels')[source]¶
- class airflow.providers.google.cloud.operators.bigquery.BigQueryIntervalCheckOperator(*, table, metrics_thresholds, date_filter_column='ds', days_back=-7, gcp_conn_id='google_cloud_default', use_legacy_sql=True, location=None, impersonation_chain=None, labels=None, deferrable=conf.getboolean('operators', 'default_deferrable', fallback=False), poll_interval=4.0, project_id=None, **kwargs)[source]¶
Bases:
_BigQueryDbHookMixin
,airflow.providers.common.sql.operators.sql.SQLIntervalCheckOperator
Check that the values of metrics given as SQL expressions are within a tolerance of the older ones.
This method constructs a query like so
SELECT {metrics_threshold_dict_key} FROM {table} WHERE {date_filter_column}=<date>
See also
For more information on how to use this operator, take a look at the guide: Compare metrics over time
- Parameters
table (str) – the table name
days_back (SupportsAbs[int]) – number of days between ds and the ds we want to check against. Defaults to 7 days
metrics_thresholds (dict) – a dictionary of ratios indexed by metrics, for example ‘COUNT(*)’: 1.5 would require a 50 percent or less difference between the current day, and the prior days_back.
use_legacy_sql (bool) – Whether to use legacy SQL (true) or standard SQL (false).
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
location (str | None) – The geographic location of the job. See details at: https://cloud.google.com/bigquery/docs/locations#specifying_your_location
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
labels (dict | None) – a dictionary containing labels for the table, passed to BigQuery
deferrable (bool) – Run operator in the deferrable mode
poll_interval (float) – (Deferrable mode only) polling period in seconds to check for the status of job. Defaults to 4 seconds.
project_id (str | None) – a string represents the BigQuery projectId
- template_fields: Sequence[str] = ('table', 'gcp_conn_id', 'sql1', 'sql2', 'impersonation_chain', 'labels')[source]¶
- class airflow.providers.google.cloud.operators.bigquery.BigQueryColumnCheckOperator(*, table, column_mapping, partition_clause=None, database=None, accept_none=True, gcp_conn_id='google_cloud_default', use_legacy_sql=True, location=None, impersonation_chain=None, labels=None, **kwargs)[source]¶
Bases:
_BigQueryDbHookMixin
,airflow.providers.common.sql.operators.sql.SQLColumnCheckOperator
Subclasses the SQLColumnCheckOperator in order to provide a job id for OpenLineage to parse.
See base class docstring for usage.
See also
For more information on how to use this operator, take a look at the guide: Check columns with predefined tests
- Parameters
table (str) – the table name
column_mapping (dict) – a dictionary relating columns to their checks
partition_clause (str | None) – a string SQL statement added to a WHERE clause to partition data
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
use_legacy_sql (bool) – Whether to use legacy SQL (true) or standard SQL (false).
location (str | None) – The geographic location of the job. See details at: https://cloud.google.com/bigquery/docs/locations#specifying_your_location
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
labels (dict | None) – a dictionary containing labels for the table, passed to BigQuery
- class airflow.providers.google.cloud.operators.bigquery.BigQueryTableCheckOperator(*, table, checks, partition_clause=None, gcp_conn_id='google_cloud_default', use_legacy_sql=True, location=None, impersonation_chain=None, labels=None, **kwargs)[source]¶
Bases:
_BigQueryDbHookMixin
,airflow.providers.common.sql.operators.sql.SQLTableCheckOperator
Subclasses the SQLTableCheckOperator in order to provide a job id for OpenLineage to parse.
See base class for usage.
See also
For more information on how to use this operator, take a look at the guide: Check table level data quality
- Parameters
table (str) – the table name
checks (dict) – a dictionary of check names and boolean SQL statements
partition_clause (str | None) – a string SQL statement added to a WHERE clause to partition data
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
use_legacy_sql (bool) – Whether to use legacy SQL (true) or standard SQL (false).
location (str | None) – The geographic location of the job. See details at: https://cloud.google.com/bigquery/docs/locations#specifying_your_location
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
labels (dict | None) – a dictionary containing labels for the table, passed to BigQuery
- class airflow.providers.google.cloud.operators.bigquery.BigQueryGetDataOperator(*, dataset_id, table_id, table_project_id=None, job_project_id=None, project_id=None, max_results=100, selected_fields=None, gcp_conn_id='google_cloud_default', location=None, impersonation_chain=None, deferrable=conf.getboolean('operators', 'default_deferrable', fallback=False), poll_interval=4.0, as_dict=False, use_legacy_sql=True, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Fetches the data from a BigQuery table (alternatively fetch data for selected columns) and returns data.
Data is returned in either of the following two formats, based on “as_dict” value: 1. False (Default) - A Python list of lists, with the number of nested lists equal to the number of rows fetched. Each nested list represents a row, where the elements within it correspond to the column values for that particular row.
Example Result:
[['Tony', 10], ['Mike', 20]
2. True - A Python list of dictionaries, where each dictionary represents a row. In each dictionary, the keys are the column names and the values are the corresponding values for those columns.
Example Result:
[{'name': 'Tony', 'age': 10}, {'name': 'Mike', 'age': 20}]
See also
For more information on how to use this operator, take a look at the guide: Fetch data from table
Note
If you pass fields to
selected_fields
which are in different order than the order of columns already in BQ table, the data will still be in the order of BQ table. For example if the BQ table has 3 columns as[A,B,C]
and you pass ‘B,A’ in theselected_fields
the data would still be of the form'A,B'
.Example:
get_data = BigQueryGetDataOperator( task_id='get_data_from_bq', dataset_id='test_dataset', table_id='Transaction_partitions', project_id='internal-gcp-project', max_results=100, selected_fields='DATE', gcp_conn_id='airflow-conn-id' )
- Parameters
dataset_id (str) – The dataset ID of the requested table. (templated)
table_id (str) – The table ID of the requested table. (templated)
table_project_id (str | None) – (Optional) The project ID of the requested table. If None, it will be derived from the hook’s project ID. (templated)
job_project_id (str | None) – (Optional) Google Cloud Project where the job is running. If None, it will be derived from the hook’s project ID. (templated)
project_id (str | None) – (Deprecated) (Optional) The name of the project where the data will be returned from. If None, it will be derived from the hook’s project ID. (templated)
max_results (int) – The maximum number of records (rows) to be fetched from the table. (templated)
selected_fields (str | None) – List of fields to return (comma-separated). If unspecified, all fields are returned.
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
location (str | None) – The location used for the operation.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
deferrable (bool) – Run operator in the deferrable mode
poll_interval (float) – (Deferrable mode only) polling period in seconds to check for the status of job. Defaults to 4 seconds.
as_dict (bool) – if True returns the result as a list of dictionaries, otherwise as list of lists (default: False).
use_legacy_sql (bool) – Whether to use legacy SQL (true) or standard SQL (false).
- template_fields: Sequence[str] = ('dataset_id', 'table_id', 'table_project_id', 'job_project_id', 'project_id', 'max_results',...[source]¶
- class airflow.providers.google.cloud.operators.bigquery.BigQueryExecuteQueryOperator(*, sql, destination_dataset_table=None, write_disposition='WRITE_EMPTY', allow_large_results=False, flatten_results=None, gcp_conn_id='google_cloud_default', udf_config=None, use_legacy_sql=True, maximum_billing_tier=None, maximum_bytes_billed=None, create_disposition='CREATE_IF_NEEDED', schema_update_options=None, query_params=None, labels=None, priority='INTERACTIVE', time_partitioning=None, api_resource_configs=None, cluster_fields=None, location=None, encryption_configuration=None, impersonation_chain=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Executes BigQuery SQL queries in a specific BigQuery database.
This operator is deprecated. Please use
airflow.providers.google.cloud.operators.bigquery.BigQueryInsertJobOperator
instead.This operator does not assert idempotency.
- Parameters
sql (str | Iterable[str]) – the SQL code to be executed as a single string, or a list of str (sql statements), or a reference to a template file. Template references are recognized by str ending in ‘.sql’
destination_dataset_table (str | None) – A dotted
(<project>.|<project>:)<dataset>.<table>
that, if set, will store the results of the query. (templated)write_disposition (str) – Specifies the action that occurs if the destination table already exists. (default: ‘WRITE_EMPTY’)
create_disposition (str) – Specifies whether the job is allowed to create new tables. (default: ‘CREATE_IF_NEEDED’)
allow_large_results (bool) – Whether to allow large results.
flatten_results (bool | None) – If true and query uses legacy SQL dialect, flattens all nested and repeated fields in the query results.
allow_large_results
must betrue
if this is set tofalse
. For standard SQL queries, this flag is ignored and results are never flattened.gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
udf_config (list | None) – The User Defined Function configuration for the query. See https://cloud.google.com/bigquery/user-defined-functions for details.
use_legacy_sql (bool) – Whether to use legacy SQL (true) or standard SQL (false).
maximum_billing_tier (int | None) – Positive integer that serves as a multiplier of the basic price. Defaults to None, in which case it uses the value set in the project.
maximum_bytes_billed (float | None) – Limits the bytes billed for this job. Queries that will have bytes billed beyond this limit will fail (without incurring a charge). If unspecified, this will be set to your project default.
api_resource_configs (dict | None) – a dictionary that contain params ‘configuration’ applied for Google BigQuery Jobs API: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs for example, {‘query’: {‘useQueryCache’: False}}. You could use it if you need to provide some params that are not supported by BigQueryOperator like args.
schema_update_options (list | tuple | set | None) – Allows the schema of the destination table to be updated as a side effect of the load job.
query_params (list | None) – a list of dictionary containing query parameter types and values, passed to BigQuery. The structure of dictionary should look like ‘queryParameters’ in Google BigQuery Jobs API: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs. For example, [{ ‘name’: ‘corpus’, ‘parameterType’: { ‘type’: ‘STRING’ }, ‘parameterValue’: { ‘value’: ‘romeoandjuliet’ } }]. (templated)
labels (dict | None) – a dictionary containing labels for the job/query, passed to BigQuery
priority (str) – Specifies a priority for the query. Possible values include INTERACTIVE and BATCH. The default value is INTERACTIVE.
time_partitioning (dict | None) – configure optional time partitioning fields i.e. partition by field, type and expiration as per API specifications.
cluster_fields (list[str] | None) – Request that the result of this query be stored sorted by one or more columns. BigQuery supports clustering for both partitioned and non-partitioned tables. The order of columns given determines the sort order.
location (str | None) – The geographic location of the job. Required except for US and EU. See details at https://cloud.google.com/bigquery/docs/locations#specifying_your_location
encryption_configuration (dict | None) –
[Optional] Custom encryption configuration (e.g., Cloud KMS keys).
encryption_configuration = { "kmsKeyName": "projects/testp/locations/us/keyRings/test-kr/cryptoKeys/test-key", }
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
- template_fields: Sequence[str] = ('sql', 'destination_dataset_table', 'labels', 'query_params', 'impersonation_chain')[source]¶
- class airflow.providers.google.cloud.operators.bigquery.BigQueryCreateEmptyTableOperator(*, dataset_id, table_id, table_resource=None, project_id=None, schema_fields=None, gcs_schema_object=None, time_partitioning=None, gcp_conn_id='google_cloud_default', google_cloud_storage_conn_id='google_cloud_default', labels=None, view=None, materialized_view=None, encryption_configuration=None, location=None, cluster_fields=None, impersonation_chain=None, if_exists='log', bigquery_conn_id=None, exists_ok=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Creates a new table in the specified BigQuery dataset, optionally with schema.
The schema to be used for the BigQuery table may be specified in one of two ways. You may either directly pass the schema fields in, or you may point the operator to a Google Cloud Storage object name. The object in Google Cloud Storage must be a JSON file with the schema fields in it. You can also create a table without schema.
See also
For more information on how to use this operator, take a look at the guide: Create native table
- Parameters
project_id (str | None) – The project to create the table into. (templated)
dataset_id (str) – The dataset to create the table into. (templated)
table_id (str) – The Name of the table to be created. (templated)
table_resource (dict[str, Any] | None) – Table resource as described in documentation: https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#Table If provided all other parameters are ignored. (templated)
schema_fields (list | None) –
If set, the schema field list as defined here: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.schema
Example:
schema_fields=[{"name": "emp_name", "type": "STRING", "mode": "REQUIRED"}, {"name": "salary", "type": "INTEGER", "mode": "NULLABLE"}]
gcs_schema_object (str | None) – Full path to the JSON file containing schema (templated). For example:
gs://test-bucket/dir1/dir2/employee_schema.json
time_partitioning (dict | None) –
configure optional time partitioning fields i.e. partition by field, type and expiration as per API specifications.
gcp_conn_id (str) – [Optional] The connection ID used to connect to Google Cloud and interact with the Bigquery service.
google_cloud_storage_conn_id (str) – [Optional] The connection ID used to connect to Google Cloud. and interact with the Google Cloud Storage service.
labels (dict | None) – a dictionary containing labels for the table, passed to BigQuery
Example (with schema JSON in GCS):
CreateTable = BigQueryCreateEmptyTableOperator( task_id='BigQueryCreateEmptyTableOperator_task', dataset_id='ODS', table_id='Employees', project_id='internal-gcp-project', gcs_schema_object='gs://schema-bucket/employee_schema.json', gcp_conn_id='airflow-conn-id', google_cloud_storage_conn_id='airflow-conn-id' )
Corresponding Schema file (
employee_schema.json
):[ { "mode": "NULLABLE", "name": "emp_name", "type": "STRING" }, { "mode": "REQUIRED", "name": "salary", "type": "INTEGER" } ]
Example (with schema in the DAG):
CreateTable = BigQueryCreateEmptyTableOperator( task_id='BigQueryCreateEmptyTableOperator_task', dataset_id='ODS', table_id='Employees', project_id='internal-gcp-project', schema_fields=[{"name": "emp_name", "type": "STRING", "mode": "REQUIRED"}, {"name": "salary", "type": "INTEGER", "mode": "NULLABLE"}], gcp_conn_id='airflow-conn-id-account', google_cloud_storage_conn_id='airflow-conn-id' )
- Parameters
view (dict | None) –
[Optional] A dictionary containing definition for the view. If set, it will create a view instead of a table:
materialized_view (dict | None) – [Optional] The materialized view definition.
encryption_configuration (dict | None) –
[Optional] Custom encryption configuration (e.g., Cloud KMS keys).
encryption_configuration = { "kmsKeyName": "projects/testp/locations/us/keyRings/test-kr/cryptoKeys/test-key", }
location (str | None) – The location used for the operation.
cluster_fields (list[str] | None) –
[Optional] The fields used for clustering. BigQuery supports clustering for both partitioned and non-partitioned tables.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
if_exists (str) – What should Airflow do if the table exists. If set to log, the TI will be passed to success and an error message will be logged. Set to ignore to ignore the error, set to fail to fail the TI, and set to skip to skip it.
exists_ok (bool | None) – Deprecated - use if_exists=”ignore” instead.
- class airflow.providers.google.cloud.operators.bigquery.BigQueryCreateExternalTableOperator(*, bucket=None, source_objects=None, destination_project_dataset_table=None, table_resource=None, schema_fields=None, schema_object=None, gcs_schema_bucket=None, source_format=None, autodetect=False, compression=None, skip_leading_rows=None, field_delimiter=None, max_bad_records=0, quote_character=None, allow_quoted_newlines=False, allow_jagged_rows=False, gcp_conn_id='google_cloud_default', google_cloud_storage_conn_id='google_cloud_default', src_fmt_configs=None, labels=None, encryption_configuration=None, location=None, impersonation_chain=None, bigquery_conn_id=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Create a new external table with data from Google Cloud Storage.
The schema to be used for the BigQuery table may be specified in one of two ways. You may either directly pass the schema fields in, or you may point the operator to a Google Cloud Storage object name. The object in Google Cloud Storage must be a JSON file with the schema fields in it.
See also
For more information on how to use this operator, take a look at the guide: Create external table
- Parameters
bucket (str | None) – The bucket to point the external table to. (templated)
source_objects (list[str] | None) – List of Google Cloud Storage URIs to point table to. If source_format is ‘DATASTORE_BACKUP’, the list must only contain a single URI.
destination_project_dataset_table (str | None) – The dotted
(<project>.)<dataset>.<table>
BigQuery table to load data into (templated). If<project>
is not included, project will be the project defined in the connection json.schema_fields (list | None) –
If set, the schema field list as defined here: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.schema
Example:
schema_fields=[{"name": "emp_name", "type": "STRING", "mode": "REQUIRED"}, {"name": "salary", "type": "INTEGER", "mode": "NULLABLE"}]
Should not be set when source_format is ‘DATASTORE_BACKUP’.
table_resource (dict[str, Any] | None) – Table resource as described in documentation: https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#Table If provided all other parameters are ignored. External schema from object will be resolved.
schema_object (str | None) – If set, a GCS object path pointing to a .json file that contains the schema for the table. (templated)
gcs_schema_bucket (str | None) – GCS bucket name where the schema JSON is stored (templated). The default value is self.bucket.
source_format (str | None) – File format of the data.
autodetect (bool) – Try to detect schema and format options automatically. The schema_fields and schema_object options will be honored when specified explicitly. https://cloud.google.com/bigquery/docs/schema-detect#schema_auto-detection_for_external_data_sources
compression (str | None) – [Optional] The compression type of the data source. Possible values include GZIP and NONE. The default value is NONE. This setting is ignored for Google Cloud Bigtable, Google Cloud Datastore backups and Avro formats.
skip_leading_rows (int | None) – Number of rows to skip when loading from a CSV.
field_delimiter (str | None) – The delimiter to use for the CSV.
max_bad_records (int) – The maximum number of bad records that BigQuery can ignore when running the job.
quote_character (str | None) – The value that is used to quote data sections in a CSV file.
allow_quoted_newlines (bool) – Whether to allow quoted newlines (true) or not (false).
allow_jagged_rows (bool) – Accept rows that are missing trailing optional columns. The missing values are treated as nulls. If false, records with missing trailing columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. Only applicable to CSV, ignored for other formats.
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud and interact with the Bigquery service.
google_cloud_storage_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud and interact with the Google Cloud Storage service.
src_fmt_configs (dict | None) – configure optional fields specific to the source format
labels (dict | None) – a dictionary containing labels for the table, passed to BigQuery
encryption_configuration (dict | None) –
[Optional] Custom encryption configuration (e.g., Cloud KMS keys).
encryption_configuration = { "kmsKeyName": "projects/testp/locations/us/keyRings/test-kr/cryptoKeys/test-key", }
location (str | None) – The location used for the operation.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
- class airflow.providers.google.cloud.operators.bigquery.BigQueryDeleteDatasetOperator(*, dataset_id, project_id=None, delete_contents=False, gcp_conn_id='google_cloud_default', impersonation_chain=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Delete an existing dataset from your Project in BigQuery.
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/delete
See also
For more information on how to use this operator, take a look at the guide: Delete dataset
- Parameters
project_id (str | None) – The project id of the dataset.
dataset_id (str) – The dataset to be deleted.
delete_contents (bool) – (Optional) Whether to force the deletion even if the dataset is not empty. Will delete all tables (if any) in the dataset if set to True. Will raise HttpError 400: “{dataset_id} is still in use” if set to False and dataset is not empty. The default value is False.
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
Example:
delete_temp_data = BigQueryDeleteDatasetOperator( dataset_id='temp-dataset', project_id='temp-project', delete_contents=True, # Force the deletion of the dataset as well as its tables (if any). gcp_conn_id='_my_gcp_conn_', task_id='Deletetemp', dag=dag)
- class airflow.providers.google.cloud.operators.bigquery.BigQueryCreateEmptyDatasetOperator(*, dataset_id=None, project_id=None, dataset_reference=None, location=None, gcp_conn_id='google_cloud_default', impersonation_chain=None, if_exists='log', exists_ok=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Create a new dataset for your Project in BigQuery.
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets#resource
See also
For more information on how to use this operator, take a look at the guide: Create dataset
- Parameters
project_id (str | None) – The name of the project where we want to create the dataset.
dataset_id (str | None) – The id of dataset. Don’t need to provide, if datasetId in dataset_reference.
location (str | None) – The geographic location where the dataset should reside.
dataset_reference (dict | None) – Dataset reference that could be provided with request body. More info: https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets#resource
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
if_exists (str) –
What should Airflow do if the dataset exists. If set to log, the TI will be passed to success and an error message will be logged. Set to ignore to ignore the error, set to fail to fail the TI, and set to skip to skip it. Example:
create_new_dataset = BigQueryCreateEmptyDatasetOperator( dataset_id='new-dataset', project_id='my-project', dataset_reference={"friendlyName": "New Dataset"} gcp_conn_id='_my_gcp_conn_', task_id='newDatasetCreator', dag=dag)
exists_ok (bool | None) – Deprecated - use if_exists=”ignore” instead.
- class airflow.providers.google.cloud.operators.bigquery.BigQueryGetDatasetOperator(*, dataset_id, project_id=None, gcp_conn_id='google_cloud_default', impersonation_chain=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Get the dataset specified by ID.
See also
For more information on how to use this operator, take a look at the guide: Get dataset details
- Parameters
dataset_id (str) – The id of dataset. Don’t need to provide, if datasetId in dataset_reference.
project_id (str | None) – The name of the project where we want to create the dataset. Don’t need to provide, if projectId in dataset_reference.
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
- class airflow.providers.google.cloud.operators.bigquery.BigQueryGetDatasetTablesOperator(*, dataset_id, project_id=None, max_results=None, gcp_conn_id='google_cloud_default', impersonation_chain=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Retrieve the list of tables in the specified dataset.
See also
For more information on how to use this operator, take a look at the guide: List tables in dataset
- Parameters
dataset_id (str) – the dataset ID of the requested dataset.
project_id (str | None) – (Optional) the project of the requested dataset. If None, self.project_id will be used.
max_results (int | None) – (Optional) the maximum number of tables to return.
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
- class airflow.providers.google.cloud.operators.bigquery.BigQueryPatchDatasetOperator(*, dataset_id, dataset_resource, project_id=None, gcp_conn_id='google_cloud_default', impersonation_chain=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Patch a dataset for your Project in BigQuery.
This operator is deprecated. Please use
airflow.providers.google.cloud.operators.bigquery.BigQueryUpdateTableOperator
instead.Only replaces fields that are provided in the submitted dataset resource.
- Parameters
dataset_id (str) – The id of dataset. Don’t need to provide, if datasetId in dataset_reference.
dataset_resource (dict) – Dataset resource that will be provided with request body. https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets#resource
project_id (str | None) – The name of the project where we want to create the dataset. Don’t need to provide, if projectId in dataset_reference.
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
- class airflow.providers.google.cloud.operators.bigquery.BigQueryUpdateTableOperator(*, table_resource, fields=None, dataset_id=None, table_id=None, project_id=None, gcp_conn_id='google_cloud_default', impersonation_chain=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Update a table for your Project in BigQuery.
Use
fields
to specify which fields of table to update. If a field is listed infields
and isNone
in table, it will be deleted.See also
For more information on how to use this operator, take a look at the guide: Update table
- Parameters
dataset_id (str | None) – The id of dataset. Don’t need to provide, if datasetId in table_reference.
table_id (str | None) – The id of table. Don’t need to provide, if tableId in table_reference.
table_resource (dict[str, Any]) – Dataset resource that will be provided with request body. https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#resource
fields (list[str] | None) – The fields of
table
to change, spelled as the Table properties (e.g. “friendly_name”).project_id (str | None) – The name of the project where we want to create the table. Don’t need to provide, if projectId in table_reference.
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
- class airflow.providers.google.cloud.operators.bigquery.BigQueryUpdateDatasetOperator(*, dataset_resource, fields=None, dataset_id=None, project_id=None, gcp_conn_id='google_cloud_default', impersonation_chain=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Update a dataset for your Project in BigQuery.
Use
fields
to specify which fields of dataset to update. If a field is listed infields
and isNone
in dataset, it will be deleted. If nofields
are provided then all fields of provideddataset_resource
will be used.See also
For more information on how to use this operator, take a look at the guide: Update dataset
- Parameters
dataset_id (str | None) – The id of dataset. Don’t need to provide, if datasetId in dataset_reference.
dataset_resource (dict[str, Any]) – Dataset resource that will be provided with request body. https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets#resource
fields (list[str] | None) – The properties of dataset to change (e.g. “friendly_name”).
project_id (str | None) – The name of the project where we want to create the dataset. Don’t need to provide, if projectId in dataset_reference.
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
- class airflow.providers.google.cloud.operators.bigquery.BigQueryDeleteTableOperator(*, deletion_dataset_table, gcp_conn_id='google_cloud_default', ignore_if_missing=False, location=None, impersonation_chain=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Delete a BigQuery table.
See also
For more information on how to use this operator, take a look at the guide: Delete table
- Parameters
deletion_dataset_table (str) – A dotted
(<project>.|<project>:)<dataset>.<table>
that indicates which table will be deleted. (templated)gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
ignore_if_missing (bool) – if True, then return success even if the requested table does not exist.
location (str | None) – The location used for the operation.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
- class airflow.providers.google.cloud.operators.bigquery.BigQueryUpsertTableOperator(*, dataset_id, table_resource, project_id=None, gcp_conn_id='google_cloud_default', location=None, impersonation_chain=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Upsert to a BigQuery table.
See also
For more information on how to use this operator, take a look at the guide: Upsert table
- Parameters
dataset_id (str) – A dotted
(<project>.|<project>:)<dataset>
that indicates which dataset will be updated. (templated)table_resource (dict) – a table resource. see https://cloud.google.com/bigquery/docs/reference/v2/tables#resource
project_id (str | None) – The name of the project where we want to update the dataset. Don’t need to provide, if projectId in dataset_reference.
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
location (str | None) – The location used for the operation.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
- class airflow.providers.google.cloud.operators.bigquery.BigQueryUpdateTableSchemaOperator(*, schema_fields_updates, dataset_id, table_id, include_policy_tags=False, project_id=None, gcp_conn_id='google_cloud_default', impersonation_chain=None, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
Update BigQuery Table Schema.
Updates fields on a table schema based on contents of the supplied schema_fields_updates parameter. The supplied schema does not need to be complete, if the field already exists in the schema you only need to supply keys & values for the items you want to patch, just ensure the “name” key is set.
See also
For more information on how to use this operator, take a look at the guide: Update table schema
- Parameters
schema_fields_updates (list[dict[str, Any]]) –
a partial schema resource. see https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#TableSchema
schema_fields_updates = [ {"name": "emp_name", "description": "Some New Description"}, { "name": "salary", "policyTags": {"names": ["some_new_policy_tag"]}, }, { "name": "departments", "fields": [ {"name": "name", "description": "Some New Description"}, {"name": "type", "description": "Some New Description"}, ], }, ]
include_policy_tags (bool) – (Optional) If set to True policy tags will be included in the update request which requires special permissions even if unchanged (default False) see https://cloud.google.com/bigquery/docs/column-level-security#roles
dataset_id (str) – A dotted
(<project>.|<project>:)<dataset>
that indicates which dataset will be updated. (templated)table_id (str) – The table ID of the requested table. (templated)
project_id (str | None) – The name of the project where we want to update the dataset. Don’t need to provide, if projectId in dataset_reference.
gcp_conn_id (str) – (Optional) The connection ID used to connect to Google Cloud.
location – The location used for the operation.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
- class airflow.providers.google.cloud.operators.bigquery.BigQueryInsertJobOperator(configuration, project_id=None, location=None, job_id=None, force_rerun=True, reattach_states=None, gcp_conn_id='google_cloud_default', impersonation_chain=None, cancel_on_kill=True, result_retry=DEFAULT_RETRY, result_timeout=None, deferrable=conf.getboolean('operators', 'default_deferrable', fallback=False), poll_interval=4.0, **kwargs)[source]¶
Bases:
airflow.providers.google.cloud.operators.cloud_base.GoogleCloudBaseOperator
,_BigQueryOpenLineageMixin
Execute a BigQuery job.
Waits for the job to complete and returns job id. This operator work in the following way:
it calculates a unique hash of the job using job’s configuration or uuid if
force_rerun
is True- creates
job_id
in form of [provided_job_id | airflow_{dag_id}_{task_id}_{exec_date}]_{uniqueness_suffix}
- creates
submits a BigQuery job using the
job_id
- if job with given id already exists then it tries to reattach to the job if its not done and its
state is in
reattach_states
. If the job is done the operator will raiseAirflowException
.
Using
force_rerun
will submit a new job every time without attaching to already existing ones.For job definition see here:
See also
For more information on how to use this operator, take a look at the guide: Execute BigQuery jobs
- Parameters
configuration (dict[str, Any]) – The configuration parameter maps directly to BigQuery’s configuration field in the job object. For more details see https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#jobconfiguration
job_id (str | None) – The ID of the job. It will be suffixed with hash of job configuration unless
force_rerun
is True. The ID must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-). The maximum length is 1,024 characters. If not provided then uuid will be generated.force_rerun (bool) – If True then operator will use hash of uuid as job id suffix
reattach_states (set[str] | None) – Set of BigQuery job’s states in case of which we should reattach to the job. Should be other than final states.
project_id (str | None) – Google Cloud Project where the job is running
location (str | None) – location the job is running
gcp_conn_id (str) – The connection ID used to connect to Google Cloud.
impersonation_chain (str | Sequence[str] | None) – Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated).
cancel_on_kill (bool) – Flag which indicates whether cancel the hook’s job or not, when on_kill is called
result_retry (google.api_core.retry.Retry) – How to retry the result call that retrieves rows
result_timeout (float | None) – The number of seconds to wait for result method before using result_retry
deferrable (bool) – Run operator in the deferrable mode
poll_interval (float) – (Deferrable mode only) polling period in seconds to check for the status of job. Defaults to 4 seconds.
- template_fields: Sequence[str] = ('configuration', 'job_id', 'impersonation_chain', 'project_id')[source]¶
- prepare_template()[source]¶
Execute after the templated fields get replaced by their content.
If you need your object to alter the content of the file before the template is rendered, it should override this method to do so.
- execute(context)[source]¶
Derive when creating an operator.
Context is the same dictionary used as when rendering jinja templates.
Refer to get_template_context for more context.