使用 Data Catalog 标记 BigQuery 表

本快速入门可帮助您完成以下任务:

  1. 创建 BigQuery 数据集和表。

  2. 创建标记模板,其架构定义了五个不同类型的标记字段。分别是 stringdoublebooleanenumeratedrichtext

  3. 查找表的 Data Catalog 条目。

  4. 在 Google Cloud 控制台中,为您的条目创建业务元数据,其中包含概览、数据管理员和标记。

借助 Data Catalog,您可以搜索和标记条目,例如 包含元数据的 BigQuery 表。可用于标记的一些元数据示例包括公开和不公开标记、数据管家和富文本概览。

准备工作

  1. 设置项目。
    1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
    2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

      Go to project selector

    3. 启用 Data Catalog and BigQuery API。

      启用 API

    4. Install the Google Cloud CLI.
    5. To initialize the gcloud CLI, run the following command:

      gcloud init
    6. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

      Go to project selector

    7. 启用 Data Catalog and BigQuery API。

      启用 API

    8. Install the Google Cloud CLI.
    9. To initialize the gcloud CLI, run the following command:

      gcloud init

向项目添加公共数据条目

Data Catalog 条目包括数据资源,例如 BigQuery 数据集或 Pub/Sub 主题。

  • 向项目添加公共数据集。

    1. 在 Google Cloud 控制台中,前往 BigQuery 页面。

      转到 BigQuery

    2. 探索器部分,点击 + 添加数据,然后选择公开 数据集

    3. 市场面板中,搜索 New York taxi trips,然后点击相关搜索结果。

    4. 点击查看数据集

创建数据集和表

  1. 创建数据集。

    1. 在 Google Cloud 控制台中,打开 BigQuery 页面。

      转到 BigQuery

    2. 探索器面板中,选择您要在其中创建数据集的项目。

    3. 点击 操作图标,然后点击创建数据集

    4. 创建数据集页面中,填写以下详细信息:

      • 数据集 ID 部分,输入 demo_dataset
      • 数据位置中选择 us (multiple regions in United States)
      • 启用表过期时间并指定天数。
      • 加密部分,让 Google 管理的加密密钥选项保持选中状态。
      • 点击创建数据集

  2. 将可公开访问的表复制到 demo_dataset

    1. 在 Google Cloud 控制台中,打开 BigQuery 页面。

      转到 BigQuery

    2. 探索器窗格中,搜索 tlc_yellow_trips 个表 (如果需要,请点击将搜索范围扩大到所有项目)和 请选择其中一项,例如 tlc_yellow_trips_2017。然后点击复制

    3. 复制表格窗格中,填写以下信息:

      1. 项目名称下拉列表中,选择您的项目。
      2. 数据集名称下拉列表中,选择 demo_dataset
      3. 对于表名称,输入 trips,然后点击复制
    4. 浏览器窗格中,确认 trips 表列在 demo_dataset 中。

在下一部分中,您会将 Data Catalog 标记添加到该表。

创建公开标记模板并为您的条目附加标记

您必须是数据集所有者才能将标记附加到数据集中的表。 如需详细了解公开和不公开标记,请参阅公开和不公开标记

在标记模板中,标记字段是可选的。将标记附加到 Data Catalog 条目时,您无需为字段提供值。但是,如果模板将字段定义为必需,则必须为字段提供值。如果未提供值,则会生成错误。

您可以使用小写字母和下划线来定义字段名称。本示例中创建的标记模板字段只是演示字段,不会自动更新也不会与 BigQuery 同步。

