Skip to main content

BigQuery

Ingesting metadata from Bigquery requires using the bigquery module.

Module bigquery

Certified

Important Capabilities

CapabilityStatusNotes
Asset ContainersEnabled by default
Data ProfilingOptionally enabled via configuration
DescriptionsEnabled by default
Detect Deleted EntitiesOptionally enabled via stateful_ingestion.remove_stale_metadata
DomainsSupported via the domain config field
Platform InstanceNot supported since BigQuery project ids are globally unique
Schema MetadataEnabled by default
Table-Level LineageOptionally enabled via configuration

Prerequisites

To understand how BigQuery ingestion needs to be set up, first familiarize yourself with the concepts in the diagram below:

There are two important concepts to understand and identify:

  • Extractor Project: This is the project associated with a service-account, whose credentials you will be configuring in the connector. The connector uses this service-account to run jobs (including queries) within the project.
  • Bigquery Projects are the projects from which table metadata, lineage, usage, and profiling data need to be collected. By default, the extractor project is included in the list of projects that DataHub collects metadata from, but you can control that by passing in a specific list of project ids that you want to collect metadata from. Read the configuration section below to understand how to limit the list of projects that DataHub extracts metadata from.

Create a datahub profile in GCP

  1. Create a custom role for datahub as per BigQuery docs.
  2. Follow the sections below to grant permissions to this role on this project and other projects.
Basic Requirements (needed for metadata ingestion)
  1. Identify your Extractor Project where the service account will run queries to extract metadata.
permission                      Description                                                                                                                        Capability                                                              
bigquery.jobs.create          Run jobs (e.g. queries) within the project. This only needs for the extractor project where the service account belongs                                                                                                                       
bigquery.jobs.list            Manage the queries that the service account has sent. This only needs for the extractor project where the service account belongs                                                                                                             
bigquery.readsessions.create  Create a session for streaming large results. This only needs for the extractor project where the service account belongs                                                                                                                     
bigquery.readsessions.getDataGet data from the read session. This only needs for the extractor project where the service account belongs                      
  1. Grant the following permissions to the Service Account on every project where you would like to extract metadata from
info

If you have multiple projects in your BigQuery setup, the role should be granted these permissions in each of the projects.

permission                      Description                                                                                                Capability              Default GCP role which contains this permission                                                                
bigquery.datasets.get        Retrieve metadata about a dataset.                                                                          Table Metadata Extraction          roles/bigquery.metadataViewer
bigquery.datasets.getIamPolicyRead a dataset's IAM permissions.                                                                          Table Metadata Extraction          roles/bigquery.metadataViewer
bigquery.tables.list          List BigQuery tables.                                                                                      Table Metadata Extraction          roles/bigquery.metadataViewer
bigquery.tables.get          Retrieve metadata for a table.                                                                              Table Metadata Extraction          roles/bigquery.metadataViewer
bigquery.routines.get          Get Routines. Needs to retrieve metadata for a table from system table.                                                                                      Table Metadata Extraction          roles/bigquery.metadataViewer
bigquery.routines.list          List Routines. Needs to retrieve metadata for a table from system table                                                                              Table Metadata Extraction          roles/bigquery.metadataViewer
resourcemanager.projects.get  Retrieve project names and metadata.                                                                        Table Metadata Extraction          roles/bigquery.metadataViewer
bigquery.jobs.listAll        List all jobs (queries) submitted by any user. Needs for Lineage extraction.                                Lineage Extraction/Usage extractionroles/bigquery.resourceViewer
logging.logEntries.list      Fetch log entries for lineage/usage data. Not required if use_exported_bigquery_audit_metadata is enabled.Lineage Extraction/Usage extractionroles/logging.privateLogViewer
logging.privateLogEntries.listFetch log entries for lineage/usage data. Not required if use_exported_bigquery_audit_metadata is enabled.Lineage Extraction/Usage extractionroles/logging.privateLogViewer
bigquery.tables.getData      Access table data to extract storage size, last updated at, data profiles etc.Profiling                                                                                                                                         

