파일 세트 항목을 사용하여 Cloud Storage에서 파일 표시

Data Catalog API를 사용하여 Cloud Storage 파일 세트 항목(이하 '파일 세트')을 만들고 검색할 수 있습니다.

파일 세트

Cloud Storage 파일 세트는 사용자가 만든 항목 그룹 내 항목입니다. 자세한 내용은 항목 및 항목 그룹을 참조하세요.

한 개 이상의 Cloud Storage 파일 집합을 지정하는 하나 이상의 파일 패턴으로 정의됩니다.

파일 패턴 요구사항:

  • 파일 패턴은 gs://bucket_name/로 시작해야 합니다.
  • 버킷 이름은 Cloud Storage 버킷 이름 요구사항을 따라야 합니다.
  • 파일 패턴의 폴더와 파일 일부에는 와일드 카드가 허용되지만 버킷 이름에는 와일드 카드가 허용되지 않습니다. 예를 들어 다음을 참조하세요.
  • 파일 세트는 파일 세트 패턴을 한 개 이상 가져야 하며 500개를 초과할 수 없습니다.

Dataflow SQL로 정의된 카탈로그가 있고 헤더 행이 없는 CSV 파일만 포함된 경우에만 Data Catalog 파일 세트를 쿼리할 수 있습니다.

항목 그룹 및 파일 세트 만들기

파일 세트는 사용자가 만든 항목 그룹 내에 있어야 합니다. 항목 그룹을 만들지 않은 경우 먼저 항목 그룹을 만든 다음 항목 그룹 내에 파일 세트를 만듭니다. 항목 그룹에 IAM 정책을 설정하여 항목 그룹 내의 파일 세트 및 기타 항목에 액세스할 수 있는 사용자를 정의할 수 있습니다.

콘솔

콘솔

  1. Dataplex > 항목 그룹 페이지로 이동합니다.

    Dataplex 항목 그룹으로 이동

  2. 항목 그룹 만들기를 클릭합니다.

  3. 항목 그룹 만들기 양식을 작성한 다음 만들기를 클릭합니다.

  4. 항목 그룹 세부정보 페이지가 열립니다. 항목 탭을 선택한 후 만들기를 클릭합니다.

  5. 파일 세트 만들기 양식을 작성합니다.

    1. 스키마를 첨부하려면 스키마 정의를 클릭하여 스키마 양식을 엽니다. + 필드 추가를 클릭하여 필드를 개별적으로 추가하거나 양식 오른쪽 상단의 텍스트로 수정을 전환하여 필드를 JSON 형식으로 지정합니다.
    2. 저장을 클릭하여 스키마를 저장합니다.
  6. 만들기를 클릭하여 파일 세트를 만듭니다.

gcloud

gcloud

1. 항목 그룹 만들기

gcloud data-catalog entry-groups create 명령어를 사용하여 연결된 스키마와 설명이 있는 항목 그룹을 만듭니다.

예:

gcloud data-catalog entry-groups create my_entrygroup \
    --location=us-central1

2. 항목 그룹 내에 파일 세트 만들기

gcloud data-catalog entry create 명령어를 사용하여 항목 그룹 내에 파일 세트를 만듭니다. 아래의 gcloud 명령어 예시로 파일 세트 데이터의 스키마를 포함하는 파일 세트 항목을 만들 수 있습니다.

gcloud data-catalog entries create my_fileset_entry \  
    --location=us-central1 \  
    --entry-group=my_entrygroup \  
    --type=FILESET \  
    --gcs-file-patterns=gs://my-bucket/*.csv \  
    --schema-from-file=path_to_schema_file \  
    --description="Fileset description ..."

플래그 참고:

  • --gcs-file-patterns: 파일 패턴 요구사항을 참조하세요.
  • --schema-from-file: 다음 샘플은 --schema-from-file 플래그에서 허용되는 스키마 텍스트 파일의 JSON 형식을 보여줍니다.
    [
      {
        "column": "first_name",
        "description": "First name",
        "mode": "REQUIRED",
        "type": "STRING"
      },
      {
        "column": "last_name",
        "description": "Last name",
        "mode": "REQUIRED",
        "type": "STRING"
      },
      {
        "column": "address",
        "description": "Address",
        "mode": "REPEATED",
        "type": "STRING"
      }
    ]
    