控制台

  1. 转到 Dataplex >代码模板页面。

    前往 Dataplex 标记模板

  2. 点击创建标记模板,然后输入以下详细信息:

    1. 输入模板名称作为 Demo Tag Template
    2. 保留默认位置。
    3. 将标记模板的可见性保留为公开
    4. 点击添加字段以添加 5 个字段。使用下表并将字段说明留空。

      字段显示名 字段 ID 必填字段 类型
      数据资产的来源 source 字符串
      资源中的行 num_rows 双精度型
      含有 PII has_pii 布尔值
      PII 类型 pii_type 枚举

      添加值 EMAIL_ADDRESSUS_SOCIAL_SECURITY_NUMBERNONE

      上下文 context RTF
  3. 点击创建

    模板详细信息页面列出了有关标记模板的所有信息。

  4. 如需将标记附加到 demo_dataset,请前往 Dataplex 搜索页面。

    进入 Dataplex

  5. 选择搜索平台部分,选择 Data Catalog 作为搜索模式。

  6. 在搜索框中,输入 demo_dataset。在搜索结果中,您可以看到 demo_dataset 数据集和 trips 表。

  7. 点击 trips 表。 此时会打开 BigQuery 表详情页面。

  8. 点击附加标记

  9. 附加标记面板中,输入以下详细信息:

    1. 选择目标作为 trips
    2. 选择标记模板作为 Demo Tag Template
    3. 对于标记值,输入以下详细信息:
      • 数据资产的来源:Copied from tlc_yellow_trips_2017
      • 数据资产中的行数:113496874
      • 含有 PII:FALSE
      • PII 类型:NONE
    4. 点击保存

      标记字段现在会列在 BigQuery 表详细信息的标记部分中。

gcloud

运行以下显示的 gcloud data-catalog tag-templates create 命令创建标记模板,其中包含下列五个标记字段:

  1. display_name: Source of data asset
    id: source
    required: TRUE
    type: String
  2. display_name: Number of rows in the data asset
    id: num_rows
    required: FALSE
    type: Double
  3. display_name: Has PII
    id: has_pii
    required: FALSE
    type: Boolean
  4. display_name: PII type
    id: pii_type
    required: FALSE
    type: Enumerated
    values:
    1. EMAIL_ADDRESS
    2. US_SOCIAL_SECURITY_NUMBER
# -------------------------------
# Create a Tag Template.
# -------------------------------
gcloud data-catalog tag-templates create demo_template \
    --location=us-central1 \
    --display-name="Demo Tag Template" \
    --field=id=source,display-name="Source of data asset",type=string,required=TRUE \
    --field=id=num_rows,display-name="Number of rows in the data asset",type=double \
    --field=id=has_pii,display-name="Has PII",type=bool \
    --field=id=pii_type,display-name="PII type",type='enum(EMAIL_ADDRESS|US_SOCIAL_SECURITY_NUMBER|NONE)'

# -------------------------------
# Lookup the Data Catalog entry for the table.
# -------------------------------
ENTRY_NAME=$(gcloud data-catalog entries lookup '//bigquery.googleapis.com/projects/PROJECT_ID/datasets/DATASET/tables/TABLE' --format="value(name)")

# -------------------------------
# Attach a Tag to the table.
# -------------------------------

# Create the Tag file.
cat > tag_file.json << EOF
  {
    "source": "BigQuery",
    "num_rows": 1000,
    "has_pii": true,
    "pii_type": "EMAIL_ADDRESS"
  }
EOF

gcloud data-catalog tags create --entry=${ENTRY_NAME} \
    --tag-template=demo_template --tag-template-location=us-central1 --tag-file=tag_file.json

Go

在尝试此示例之前,请按照Go Data Catalog 快速入门:使用 客户端库。 有关详情,请参阅 Data Catalog Go API 参考文档

如需向 Data Catalog 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


// The datacatalog_quickstart application demonstrates how to define a tag
// template, populate values in the template, and attach a tag based on the
// template to a BigQuery table.
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"strings"
	"time"

	datacatalog "cloud.google.com/go/datacatalog/apiv1"
	"cloud.google.com/go/datacatalog/apiv1/datacatalogpb"
)

