Data Catalog を使用して BigQuery テーブルにタグ付けする

このクイックスタートは、次のタスクの実施に役立ちます。

  1. BigQuery データセットとテーブルを作成する。

  2. 異なるタイプの 5 つのタグフィールドを定義するスキーマを使用してタグ テンプレートを作成します。stringdoublebooleanenumeratedrichtext です。

  3. テーブルのデータカタログ エントリを検索します。

  4. Google Cloud コンソールで、概要、データ スチュワード、タグを含むエントリのビジネス メタデータを作成します。

Data Catalog を使用すると、メタデータで BigQuery テーブルなどのエントリを検索してタグ付けできます。タグ付けに使用できるメタデータの例には、公開タグと非公開タグ、データ スチュワード、リッチテキストの概要などがあります。

始める前に

  1. プロジェクトの設定。
    1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
    2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

      プロジェクト セレクタに移動

    3. Data Catalog and BigQuery API を有効にします。

      API を有効にする

    4. Google Cloud CLI をインストールします。
    5. gcloud CLI を初期化するには:

      gcloud init
    6. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

      プロジェクト セレクタに移動

    7. Data Catalog and BigQuery API を有効にします。

      API を有効にする

    8. Google Cloud CLI をインストールします。
    9. gcloud CLI を初期化するには:

      gcloud init

一般公開データ エントリをプロジェクトに追加する

Data Catalog エントリには、BigQuery データセットや Pub/Sub トピックなどのデータリソースが含まれます。

  • 一般公開データセットをプロジェクトに追加します。

    1. Google Cloud コンソールで [BigQuery] ページに移動します。

      BigQuery に移動

    2. [エクスプローラ] セクションで、[+ データを追加] をクリックして、リストから [公開データセット] を選択します。

    3. [Marketplace] パネルで「New York taxi trips」を検索し、関連する検索結果をクリックします。

    4. [データセットを表示] をクリックします。

データセットとテーブルを作成する

  1. データセットを作成します。

    1. Google Cloud コンソールで [BigQuery] ページを開きます。

      [BigQuery] に移動

    2. [エクスプローラ] パネルで、データセットを作成するプロジェクトを選択します。

    3. アクション アイコンをクリックし、[データセットを作成] をクリックします。

    4. [データセットを作成] ページで、次の詳細を入力します。

      • [データセット ID] に「demo_dataset」を入力します。
      • [Data location] で [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 必須項目 タイプ
      データアセットのソース ソース 文字列
      アセットの行 num_rows × 倍精度
      Has PII has_pii × ブール値
      PII タイプ PII タイプ × 列挙

      EMAIL_ADDRESSUS_SOCIAL_SECURITY_NUMBERNONE の値を追加します。

      背景 背景 × リッチテキスト
  3. [作成] をクリックします。

    [テンプレートの詳細] ページには、タグ テンプレートに関するすべての情報が一覧表示されます。

  4. demo_dataset にタグを添付するには、Dataplex の検索ページに移動します。

    Dataplex に移動

  5. [検索] ボックスに「demo_dataset」と入力します。 検索結果には、demo_dataset データセットと trips テーブルが表示されます。

  6. [trips] テーブルをクリックします。 [BigQuery テーブルの詳細] ページが開きます。

  7. [タグを添付] をクリックします。

  8. [タグを添付] パネルに、次の情報を入力します。

    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 コマンドを実行して、次の 5 つのタグフィールドを持つタグ テンプレートを作成します。

  1. display_name: データアセットのソース
    id: ソース
    required: true
    type: string
  2. display_name: データアセットの行数
    id: num_rows
    required: false
    type: double
  3. display_name: PII あり
    id: has_pii
    required: false
    type: boolean
  4. display_name: PII タイプ
    id: pii_type
    required: false
    type: enum
    values:
    1. EMAIL_ADDRESS
    2. US_SOCIAL_SECURITY_NUMBER
    3. なし
# -------------------------------
# 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

このサンプルを試す前に、クライアント ライブラリを使用した Data Catalog のクイックスタートにある Go の設定手順を行ってください。詳細については、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

このサンプルを試す前に、クライアント ライブラリを使用した Data Catalog のクイックスタートにある Java の設定手順を行ってください。詳細については、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

このサンプルを試す前に、クライアント ライブラリを使用した Data Catalog のクイックスタートにある Node.js の設定手順を行ってください。詳細については、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

このサンプルを試す前に、クライアント ライブラリを使用した Data Catalog のクイックスタートにある Python の設定手順を行ってください。詳細については、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 メソッドと URL:

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 メソッドと URL:

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: デモ データセットのトリップ テーブルの Data Catalog エントリ ID(前のステップの検索結果で返されます)。

HTTP メソッドと URL:

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. [検索] ボックスに「demo_dataset」と入力します。

    検索結果には、demo_dataset データセットと trips テーブルが表示されます。

  3. [trips] テーブルをクリックします。

    [BigQuery テーブルの詳細] ページが開きます。

  4. [概要を追加] をクリックしてテキストを入力します。画像とリッチ形式のテキストを追加することもできます。

  5. [保存] をクリックします。

エントリにデータ スチュワードを追加する

Google Cloud コンソール内で、1 つ以上のデータ スチュワードを Data Catalog プロジェクトのエントリに追加できます。データエントリのデータ スチュワードに対して、データエントリに関する詳細情報を要求すことができます。

  1. trips テーブルの概要を作成するには、前のセクションの最初の 3 つのステップを繰り返します。

  2. スチュワードの編集アイコンをクリックして、1 つ以上のメールアドレスを追加します。

    Google 以外のメール アカウントを持つユーザーを追加できます。

  3. [保存] をクリックします。

クリーンアップ

このページで使用したリソースについて、Google Cloud アカウントに課金されないようにするには、次の手順を実施します。

プロジェクトを削除する

課金をなくす最も簡単な方法は、チュートリアル用に作成したプロジェクトを削除することです。

プロジェクトを削除するには:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

データセットの削除

  1. 必要に応じて、[BigQuery] ページに移動します。

    BigQuery に移動

  2. [エクスプローラ] パネルで、作成した demo_dataset データセットを検索します。

  3. [アクション] オプションをクリックし、[データセットを削除] をクリックします。

  4. 削除のアクションを確認します。

タグ テンプレートを削除する

  1. [Data Catalog] > [テンプレート] ページに移動します。

    Data Catalog の [テンプレート] に移動

  2. [デモ タグ テンプレート] を選択します。

  3. その行で、 [アクション] オプションをクリックし、[このテンプレートを削除] をクリックします。

  4. 削除のアクションを確認します。

次のステップ