Create a service account in the Extractor Project

  1. Setup a ServiceAccount as per BigQuery docs and assign the previously created role to this service account.
  2. Download a service account JSON keyfile. Example credential file:
{
"type": "service_account",
"project_id": "project-id-1234567",
"private_key_id": "d0121d0000882411234e11166c6aaa23ed5d74e0",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIyourkey\n-----END PRIVATE KEY-----",
"client_email": "test@suppproject-id-1234567.iam.gserviceaccount.com",
"client_id": "113545814931671546333",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/test%suppproject-id-1234567.iam.gserviceaccount.com"
}
  1. To provide credentials to the source, you can either:

    Set an environment variable:

    $ export GOOGLE_APPLICATION_CREDENTIALS="/path/to/keyfile.json"

    or

    Set credential config in your source based on the credential json file. For example:

    credential:
    project_id: project-id-1234567
    private_key_id: "d0121d0000882411234e11166c6aaa23ed5d74e0"
    private_key: "-----BEGIN PRIVATE KEY-----\nMIIyourkey\n-----END PRIVATE KEY-----\n"
    client_email: "test@suppproject-id-1234567.iam.gserviceaccount.com"
    client_id: "123456678890"

Lineage Computation Details

When use_exported_bigquery_audit_metadata is set to true, lineage information will be computed using exported bigquery logs. On how to setup exported bigquery audit logs, refer to the following docs on BigQuery audit logs. Note that only protoPayloads with "type.googleapis.com/google.cloud.audit.BigQueryAuditMetadata" are supported by the current ingestion version. The bigquery_audit_metadata_datasets parameter will be used only if use_exported_bigquery_audit_metadat is set to true.

Note: the bigquery_audit_metadata_datasets parameter receives a list of datasets, in the format $PROJECT.$DATASET. This way queries from a multiple number of projects can be used to compute lineage information.

Note: Since bigquery source also supports dataset level lineage, the auth client will require additional permissions to be able to access the google audit logs. Refer the permissions section in bigquery-usage section below which also accesses the audit logs.

Profiling Details

For performance reasons, we only profile the latest partition for partitioned tables and the latest shard for sharded tables. You can set partition explicitly with partition.partition_datetime property if you want, though note that partition config will be applied to all partitioned tables.

Caveats

  • For materialized views, lineage is dependent on logs being retained. If your GCP logging is retained for 30 days (default) and 30 days have passed since the creation of the materialized view we won't be able to get lineage for them.

CLI based Ingestion

Install the Plugin

pip install 'acryl-datahub[bigquery]'

Starter Recipe

Check out the following recipe to get started with ingestion! See below for full configuration options.

For general pointers on writing and running a recipe, see our main recipe guide.

source:
type: bigquery
config:
# `schema_pattern` for BQ Datasets
schema_pattern:
allow:
- finance_bq_dataset
table_pattern:
deny:
# The exact name of the table is revenue_table_name
# The reason we have this `.*` at the beginning is because the current implmenetation of table_pattern is testing
# project_id.dataset_name.table_name
# We will improve this in the future
- .*revenue_table_name
include_table_lineage: true
include_usage_statistics: true
profiling:
enabled: true
profile_table_level_only: true

sink:
# sink configs

Config Details

Note that a . is used to denote nested fields in the YAML recipe.