func main() {
	projectID := flag.String("project_id", "", "Cloud Project ID, used for session creation.")
	location := flag.String("location", "us-central1", "data catalog region to use for the quickstart")
	table := flag.String("table", "myproject.mydataset.mytable", "bigquery table to tag in project.dataset.table format")

	flag.Parse()

	ctx := context.Background()
	client, err := datacatalog.NewClient(ctx)
	if err != nil {
		log.Fatalf("datacatalog.NewClient: %v", err)
	}
	defer client.Close()

	// Create the tag template.
	tmpl, err := createQuickstartTagTemplate(ctx, client, *projectID, *location)
	if err != nil {
		log.Fatalf("createQuickstartTagTemplate: %v", err)
	}
	fmt.Printf("Created tag template: %s\n", tmpl.GetName())

	// Convert a BigQuery resource identifier into the equivalent datacatalog
	// format.
	resource, err := convertBigQueryResourceRepresentation(*table)
	if err != nil {
		log.Fatalf("couldn't parse --table flag (%s): %v", *table, err)
	}

	// Lookup the entry metadata for the BQ table resource.
	entry, err := client.LookupEntry(ctx, &datacatalogpb.LookupEntryRequest{
		TargetName: &datacatalogpb.LookupEntryRequest_LinkedResource{
			LinkedResource: resource,
		},
	})
	if err != nil {
		log.Fatalf("client.LookupEntry: %v", err)
	}
	fmt.Printf("Successfully looked up table entry: %s\n", entry.GetName())

	// Create a tag based on the template, and apply it to the entry.
	tag, err := createQuickstartTag(ctx, client, "my-quickstart-tag", tmpl.GetName(), entry.GetName())
	if err != nil {
		log.Fatalf("couldn't create tag: %v", err)
	}
	fmt.Printf("Created tag: %s", tag.GetName())
}

// createQuickstartTagTemplate registers a tag template in datacatalog.
func createQuickstartTagTemplate(ctx context.Context, client *datacatalog.Client, projectID, location string) (*datacatalogpb.TagTemplate, error) {
	loc := fmt.Sprintf("projects/%s/locations/%s", projectID, location)

	// Define the tag template.
	template := &datacatalogpb.TagTemplate{
		DisplayName: "Quickstart Tag Template",
		Fields: map[string]*datacatalogpb.TagTemplateField{
			"source": {
				DisplayName: "Source of data asset",
				Type: &datacatalogpb.FieldType{
					TypeDecl: &datacatalogpb.FieldType_PrimitiveType_{
						PrimitiveType: datacatalogpb.FieldType_STRING,
					},
				},
			},
			"num_rows": {
				DisplayName: "Number of rows in data asset",
				Type: &datacatalogpb.FieldType{
					TypeDecl: &datacatalogpb.FieldType_PrimitiveType_{
						PrimitiveType: datacatalogpb.FieldType_DOUBLE,
					},
				},
			},
			"has_pii": {
				DisplayName: "Has PII",
				Type: &datacatalogpb.FieldType{
					TypeDecl: &datacatalogpb.FieldType_PrimitiveType_{
						PrimitiveType: datacatalogpb.FieldType_BOOL,
					},
				},
			},
			"pii_type": {
				DisplayName: "PII Type",
				Type: &datacatalogpb.FieldType{
					TypeDecl: &datacatalogpb.FieldType_EnumType_{
						EnumType: &datacatalogpb.FieldType_EnumType{
							AllowedValues: []*datacatalogpb.FieldType_EnumType_EnumValue{
								{DisplayName: "EMAIL"},
								{DisplayName: "SOCIAL SECURITY NUMBER"},
								{DisplayName: "NONE"},
							},
						},
					},
				},
			},
		},
	}

	//Construct the creation request using the template definition.
	req := &datacatalogpb.CreateTagTemplateRequest{
		Parent:        loc,
		TagTemplateId: "quickstart_tag_template",
		TagTemplate:   template,
	}

	return client.CreateTagTemplate(ctx, req)

}

// createQuickstartTag populates tag values according to the template, and attaches
// the tag to the designeated entry.
func createQuickstartTag(ctx context.Context, client *datacatalog.Client, tagID, templateName, entryName string) (*datacatalogpb.Tag, error) {
	tag := &datacatalogpb.Tag{
		Name:     fmt.Sprintf("%s/tags/%s", entryName, tagID),
		Template: templateName,
		Fields: map[string]*datacatalogpb.TagField{
			"source": {
				Kind: &datacatalogpb.TagField_StringValue{StringValue: "Copied from tlc_yellow_trips_2018"},
			},
			"num_rows": {
				Kind: &datacatalogpb.TagField_DoubleValue{DoubleValue: 113496874},
			},
			"has_pii": {
				Kind: &datacatalogpb.TagField_BoolValue{BoolValue: false},
			},
			"pii_type": {
				Kind: &datacatalogpb.TagField_EnumValue_{
					EnumValue: &datacatalogpb.TagField_EnumValue{
						DisplayName: "NONE",
					},
				},
			},
		},
	}

	req := &datacatalogpb.CreateTagRequest{
		Parent: entryName,
		Tag:    tag,
	}
	return client.CreateTag(ctx, req)
}

