如何在GCP中为BigQuery指定前缀列添加Data Catalog标签?
问题描述
在GCP BigQuery中,需为列名前缀匹配的列添加标签(例如给所有以ABC_开头的列添加Private Info标签),编写的Python代码运行时报错Resource Name Invalid,提示列不能作为资源,原代码如下:
dataset_id = 'my_dataset' for table in bigquery_client.list_tables(dataset_id): # Get the schema of the table table_ref = f'{project_id}.{dataset_id}.{table.table_id}' table = bigquery_client.get_table(table_ref) schema = table.schema table_id = table.table_id # Loop through the schema fields, and create tags for columns that match the criteria for field in schema: if field.name.startswith('RUR_'): tag = datacatalog.Tag() tag.template = f'projects/{project_id}/locations/us-central1/tagTemplates/{tag_template_id}' tag.fields['owner'].string_value = 'John Doe' tag = datacatalog_client.create_tag(parent=f'projects/{project_id}/locations/us-central1/entryGroups/{entry_group_id}/entries/{table_id}/fields/{field.name}', tag=tag) print(f'Tag created for column {field.name} in table {table_id}')
解决方案
错误根源是你错误地将列字段作为Tag的父资源。在GCP Data Catalog中,BigQuery的列字段不能直接作为Tag的父节点,正确的做法是通过表的Data Catalog Entry关联,并指定目标列的路径。
修正步骤
获取表对应的Data Catalog Entry
调用datacatalog_client.lookup_entry方法,传入BigQuery表的完整资源路径(格式://bigquery.googleapis.com/projects/{project_id}/datasets/{dataset_id}/tables/{table_id}),获取表的Entry对象。指定Tag的父资源与目标列
创建Tag时,父资源设为表Entry的名称,同时通过tag.column字段指定目标列的名称(顶层列直接填列名即可)。
修正后的代码
from google.cloud import bigquery, datacatalog_v1 # 初始化客户端 bigquery_client = bigquery.Client(project=project_id) datacatalog_client = datacatalog_v1.DataCatalogClient() dataset_id = 'my_dataset' tag_template_id = 'your_tag_template_id' # 替换为你的标签模板ID for table in bigquery_client.list_tables(dataset_id): table_ref = f'{project_id}.{dataset_id}.{table.table_id}' table = bigquery_client.get_table(table_ref) table_id = table.table_id # 1. 获取表对应的Data Catalog Entry linked_resource = f'//bigquery.googleapis.com/projects/{project_id}/datasets/{dataset_id}/tables/{table_id}' entry = datacatalog_client.lookup_entry(request={"linked_resource": linked_resource}) # 遍历schema字段,匹配前缀的列添加标签 for field in table.schema: if field.name.startswith('RUR_'): tag = datacatalog_v1.Tag() tag.template = f'projects/{project_id}/locations/us-central1/tagTemplates/{tag_template_id}' # 设置标签字段值(根据你的模板调整) tag.fields['owner'].string_value = 'John Doe' # 指定目标列 tag.column = field.name # 2. 创建标签,父资源为表的Entry名称 tag = datacatalog_client.create_tag(parent=entry.name, tag=tag) print(f'Tag created for column {field.name} in table {table_id}')
注意事项
- 确保你的标签模板(
tag_template_id)已经在指定区域创建,且包含owner字段(或根据你的需求调整字段名)。 - 运行代码的账号需要拥有
datacatalog.tags.create权限,以及BigQuery表的读取权限和Data Catalog Entry的访问权限。
内容的提问来源于stack exchange,提问作者Ananya Dwivedi
相关产品推荐
相关产品推荐