View All Configuration Options
Field [Required]TypeDescriptionDefaultNotes
bigquery_audit_metadata_datasetsarray(string)None
bucket_durationEnumSize of the time window to aggregate usage stats.DAY
capture_dataset_label_as_tagbooleanCapture BigQuery dataset labels as DataHub tagNone
capture_table_label_as_tagbooleanCapture BigQuery table labels as DataHub tagNone
column_limitintegerMaximum number of columns to process in a table. This is a low level config property which should be touched with care. This restriction is needed because excessively wide tables can result in failure to ingest the schema.300
convert_urns_to_lowercasebooleanConvert urns to lowercase.None
debug_include_full_payloadsbooleanInclude full payload into events. It is only for debugging and internal use.None
enable_legacy_sharded_table_supportbooleanUse the legacy sharded table urn suffix added.True
end_timestring(date-time)Latest date of usage to consider. Default: Current time in UTCNone
extra_client_optionsobjectAdditional options to pass to google.cloud.logging_v2.client.Client.None
extract_lineage_from_catalogbooleanThis flag enables the data lineage extraction from Data Lineage API exposed by Google Data Catalog. NOTE: This extractor can't build views lineage. It's recommended to enable the view's DDL parsing. Read the docs to have more information about: https://cloud.google.com/data-catalog/docs/reference/data-lineage/restNone
include_external_urlbooleanWhether to populate BigQuery Console url to Datasets/TablesTrue
include_table_lineagebooleanOption to enable/disable lineage generation. Is enabled by default.True
include_table_location_lineagebooleanIf the source supports it, include table lineage to the underlying storage location.True
include_tablesbooleanWhether tables should be ingested.True
include_usage_statisticsbooleanGenerate usage statisticTrue
include_viewsbooleanWhether views should be ingested.True
incremental_lineagebooleanWhen enabled, emits lineage as incremental to existing lineage already in DataHub. When disabled, re-states lineage on each run.True
lineage_parse_view_ddlbooleanSql parse view ddl to get lineage.True
lineage_sql_parser_use_raw_namesbooleanThis parameter ignores the lowercase pattern stipulated in the SQLParser. NOTE: Ignored if lineage_use_sql_parser is False.None
lineage_use_sql_parserbooleanExperimental. Use sql parser to resolve view/table lineage. If there is a view being referenced then bigquery sends both the view as well as underlying tablein the references. There is no distinction between direct/base objects accessed. So doing sql parsing to ensure we only use direct objects accessed for lineage.None
log_page_sizeintegerThe number of log item will be queried per page for lineage collection1000
match_fully_qualified_namesbooleanWhether dataset_pattern is matched against fully qualified dataset name <project_id>.<dataset_name>.None
max_query_durationnumber(time-delta)Correction to pad start_time and end_time with. For handling the case where the read happens within our time range but the query completion event is delayed and happens after the configured end time.900.0
number_of_datasets_process_in_batch_if_profiling_enabledintegerNumber of partitioned table queried in batch when getting metadata. This is a low level config property which should be touched with care. This restriction is needed because we query partitions system view which throws error if we try to touch too many tables.80
optionsobjectAny options specified here will be passed to SQLAlchemy's create_engine as kwargs. See https://docs.sqlalchemy.org/en/14/core/engines.html#sqlalchemy.create_engine for details.None
platform_instancestringThe instance of the platform that all assets produced by this recipe belong toNone
project_idstring[deprecated] Use project_id_pattern or project_ids instead.None
project_idsarray(string)None
project_on_behalfstring[Advanced] The BigQuery project in which queries are executed. Will be passed when creating a job. If not passed, falls back to the project associated with the service account.None
rate_limitbooleanShould we rate limit requests made to API.None
requests_per_minintegerUsed to control number of API calls made per min. Only used when rate_limit is set to True.60
schemestringbigquery
sharded_table_patternstringThe regex pattern to match sharded tables and group as one table. This is a very low level config parameter, only change if you know what you are doing,((.+)[_$])?(\d{8})$
sql_parser_use_external_processbooleanWhen enabled, sql parser will run in isolated in a separate process. This can affect processing time but can protect from sql parser's mem leak.None
start_timestring(date-time)Earliest date of usage to consider. Default: Last full day in UTC (or hour, depending on bucket_duration)None
store_last_lineage_extraction_timestampbooleanEnable checking last lineage extraction date in store.None
store_last_profiling_timestampsbooleanEnable storing last profile timestamp in store.None
store_last_usage_extraction_timestampbooleanEnable checking last usage timestamp in store.True
temp_table_dataset_prefixstringIf you are creating temp tables in a dataset with a particular prefix you can use this config to set the prefix for the dataset. This is to support workflows from before bigquery's introduction of temp tables. By default we use _ because of datasets that begin with an underscore are hidden by default https://cloud.google.com/bigquery/docs/datasets#dataset-naming._
upstream_lineage_in_reportbooleanUseful for debugging lineage information. Set to True to see the raw lineage created internally.None
use_date_sharded_audit_log_tablesbooleanWhether to read date sharded tables or time partitioned tables when extracting usage from exported audit logs.None
use_exported_bigquery_audit_metadatabooleanWhen configured, use BigQueryAuditMetadata in bigquery_audit_metadata_datasets to compute lineage information.None
envstringThe environment that all assets produced by this connector belong toPROD
credentialBigQueryCredentialBigQuery credential informationsNone
credential.client_email [❓ (required if credential is set)]stringClient emailNone
credential.client_id [❓ (required if credential is set)]stringClient IdNone
credential.private_key [❓ (required if credential is set)]stringPrivate key in a form of '-----BEGIN PRIVATE KEY-----\nprivate-key\n-----END PRIVATE KEY-----\n'None
credential.private_key_id [❓ (required if credential is set)]stringPrivate key idNone
credential.project_id [❓ (required if credential is set)]stringProject id to set the credentialsNone
credential.auth_provider_x509_cert_urlstringAuth provider x509 certificate urlhttps://www.googleapis.com/oauth2/v1/certs
credential.auth_uristringAuthentication urihttps://accounts.google.com/o/oauth2/auth
credential.client_x509_cert_urlstringIf not set it will be default to https://www.googleapis.com/robot/v1/metadata/x509/client_emailNone
credential.token_uristringToken urihttps://oauth2.googleapis.com/token
credential.typestringAuthentication typeservice_account
dataset_patternAllowDenyPatternRegex patterns for dataset to filter in ingestion. Specify regex to only match the schema name. e.g. to match all tables in schema analytics, use the regex 'analytics'{'allow': ['.*'], 'deny': [], 'ignoreCase': True}
dataset_pattern.allowarray(string)None
dataset_pattern.denyarray(string)None
dataset_pattern.ignoreCasebooleanWhether to ignore case sensitivity during pattern matching.True
domainmap(str,AllowDenyPattern)A class to store allow deny regexesNone
domain.key.allowarray(string)None
domain.key.denyarray(string)None
domain.key.ignoreCasebooleanWhether to ignore case sensitivity during pattern matching.True
profile_patternAllowDenyPatternRegex patterns to filter tables (or specific columns) for profiling during ingestion. Note that only tables allowed by the table_pattern will be considered.{'allow': ['.*'], 'deny': [], 'ignoreCase': True}
profile_pattern.allowarray(string)None
profile_pattern.denyarray(string)None
profile_pattern.ignoreCasebooleanWhether to ignore case sensitivity during pattern matching.True
project_id_patternAllowDenyPatternRegex patterns for project_id to filter in ingestion.{'allow': ['.*'], 'deny': [], 'ignoreCase': True}
project_id_pattern.allowarray(string)None
project_id_pattern.denyarray(string)None
project_id_pattern.ignoreCasebooleanWhether to ignore case sensitivity during pattern matching.True
schema_patternAllowDenyPatternRegex patterns for schemas to filter in ingestion. Specify regex to only match the schema name. e.g. to match all tables in schema analytics, use the regex 'analytics'{'allow': ['.*'], 'deny': [], 'ignoreCase': True}
schema_pattern.allowarray(string)None
schema_pattern.denyarray(string)None
schema_pattern.ignoreCasebooleanWhether to ignore case sensitivity during pattern matching.True
table_patternAllowDenyPatternRegex patterns for tables to filter in ingestion. Specify regex to match the entire table name in database.schema.table format. e.g. to match all tables starting with customer in Customer database and public schema, use the regex 'Customer.public.customer.*'{'allow': ['.*'], 'deny': [], 'ignoreCase': True}
table_pattern.allowarray(string)None
table_pattern.denyarray(string)None
table_pattern.ignoreCasebooleanWhether to ignore case sensitivity during pattern matching.True
usageBigQueryUsageConfigUsage related configs{'bucket_duration': 'DAY', 'end_time': '2023-03-23T20:03:43.150964+00:00', 'start_time': '2023-03-22T00:00:00+00:00', 'top_n_queries': 10, 'user_email_pattern': {'allow': ['.*'], 'deny': [], 'ignoreCase': True}, 'include_operational_stats': True, 'include_read_operational_stats': False, 'format_sql_queries': False, 'include_top_n_queries': True, 'query_log_delay': None, 'max_query_duration': 900.0}
usage.bucket_durationEnumSize of the time window to aggregate usage stats.DAY
usage.end_timestring(date-time)Latest date of usage to consider. Default: Current time in UTCNone
usage.format_sql_queriesbooleanWhether to format sql queriesNone
usage.include_operational_statsbooleanWhether to display operational stats.True
usage.include_read_operational_statsbooleanWhether to report read operational stats. Experimental.None
usage.include_top_n_queriesbooleanWhether to ingest the top_n_queries.True
usage.max_query_durationnumber(time-delta)Correction to pad start_time and end_time with. For handling the case where the read happens within our time range but the query completion event is delayed and happens after the configured end time.900.0
usage.query_log_delayintegerTo account for the possibility that the query event arrives after the read event in the audit logs, we wait for at least query_log_delay additional events to be processed before attempting to resolve BigQuery job information from the logs. If query_log_delay is None, it gets treated as an unlimited delay, which prioritizes correctness at the expense of memory usage.None
usage.start_timestring(date-time)Earliest date of usage to consider. Default: Last full day in UTC (or hour, depending on bucket_duration)None
usage.top_n_queriesintegerNumber of top queries to save to each table.10
usage.user_email_patternAllowDenyPatternregex patterns for user emails to filter in usage.{'allow': ['.*'], 'deny': [], 'ignoreCase': True}
usage.user_email_pattern.allowarray(string)None
usage.user_email_pattern.denyarray(string)None
usage.user_email_pattern.ignoreCasebooleanWhether to ignore case sensitivity during pattern matching.True
view_patternAllowDenyPatternRegex patterns for views to filter in ingestion. Note: Defaults to table_pattern if not specified. Specify regex to match the entire view name in database.schema.view format. e.g. to match all views starting with customer in Customer database and public schema, use the regex 'Customer.public.customer.*'{'allow': ['.*'], 'deny': [], 'ignoreCase': True}
view_pattern.allowarray(string)None
view_pattern.denyarray(string)None
view_pattern.ignoreCasebooleanWhether to ignore case sensitivity during pattern matching.True
profilingGEProfilingConfig{'enabled': False, 'limit': None, 'offset': None, 'report_dropped_profiles': False, 'turn_off_expensive_profiling_metrics': False, 'profile_table_level_only': False, 'include_field_null_count': True, 'include_field_distinct_count': True, 'include_field_min_value': True, 'include_field_max_value': True, 'include_field_mean_value': True, 'include_field_median_value': True, 'include_field_stddev_value': True, 'include_field_quantiles': False, 'include_field_distinct_value_frequencies': False, 'include_field_histogram': False, 'include_field_sample_values': True, 'field_sample_values_limit': 20, 'max_number_of_fields_to_profile': None, 'profile_if_updated_since_days': None, 'profile_table_size_limit': 5, 'profile_table_row_limit': 5000000, 'profile_table_row_count_estimate_only': False, 'max_workers': 20, 'query_combiner_enabled': True, 'catch_exceptions': True, 'partition_profiling_enabled': True, 'partition_datetime': None}
profiling.catch_exceptionsbooleanTrue
profiling.enabledbooleanWhether profiling should be done.None
profiling.field_sample_values_limitintegerUpper limit for number of sample values to collect for all columns.20
profiling.include_field_distinct_countbooleanWhether to profile for the number of distinct values for each column.True
profiling.include_field_distinct_value_frequenciesbooleanWhether to profile for distinct value frequencies.None
profiling.include_field_histogrambooleanWhether to profile for the histogram for numeric fields.None
profiling.include_field_max_valuebooleanWhether to profile for the max value of numeric columns.True
profiling.include_field_mean_valuebooleanWhether to profile for the mean value of numeric columns.True
profiling.include_field_median_valuebooleanWhether to profile for the median value of numeric columns.True
profiling.include_field_min_valuebooleanWhether to profile for the min value of numeric columns.True
profiling.include_field_null_countbooleanWhether to profile for the number of nulls for each column.True
profiling.include_field_quantilesbooleanWhether to profile for the quantiles of numeric columns.None
profiling.include_field_sample_valuesbooleanWhether to profile for the sample values for all columns.True
profiling.include_field_stddev_valuebooleanWhether to profile for the standard deviation of numeric columns.True
profiling.limitintegerMax number of documents to profile. By default, profiles all documents.None
profiling.max_number_of_fields_to_profileintegerA positive integer that specifies the maximum number of columns to profile for any table. None implies all columns. The cost of profiling goes up significantly as the number of columns to profile goes up.None
profiling.max_workersintegerNumber of worker threads to use for profiling. Set to 1 to disable.20
profiling.offsetintegerOffset in documents to profile. By default, uses no offset.None
profiling.partition_datetimestring(date-time)For partitioned datasets profile only the partition which matches the datetime or profile the latest one if not set. Only Bigquery supports this.None
profiling.partition_profiling_enabledbooleanTrue
profiling.profile_if_updated_since_daysnumberProfile table only if it has been updated since these many number of days. If set to null, no constraint of last modified time for tables to profile. Supported only in snowflake and BigQuery.None
profiling.profile_table_level_onlybooleanWhether to perform profiling at table-level only, or include column-level profiling as well.None
profiling.profile_table_row_count_estimate_onlybooleanUse an approximate query for row count. This will be much faster but slightly less accurate. Only supported for Postgres.None
profiling.profile_table_row_limitintegerProfile tables only if their row count is less then specified count. If set to null, no limit on the row count of tables to profile. Supported only in snowflake and BigQuery5000000
profiling.profile_table_size_limitintegerProfile tables only if their size is less then specified GBs. If set to null, no limit on the size of tables to profile. Supported only in snowflake and BigQuery5
profiling.query_combiner_enabledbooleanThis feature is still experimental and can be disabled if it causes issues. Reduces the total number of queries issued and speeds up profiling by dynamically combining SQL queries where possible.True
profiling.report_dropped_profilesbooleanWhether to report datasets or dataset columns which were not profiled. Set to True for debugging purposes.None
profiling.turn_off_expensive_profiling_metricsbooleanWhether to turn off expensive profiling or not. This turns off profiling for quantiles, distinct_value_frequencies, histogram & sample_values. This also limits maximum number of fields being profiled to 10.None
stateful_ingestionStatefulStaleMetadataRemovalConfigBase specialized config for Stateful Ingestion with stale metadata removal capability.None
stateful_ingestion.enabledbooleanThe type of the ingestion state provider registered with datahub.None
stateful_ingestion.ignore_new_statebooleanIf set to True, ignores the current checkpoint state.None
stateful_ingestion.ignore_old_statebooleanIf set to True, ignores the previous checkpoint state.None
stateful_ingestion.remove_stale_metadatabooleanSoft-deletes the entities present in the last successful run but missing in the current run with stateful_ingestion enabled.True

Code Coordinates

  • Class Name: datahub.ingestion.source.bigquery_v2.bigquery.BigqueryV2Source
  • Browse on GitHub

Questions

If you've got any questions on configuring ingestion for BigQuery, feel free to ping us on our Slack