// convertBigQueryResourceRepresentation converts a table identifier in standard sql form
// (project.datadata.table) into the representation used within data catalog.
func convertBigQueryResourceRepresentation(table string) (string, error) {
	parts := strings.Split(table, ".")
	if len(parts) != 3 {
		return "", fmt.Errorf("specified table string is not in expected project.dataset.table format: %s", table)
	}
	return fmt.Sprintf("//bigquery.googleapis.com/projects/%s/datasets/%s/tables/%s", parts[0], parts[1], parts[2]), nil
}

Java

在尝试此示例之前,请按照Java Data Catalog 快速入门:使用 客户端库。 有关详情,请参阅 Data Catalog Java API 参考文档

如需向 Data Catalog 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.datacatalog.v1.CreateTagRequest;
import com.google.cloud.datacatalog.v1.CreateTagTemplateRequest;
import com.google.cloud.datacatalog.v1.DataCatalogClient;
import com.google.cloud.datacatalog.v1.Entry;
import com.google.cloud.datacatalog.v1.FieldType;
import com.google.cloud.datacatalog.v1.FieldType.EnumType;
import com.google.cloud.datacatalog.v1.FieldType.EnumType.EnumValue;
import com.google.cloud.datacatalog.v1.FieldType.PrimitiveType;
import com.google.cloud.datacatalog.v1.LocationName;
import com.google.cloud.datacatalog.v1.LookupEntryRequest;
import com.google.cloud.datacatalog.v1.Tag;
import com.google.cloud.datacatalog.v1.TagField;
import com.google.cloud.datacatalog.v1.TagTemplate;
import com.google.cloud.datacatalog.v1.TagTemplateField;
import java.io.IOException;

public class Quickstart {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String tagTemplateId = "my_tag_template";
    createTags(projectId, tagTemplateId);
  }

  public static void createTags(String projectId, String tagTemplateId) throws IOException {
    // Currently, Data Catalog stores metadata in the us-central1 region.
    String location = "us-central1";

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DataCatalogClient dataCatalogClient = DataCatalogClient.create()) {

      // -------------------------------
      // Create a Tag Template.
      // -------------------------------
      TagTemplateField sourceField =
          TagTemplateField.newBuilder()
              .setDisplayName("Source of data asset")
              .setType(FieldType.newBuilder().setPrimitiveType(PrimitiveType.STRING).build())
              .build();

      TagTemplateField numRowsField =
          TagTemplateField.newBuilder()
              .setDisplayName("Number of rows in data asset")
              .setType(FieldType.newBuilder().setPrimitiveType(PrimitiveType.DOUBLE).build())
              .build();

      TagTemplateField hasPiiField =
          TagTemplateField.newBuilder()
              .setDisplayName("Has PII")
              .setType(FieldType.newBuilder().setPrimitiveType(PrimitiveType.BOOL).build())
              .build();

      TagTemplateField piiTypeField =
          TagTemplateField.newBuilder()
              .setDisplayName("PII type")
              .setType(
                  FieldType.newBuilder()
                      .setEnumType(
                          EnumType.newBuilder()
                              .addAllowedValues(
                                  EnumValue.newBuilder().setDisplayName("EMAIL").build())
                              .addAllowedValues(
                                  EnumValue.newBuilder()
                                      .setDisplayName("SOCIAL SECURITY NUMBER")
                                      .build())
                              .addAllowedValues(
                                  EnumValue.newBuilder().setDisplayName("NONE").build())
                              .build())
                      .build())
              .build();

      TagTemplate tagTemplate =
          TagTemplate.newBuilder()
              .setDisplayName("Demo Tag Template")
              .putFields("source", sourceField)
              .putFields("num_rows", numRowsField)
              .putFields("has_pii", hasPiiField)
              .putFields("pii_type", piiTypeField)
              .build();

      CreateTagTemplateRequest createTagTemplateRequest =
          CreateTagTemplateRequest.newBuilder()
              .setParent(
                  LocationName.newBuilder()
                      .setProject(projectId)
                      .setLocation(location)
                      .build()
                      .toString())
              .setTagTemplateId(tagTemplateId)
              .setTagTemplate(tagTemplate)
              .build();

      // Create the Tag Template.
      tagTemplate = dataCatalogClient.createTagTemplate(createTagTemplateRequest);

      // -------------------------------
      // Lookup Data Catalog's Entry referring to the table.
      // -------------------------------
      String linkedResource =
          String.format(
              "//bigquery.googleapis.com/projects/%s/datasets/test_dataset/tables/test_table",
              projectId);
      LookupEntryRequest lookupEntryRequest =
          LookupEntryRequest.newBuilder().setLinkedResource(linkedResource).build();
      Entry tableEntry = dataCatalogClient.lookupEntry(lookupEntryRequest);

      // -------------------------------
      // Attach a Tag to the table.
      // -------------------------------
      TagField sourceValue =
          TagField.newBuilder().setStringValue("Copied from tlc_yellow_trips_2017").build();
      TagField numRowsValue = TagField.newBuilder().setDoubleValue(113496874).build();
      TagField hasPiiValue = TagField.newBuilder().setBoolValue(false).build();
      TagField piiTypeValue =
          TagField.newBuilder()
              .setEnumValue(TagField.EnumValue.newBuilder().setDisplayName("NONE").build())
              .build();

      Tag tag =
          Tag.newBuilder()
              .setTemplate(tagTemplate.getName())
              .putFields("source", sourceValue)
              .putFields("num_rows", numRowsValue)
              .putFields("has_pii", hasPiiValue)
              .putFields("pii_type", piiTypeValue)
              .build();

      CreateTagRequest createTagRequest =
          CreateTagRequest.newBuilder().setParent(tableEntry.getName()).setTag(tag).build();

      dataCatalogClient.createTag(createTagRequest);
      System.out.printf("Tag created successfully");
    }
  }
}