자바

이 샘플을 사용해 보기 전에 Data Catalog 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Data Catalog Java API 참고 문서를 참조하세요.

Data Catalog에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.cloud.datacatalog.v1.ColumnSchema;
import com.google.cloud.datacatalog.v1.CreateEntryRequest;
import com.google.cloud.datacatalog.v1.DataCatalogClient;
import com.google.cloud.datacatalog.v1.Entry;
import com.google.cloud.datacatalog.v1.EntryGroupName;
import com.google.cloud.datacatalog.v1.EntryType;
import com.google.cloud.datacatalog.v1.GcsFilesetSpec;
import com.google.cloud.datacatalog.v1.Schema;
import java.io.IOException;

// Sample to create file set entry
public class CreateFilesetEntry {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String entryGroupId = "fileset_entry_group";
    String entryId = "fileset_entry_id";
    createFilesetEntry(projectId, entryGroupId, entryId);
  }

  // Create Fileset Entry.
  public static void createFilesetEntry(String projectId, String entryGroupId, String entryId)
      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()) {
      // Construct the Entry for the Entry request.
      Entry entry =
          Entry.newBuilder()
              .setDisplayName("My Fileset")
              .setDescription("This fileset consists of ....")
              .setGcsFilesetSpec(
                  GcsFilesetSpec.newBuilder().addFilePatterns("gs://cloud-samples-data/*").build())
              .setSchema(
                  Schema.newBuilder()
                      .addColumns(
                          ColumnSchema.newBuilder()
                              .setColumn("first_name")
                              .setDescription("First name")
                              .setMode("REQUIRED")
                              .setType("STRING")
                              .build())
                      .addColumns(
                          ColumnSchema.newBuilder()
                              .setColumn("last_name")
                              .setDescription("Last name")
                              .setMode("REQUIRED")
                              .setType("STRING")
                              .build())
                      .addColumns(
                          ColumnSchema.newBuilder()
                              .setColumn("addresses")
                              .setDescription("Addresses")
                              .setMode("REPEATED")
                              .setType("RECORD")
                              .addSubcolumns(
                                  ColumnSchema.newBuilder()
                                      .setColumn("city")
                                      .setDescription("City")
                                      .setMode("NULLABLE")
                                      .setType("STRING")
                                      .build())
                              .addSubcolumns(
                                  ColumnSchema.newBuilder()
                                      .setColumn("state")
                                      .setDescription("State")
                                      .setMode("NULLABLE")
                                      .setType("STRING")
                                      .build())
                              .build())
                      .build())
              .setType(EntryType.FILESET)
              .build();

      // Construct the Entry request to be sent by the client.
      CreateEntryRequest entryRequest =
          CreateEntryRequest.newBuilder()
              .setParent(EntryGroupName.of(projectId, location, entryGroupId).toString())
              .setEntryId(entryId)
              .setEntry(entry)
              .build();

      // Use the client to send the API request.
      Entry entryCreated = dataCatalogClient.createEntry(entryRequest);
      System.out.printf("Entry created with name: %s", entryCreated.getName());
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 Data Catalog 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Data Catalog Node.js API 참고 문서를 참조하세요.

Data Catalog에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

async function createFileset() {
  // Create a fileset within an entry group.

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'my_project';
  // const entryGroupId = 'my_entry_group';
  // const entryId = 'my_entry';

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

  // Delete any pre-existing Entry with the same name that will be used
  // when creating the new Entry.
  try {
    const formattedName = datacatalog.entryPath(
      projectId,
      location,
      entryGroupId,
      entryId
    );
    await datacatalog.deleteEntry({name: formattedName});
  } catch (err) {
    console.log('Entry does not exist.');
  }

  // Delete any pre-existing Entry Group with the same name
  // that will be used to create the new Entry Group.
  try {
    const formattedName = datacatalog.entryGroupPath(
      projectId,
      location,
      entryGroupId
    );
    await datacatalog.deleteEntryGroup({name: formattedName});
  } catch (err) {
    console.log('Entry Group does not exist.');
  }

  // Construct the Entry Group for the Entry Group request.
  const entryGroup = {
    displayName: 'My Fileset Entry Group',
    description: 'This Entry Group consists of ....',
  };

  // Construct the Entry Group request to be sent by the client.
  const entryGroupRequest = {
    parent: datacatalog.locationPath(projectId, location),
    entryGroupId: entryGroupId,
    entryGroup: entryGroup,
  };

  // Use the client to send the API request.
  await datacatalog.createEntryGroup(entryGroupRequest);

  // Construct the Entry for the Entry request.
  const FILESET_TYPE = 4;

  const entry = {
    displayName: 'My Fileset',
    description: 'This fileset consists of ....',
    gcsFilesetSpec: {filePatterns: ['gs://my_bucket/*']},
    schema: {
      columns: [
        {
          column: 'city',
          description: 'City',
          mode: 'NULLABLE',
          type: 'STRING',
        },
        {
          column: 'state',
          description: 'State',
          mode: 'NULLABLE',
          type: 'STRING',
        },
        {
          column: 'addresses',
          description: 'Addresses',
          mode: 'REPEATED',
          subcolumns: [
            {
              column: 'city',
              description: 'City',
              mode: 'NULLABLE',
              type: 'STRING',
            },
            {
              column: 'state',
              description: 'State',
              mode: 'NULLABLE',
              type: 'STRING',
            },
          ],
          type: 'RECORD',
        },
      ],
    },
    type: FILESET_TYPE,
  };

  // Construct the Entry request to be sent by the client.
  const request = {
    parent: datacatalog.entryGroupPath(projectId, location, entryGroupId),
    entryId: entryId,
    entry: entry,
  };

  // Use the client to send the API request.
  const [response] = await datacatalog.createEntry(request);

  console.log(`Name: ${response.name}`);
  console.log(`Display name: ${response.displayName}`);
  console.log(`Type: ${response.type}`);
}
createFileset();

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.
project_id = "project_id"
fileset_entry_group_id = "entry_group_id"
fileset_entry_id = "entry_id"

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

datacatalog = datacatalog_v1.DataCatalogClient()

# Create an Entry Group.
entry_group_obj = datacatalog_v1.types.EntryGroup()
entry_group_obj.display_name = "My Fileset Entry Group"
entry_group_obj.description = "This Entry Group consists of ...."

entry_group = datacatalog.create_entry_group(
    parent=datacatalog_v1.DataCatalogClient.common_location_path(
        project_id, location
    ),
    entry_group_id=fileset_entry_group_id,
    entry_group=entry_group_obj,
)
print(f"Created entry group: {entry_group.name}")

# Create a Fileset Entry.
entry = datacatalog_v1.types.Entry()
entry.display_name = "My Fileset"
entry.description = "This fileset consists of ...."
entry.gcs_fileset_spec.file_patterns.append("gs://my_bucket/*.csv")
entry.type_ = datacatalog_v1.EntryType.FILESET

# Create the Schema, for example when you have a csv file.
entry.schema.columns.append(
    datacatalog_v1.types.ColumnSchema(
        column="first_name",
        description="First name",
        mode="REQUIRED",
        type_="STRING",
    )
)

entry.schema.columns.append(
    datacatalog_v1.types.ColumnSchema(
        column="last_name", description="Last name", mode="REQUIRED", type_="STRING"
    )
)

# Create the addresses parent column
addresses_column = datacatalog_v1.types.ColumnSchema(
    column="addresses", description="Addresses", mode="REPEATED", type_="RECORD"
)

# Create sub columns for the addresses parent column
addresses_column.subcolumns.append(
    datacatalog_v1.types.ColumnSchema(
        column="city", description="City", mode="NULLABLE", type_="STRING"
    )
)

addresses_column.subcolumns.append(
    datacatalog_v1.types.ColumnSchema(
        column="state", description="State", mode="NULLABLE", type_="STRING"
    )
)

entry.schema.columns.append(addresses_column)

entry = datacatalog.create_entry(
    parent=entry_group.name, entry_id=fileset_entry_id, entry=entry
)
print(f"Created fileset entry: {entry.name}")

REST 및 명령줄

REST

해당 언어의 Cloud 클라이언트 라이브러리에 액세스할 수 없거나 REST 요청을 사용하여 API를 테스트하려면 다음 예시를 확인하고 Data Catalog REST API entryGroups.createentryGroups.entries.create 문서를 참조하세요.

1. 항목 그룹 만들기

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: Google Cloud 프로젝트 ID
  • entryGroupId: ID는 문자 또는 밑줄로 시작해야 하며 영어, 숫자, 밑줄로만 구성될 수 있고 64자 이하여야 합니다.
  • displayName: 항목 그룹의 텍스트 이름입니다.

HTTP 메서드 및 URL:

POST https://datacatalog.googleapis.com/v1/projects/project-id/locations/region/entryGroups?entryGroupId=entryGroupId

JSON 요청 본문:

{
  "displayName": "Entry Group display name"
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/my_projectid/locations/us-central1/entryGroups/my_entry_group",
  "displayName": "Entry Group display name",
  "dataCatalogTimestamps": {
    "createTime": "2019-10-19T16:35:50.135Z",
    "updateTime": "2019-10-19T16:35:50.135Z"
  }
}

2. 항목 그룹 내에 파일 세트 만들기

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project_id: Google Cloud 프로젝트 ID
  • entryGroupId: 기존 entryGroups의 ID입니다. 이 StryGroup에서 파일 세트가 생성됩니다.
  • entryId: 새 파일 세트의 항목 ID입니다. ID는 문자 또는 밑줄로 시작해야 하며 영어, 숫자, 밑줄로만 구성될 수 있고 64자 이하여야 합니다.
  • description: 파일 세트 설명입니다.
  • displayName: 파일 세트 항목의 텍스트 이름입니다.
  • filePatterns : 'gs://bucket_name/'로 시작해야 합니다. 파일 패턴 요구사항을 참조하세요.
  • schema: 파일 세트 스키마입니다.

    JSON 스키마 예시:
    { ...
      "schema": {
        "columns": [
          {
            "column": "first_name",
            "description": "First name",
            "mode": "REQUIRED",
            "type": "STRING"
          },
          {
            "column": "last_name",
            "description": "Last name",
            "mode": "REQUIRED",
            "type": "STRING"
          },
          {
            "column": "address",
            "description": "Address",
            "mode": "REPEATED",
            "subcolumns": [
              {
                "column": "city",
                "description": "City",
                "mode": "NULLABLE",
                "type": "STRING"
              },
              {
                "column": "state",
                "description": "State",
                "mode": "NULLABLE",
                "type": "STRING"
              }
            ],
            "type": "RECORD"
          }
        ]
      }
    ...
    }
    

HTTP 메서드 및 URL:

POST https://datacatalog.googleapis.com/v1/projects/project_id/locations/region/entryGroups/entryGroupId/entries?entryId=entryId

JSON 요청 본문:

{
  "description": "Fileset description.",
  "displayName": "Display name",
  "gcsFilesetSpec": {
    "filePatterns": [
      "gs://bucket_name/file_pattern"
    ]
  },
  "type": "FILESET",
  "schema": { schema }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/my_project_id/locations/us-central1/entryGroups/my_entryGroup_id/entries/my_entry_id",
  "type": "FILESET",
  "displayName": "My Fileset",
  "description": "My Fileset description.",
  "schema": {
    "columns": [
      {
        "type": "STRING",
        "description": "First name",
        "mode": "REQUIRED",
        "column": "first_name"
      },
      {
        "type": "STRING",
        "description": "Last name",
        "mode": "REQUIRED",
        "column": "last_name"
      },
      {
        "type": "RECORD",
        "description": "Address",
        "mode": "REPEATED",
        "column": "address",
        "subcolumns": [
          {
            "type": "STRING",
            "description": "City",
            "mode": "NULLABLE",
            "column": "city"
          },
          {
            "type": "STRING",
            "description": "State",
            "mode": "NULLABLE",
            "column": "state"
          }
        ]
      }
    ]
  },
  "gcsFilesetSpec": {
    "filePatterns": [
      "gs://my_bucket_name/chicago_taxi_trips/csv/shard-*.csv"
    ]
  },
  "sourceSystemTimestamps": {
    "createTime": "2019-10-23T23:11:26.326Z",
    "updateTime": "2019-10-23T23:11:26.326Z"
  },
"linkedResource": "//datacatalog.googleapis.com/projects/my_project_id/locations/us-central1/entryGroups/my_entryGroup_id/entries/my_entry_id"
}

IAM 역할, 권한, 정책

Data Catalog는 파일 세트 및 기타 Data Catalog 리소스의 권한 관리를 용이하게 하기 위해 항목 및 entryGroup 역할을 정의합니다.

항목 역할 설명
dataCatalog.entryOwner 특정 항목 또는 항목 그룹의 소유자입니다.
  • 권한:
    • datacatalog.entries.(*)
    • datacatalog.entryGroups.get
  • 적용 가능성:
    • 조직, 프로젝트, entryGroup.
dataCatalog.entryViewer 항목 및 항목 그룹의 세부정보를 볼 수 있습니다.
  • 권한
    • datacatalog.entries.get
    • datacatalog.entryGroups.get
  • 적용 가능성:
    • 조직, 프로젝트, entryGroup.
항목 그룹 역할 설명
dataCatalog.entryGroupOwner 특정 항목 그룹의 소유자입니다.
  • 권한:
    • datacatalog.entryGroups.(*)
    • datacatalog entries.(*)
  • 적용 가능성:
    • 조직, 프로젝트, entryGroups 수준
dataCatalog.entryGroupCreator 프로젝트 내에서 entryGroups를 만들 수 있습니다. entryGroup의 생성자에게는 자동으로 dataCatalog.entryGroupOwner 역할이 부여됩니다.
  • 권한
    • datacatalog.entryGroups.(get | create)
  • 적용 가능성:
    • 조직 및 프로젝트 수준

IAM 정책 설정

datacatalog.<resource>.setIamPolicy 권한이 있는 사용자는 Data Catalog 항목 그룹 및 기타 Data Catalog 리소스에 IAM 정책을 설정할 수 있습니다(Data Catalog 참조).

gcloud

콘솔

Data Catalog UI항목 그룹 세부정보 페이지로 이동한 다음 오른쪽에 있는 IAM 패널을 사용하여 권한을 부여하거나 취소합니다.

항목 그룹 역할 부여

예시 1:

파일 세트에 대한 비즈니스 컨텍스트가 다른 회사는 별도의 order-filesuser-files 항목 그룹을 만듭니다.

order-files 그룹에는 취소 및 완료된 주문 파일이 있는 스토리지 버킷이 포함되고 user-files 그룹에는 PII 파일이 있는 스토리지 버킷이 포함됩니다.
그림 1. 주문 데이터 및 사용자 데이터를 다른 항목 그룹에 저장하는 방법의 예시입니다.

회사는 사용자에게 order-files에 대한 EntryGroup 뷰어 역할을 부여합니다. 즉 해당 항목 그룹에 포함된 항목만 검색할 수 있습니다. 검색결과는 user-files 항목 그룹의 항목을 반환하지 않습니다.

예시 2:

회사는 project_entry_group 프로젝트의 사용자에게만 EntryGroup 뷰어 역할을 부여합니다. 사용자는 해당 프로젝트 내의 항목만 볼 수 있습니다.

파일 세트 검색

사용자는 type 속성을 사용하여 Data Catalog에서 검색 범위를 제한할 수 있습니다. type=entry_group는 검색어를 항목 그룹으로 제한하며 type=fileset는 파일 세트만 검색합니다. type 속성은 projectid와 같은 다른 속성과 함께 사용할 수 있습니다.

gcloud

  • 프로젝트의 항목 그룹을 검색합니다.

    gcloud data-catalog search \  
        --include-project-ids=my-project
        "projectid=my-project type=entry_group"
    

  • 액세스할 수 있는 모든 항목 그룹을 검색합니다.

    gcloud data-catalog search \  
        --include-project-ids=my-project
        "type=entry_group"
    

  • 프로젝트에서 파일 세트를 검색합니다.

    gcloud data-catalog search \  
        --include-project-ids=my-project
        "type=entry.fileset"
    

  • 프로젝트에서 파일 세트를 검색합니다 - 단순 문법

    gcloud data-catalog search \  
        --include-project-ids=my-project
        "type=fileset"