Node.js

在尝试此示例之前,请按照Node.js Data Catalog 快速入门:使用 客户端库。 有关详情,请参阅 Data Catalog Node.js API 参考文档

如需向 Data Catalog 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// Import the Google Cloud client library and create a client.
const {DataCatalogClient} = require('@google-cloud/datacatalog').v1;
const datacatalog = new DataCatalogClient();

async function quickstart() {
  // Common fields.
  let request;
  let responses;

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'my_project'; // Google Cloud Platform project
  // const datasetId = 'demo_dataset';
  // const tableId = 'trips';

  // Currently, Data Catalog stores metadata in the
  // us-central1 region.
  const location = 'us-central1';

  // Create Fields.
  const fieldSource = {
    displayName: 'Source of data asset',
    type: {
      primitiveType: 'STRING',
    },
  };

  const fieldNumRows = {
    displayName: 'Number of rows in data asset',
    type: {
      primitiveType: 'DOUBLE',
    },
  };

  const fieldHasPII = {
    displayName: 'Has PII',
    type: {
      primitiveType: 'BOOL',
    },
  };

  const fieldPIIType = {
    displayName: 'PII type',
    type: {
      enumType: {
        allowedValues: [
          {
            displayName: 'EMAIL',
          },
          {
            displayName: 'SOCIAL SECURITY NUMBER',
          },
          {
            displayName: 'NONE',
          },
        ],
      },
    },
  };

  // Create Tag Template.
  const tagTemplateId = 'demo_tag_template';

  const tagTemplate = {
    displayName: 'Demo Tag Template',
    fields: {
      source: fieldSource,
      num_rows: fieldNumRows,
      has_pii: fieldHasPII,
      pii_type: fieldPIIType,
    },
  };

  const tagTemplatePath = datacatalog.tagTemplatePath(
    projectId,
    location,
    tagTemplateId
  );

  // Delete any pre-existing Template with the same name.
  try {
    request = {
      name: tagTemplatePath,
      force: true,
    };
    await datacatalog.deleteTagTemplate(request);
    console.log(`Deleted template: ${tagTemplatePath}`);
  } catch (error) {
    console.log(`Cannot delete template: ${tagTemplatePath}`);
  }

  // Create the Tag Template request.
  const locationPath = datacatalog.locationPath(projectId, location);

  request = {
    parent: locationPath,
    tagTemplateId: tagTemplateId,
    tagTemplate: tagTemplate,
  };

  // Execute the request.
  responses = await datacatalog.createTagTemplate(request);
  const createdTagTemplate = responses[0];
  console.log(`Created template: ${createdTagTemplate.name}`);

  // Lookup Data Catalog's Entry referring to the table.
  responses = await datacatalog.lookupEntry({
    linkedResource:
      '//bigquery.googleapis.com/projects/' +
      `${projectId}/datasets/${datasetId}/tables/${tableId}`,
  });
  const entry = responses[0];
  console.log(`Entry name: ${entry.name}`);
  console.log(`Entry type: ${entry.type}`);
  console.log(`Linked resource: ${entry.linkedResource}`);

  // Attach a Tag to the table.
  const tag = {
    name: entry.name,
    template: createdTagTemplate.name,
    fields: {
      source: {
        stringValue: 'copied from tlc_yellow_trips_2017',
      },
      num_rows: {
        doubleValue: 113496874,
      },
      has_pii: {
        boolValue: false,
      },
      pii_type: {
        enumValue: {
          displayName: 'NONE',
        },
      },
    },
  };

  request = {
    parent: entry.name,
    tag: tag,
  };

  // Create the Tag.
  await datacatalog.createTag(request);
  console.log(`Tag created for entry: ${entry.name}`);
}
quickstart();

Python

在尝试此示例之前,请按照Python Data Catalog 快速入门:使用 客户端库。 有关详情,请参阅 Data Catalog Python API 参考文档

如需向 Data Catalog 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

# Import required modules.
from google.cloud import datacatalog_v1

# TODO: Set these values before running the sample.
# Google Cloud Platform project.
project_id = "my_project"
# Set dataset_id to the ID of existing dataset.
dataset_id = "demo_dataset"
# Set table_id to the ID of existing table.
table_id = "trips"
# Tag template to create.
tag_template_id = "example_tag_template"

# For all regions available, see:
# https://cloud.google.com/data-catalog/docs/concepts/regions
location = "us-central1"

# Use Application Default Credentials to create a new
# Data Catalog client. GOOGLE_APPLICATION_CREDENTIALS
# environment variable must be set with the location
# of a service account key file.
datacatalog_client = datacatalog_v1.DataCatalogClient()

# Create a Tag Template.
tag_template = datacatalog_v1.types.TagTemplate()

tag_template.display_name = "Demo Tag Template"

tag_template.fields["source"] = datacatalog_v1.types.TagTemplateField()
tag_template.fields["source"].display_name = "Source of data asset"
tag_template.fields[
    "source"
].type_.primitive_type = datacatalog_v1.types.FieldType.PrimitiveType.STRING

tag_template.fields["num_rows"] = datacatalog_v1.types.TagTemplateField()
tag_template.fields["num_rows"].display_name = "Number of rows in data asset"
tag_template.fields[
    "num_rows"
].type_.primitive_type = datacatalog_v1.types.FieldType.PrimitiveType.DOUBLE

tag_template.fields["has_pii"] = datacatalog_v1.types.TagTemplateField()
tag_template.fields["has_pii"].display_name = "Has PII"
tag_template.fields[
    "has_pii"
].type_.primitive_type = datacatalog_v1.types.FieldType.PrimitiveType.BOOL

tag_template.fields["pii_type"] = datacatalog_v1.types.TagTemplateField()
tag_template.fields["pii_type"].display_name = "PII type"

for display_name in ["EMAIL", "SOCIAL SECURITY NUMBER", "NONE"]:
    enum_value = datacatalog_v1.types.FieldType.EnumType.EnumValue(
        display_name=display_name
    )
    tag_template.fields["pii_type"].type_.enum_type.allowed_values.append(
        enum_value
    )

expected_template_name = datacatalog_v1.DataCatalogClient.tag_template_path(
    project_id, location, tag_template_id
)

# Create the Tag Template.
try:
    tag_template = datacatalog_client.create_tag_template(
        parent=f"projects/{project_id}/locations/{location}",
        tag_template_id=tag_template_id,
        tag_template=tag_template,
    )
    print(f"Created template: {tag_template.name}")
except OSError as e:
    print(f"Cannot create template: {expected_template_name}")
    print(f"{e}")

# Lookup Data Catalog's Entry referring to the table.
resource_name = (
    f"//bigquery.googleapis.com/projects/{project_id}"
    f"/datasets/{dataset_id}/tables/{table_id}"
)
table_entry = datacatalog_client.lookup_entry(
    request={"linked_resource": resource_name}
)

# Attach a Tag to the table.
tag = datacatalog_v1.types.Tag()

tag.template = tag_template.name
tag.name = "my_super_cool_tag"

tag.fields["source"] = datacatalog_v1.types.TagField()
tag.fields["source"].string_value = "Copied from tlc_yellow_trips_2018"

tag.fields["num_rows"] = datacatalog_v1.types.TagField()
tag.fields["num_rows"].double_value = 113496874

tag.fields["has_pii"] = datacatalog_v1.types.TagField()
tag.fields["has_pii"].bool_value = False

tag.fields["pii_type"] = datacatalog_v1.types.TagField()
tag.fields["pii_type"].enum_value.display_name = "NONE"

tag = datacatalog_client.create_tag(parent=table_entry.name, tag=tag)
print(f"Created tag: {tag.name}")

REST 和命令行

REST

如果您无法使用针对您的语言的 Cloud 客户端库或者您想要使用 REST 请求来测试 API,请参阅以下示例并参阅 Data Catalog REST API 文档。

1.创建标记模板。

在使用任何请求数据之前,请先进行以下替换:

  • project-id:您的 Google Cloud 项目 ID

HTTP 方法和网址:

POST https://datacatalog.googleapis.com/v1/projects/project-id/locations/region/tagTemplates?tagTemplateId=demo_tag_template

请求 JSON 正文:


{
  "displayName":"Demo Tag Template",
  "fields":{
    "source":{
      "displayName":"Source of data asset",
      "isRequired": "true",
      "type":{
        "primitiveType":"STRING"
      }
    },
    "num_rows":{
      "displayName":"Number of rows in data asset",
      "isRequired": "false",
      "type":{
        "primitiveType":"DOUBLE"
      }
    },
    "has_pii":{
      "displayName":"Has PII",
      "isRequired": "false",
      "type":{
        "primitiveType":"BOOL"
      }
    },
    "pii_type":{
      "displayName":"PII type",
      "isRequired": "false",
      "type":{
        "enumType":{
          "allowedValues":[
            {
              "displayName":"EMAIL_ADDRESS"
            },
            {
              "displayName":"US_SOCIAL_SECURITY_NUMBER"
            },
            {
              "displayName":"NONE"
            }
          ]
        }
      }
    }
  }
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name":"projects/project-id/locations/us-central1/tagTemplates/demo_tag_template",
  "displayName":"Demo Tag Template",
  "fields":{
    "num_rows":{
      "displayName":"Number of rows in data asset",
      "isRequired": "false",
      "type":{
        "primitiveType":"DOUBLE"
      }
    },
    "has_pii":{
      "displayName":"Has PII",
      "isRequired": "false",
      "type":{
        "primitiveType":"BOOL"
      }
    },
    "pii_type":{
      "displayName":"PII type",
      "isRequired": "false",
      "type":{
        "enumType":{
          "allowedValues":[
            {
              "displayName":"EMAIL_ADDRESS"
            },
            {
              "displayName":"NONE"
            },
            {
              "displayName":"US_SOCIAL_SECURITY_NUMBER"
            }
          ]
        }
      }
    },
    "source":{
      "displayName":"Source of data asset",
      "isRequired":"true",
      "type":{
        "primitiveType":"STRING"
      }
    }
  }
}

2.查找 BigQuery 表的 Data Catalog entry-id

在使用任何请求数据之前,请先进行以下替换:

  • project-id:Google Cloud 项目 ID

HTTP 方法和网址:

GET https://datacatalog.googleapis.com/v1/entries:lookup?linkedResource=//bigquery.googleapis.com/projects/project-id/datasets/demo_dataset/tables/trips

请求 JSON 正文:

Request body is empty.

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/project-id/locations/US/entryGroups/@bigquery/entries/entry-id",
  "type": "TABLE",
  "schema": {
    "columns": [
      {
        "type": "STRING",
        "description": "A code indicating the TPEP provider that provided the record. 1= ",
        "mode": "REQUIRED",
        "column": "vendor_id"
      },
      ...
    ]
  },
  "sourceSystemTimestamps": {
    "createTime": "2019-01-25T01:45:29.959Z",
    "updateTime": "2019-03-19T23:20:26.540Z"
  },
  "linkedResource": "//bigquery.googleapis.com/projects/project-id/datasets/demo_dataset/tables/trips",
  "bigqueryTableSpec": {
    "tableSourceType": "BIGQUERY_TABLE"
  }
}

3.从模板创建标记并将其附加到 BigQuery 表。

在使用任何请求数据之前,请先进行以下替换:

  • project-id:Google Cloud 项目 ID
  • entry-id:演示数据集 trips 表的 Data Catalog 条目 ID(在上一步的查找结果中返回)。

HTTP 方法和网址:

POST https://datacatalog.googleapis.com/v1/projects/project-id/locations/region/entryGroups/@bigquery/entries/entry-id/tags

请求 JSON 正文:

{
  "template":"projects/project-id/locations/us-central1/tagTemplates/demo_tag_template",
  "fields":{
    "source":{
      "stringValue":"Copied from tlc_yellow_trips_2017"
    },
    "num_rows":{
      "doubleValue":113496874
    },
    "has_pii":{
      "boolValue":false
    },
    "pii_type":{
      "enumValue":{
        "displayName":"NONE"
      }
    }
  }
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name":"projects/project-id/locations/US/entryGroups/@bigquery/entries/entry-id/tags/tag-id",
  "template":"projects/project-id/locations/us-central1/tagTemplates/demo_tag_template",
  "fields":{
    "pii_type":{
      "displayName":"PII type",
      "enumValue":{
        "displayName":"NONE"
      }
    },
    "has_pii":{
      "displayName":"Has PII",
      "boolValue":false
    },
    "source":{
      "displayName":"Source of data asset",
      "stringValue":"Copied from tlc_yellow_trips_2017"
    },
    "num_rows":{
      "displayName":"Number of rows in data asset",
      "doubleValue":113496874
    }
  },
  "templateDisplayName":"Demo Tag Template"
}
注意:在 BigQuery 中重命名表 会删除与其及其列相关联的所有标记。

为您的条目创建概览

在 Google Cloud 控制台中,您可以使用富文本来描述 Data Catalog 项目中的条目。

  1. 如需创建 trips 表的概览,请前往 Dataplex 搜索页面。

    进入 Dataplex

  2. 选择搜索平台部分,选择 Data Catalog 作为搜索模式。

  3. 在搜索框中,输入 demo_dataset

    在搜索结果中,您可以看到 demo_dataset 数据集和 trips 表。

  4. 点击 trips 表。

    此时会打开 BigQuery 表详情页面。

  5. 点击添加概览并输入一些文本。您还可以添加图片和富格式的文本。

  6. 点击保存

为您的条目添加数据管理员

在 Google Cloud 控制台中,您可以向一个条目添加一个或多个数据管理员 在 Data Catalog 项目中创建。可以联系数据条目的数据管家,以请求有关数据条目的更多信息。

  1. 如需为 trips 表创建概览,请重复上一部分中的前 3 个步骤。

  2. 点击编辑管家图标,然后添加一个或多个电子邮件地址。

    您可以添加具有非 Google 电子邮件账号的用户。

  3. 点击保存

清理

为避免因本页中使用的资源导致您的 Google Cloud 账号产生费用,请按照以下步骤操作。

删除项目

为了避免产生费用,最简单的方法是删除您为本教程创建的项目。

要删除项目,请执行以下操作:

  1. 在 Google Cloud 控制台中,进入管理资源页面。

    转到“管理资源”

  2. 在项目列表中,选择要删除的项目,然后点击删除
  3. 在对话框中输入项目 ID,然后点击关闭以删除项目。

删除数据集

  1. 如有必要,请转到 BigQuery 页面。

    转到 BigQuery

  2. 浏览器面板中,搜索您创建的 demo_dataset 数据集。

  3. 点击 操作选项,然后点击删除数据集

  4. 确认删除操作。

删除标记模板

  1. 转到 Data Catalog > 模板页面。

    转到 Data Catalog 模板

  2. 选择演示标记模板

  3. 在行中,点击 操作选项,然后点击删除此模板

  4. 确认删除操作。

后续步骤