목록 만들기(v1)

데이터 교환 내에 목록을 만들어 BigQuery 데이터 세트를 공유합니다.

코드 샘플

Go

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

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.


import (
	"context"
	"fmt"
	"io"

	analyticshub "cloud.google.com/go/bigquery/analyticshub/apiv1"
	analyticshubpb "cloud.google.com/go/bigquery/analyticshub/apiv1/analyticshubpb"
)

// createListing creates a listing within a Data Exchange to share a BigQuery dataset.
func createListing(ctx context.Context, w io.Writer, listingID string, projectID string, locationID string, dataExchangeID string, datasetID string) error {
	parent := fmt.Sprintf("projects/%s/locations/%s/dataExchanges/%s", projectID, locationID, dataExchangeID)
	listing := &analyticshubpb.Listing{
		DisplayName: "Example Listing",
		Description: "Listing created to share dataset resources",
		Source: &analyticshubpb.Listing_BigqueryDataset{
			BigqueryDataset: &analyticshubpb.Listing_BigQueryDatasetSource{
				Dataset: fmt.Sprintf("projects/%s/datasets/%s", projectID, datasetID),
			},
		},
	}

	client, err := analyticshub.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("analyticshub.NewClient: %w", err)
	}
	defer client.Close()

	req := &analyticshubpb.CreateListingRequest{
		Parent:    parent,
		ListingId: listingID,
		Listing:   listing,
	}

	resp, err := client.CreateListing(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateListing: %w", err)
	}

	fmt.Fprintf(w, "Created listing: %s\n", resp.GetName())
	return nil
}

Java

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

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

import com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubServiceClient;
import com.google.cloud.bigquery.analyticshub.v1.CreateListingRequest;
import com.google.cloud.bigquery.analyticshub.v1.Listing;
import java.io.IOException;

public class CreateListing {

  public static void main(String[] args) throws IOException {
    String listingId = "example-listing_id";
    String projectId = "example-project_id";
    String locationId = "example-location_id";
    String dataExchangeId = "example-data_exchange_id";
    String datasetId = "example-dataset_id";
    createListing(listingId, projectId, locationId, dataExchangeId, datasetId);
  }

  public static void createListing(
      String listingId,
      String projectId,
      String locationId,
      String dataExchangeId,
      String datasetId)
      throws IOException {
    try (AnalyticsHubServiceClient client = AnalyticsHubServiceClient.create()) {
      String parent =
          String.format(
              "projects/%s/locations/%s/dataExchanges/%s",
              projectId, locationId, dataExchangeId);

      String dataset = String.format("projects/%s/datasets/%s", projectId, datasetId);
      Listing.BigQueryDatasetSource datasetSource =
          Listing.BigQueryDatasetSource.newBuilder()
              .setDataset(dataset)
              .build();

      Listing listing =
          Listing.newBuilder()
              .setDisplayName("Sample Listing")
              .setBigqueryDataset(datasetSource)
              .build();

      CreateListingRequest request =
          CreateListingRequest.newBuilder()
              .setParent(parent)
              .setListingId(listingId)
              .setListing(listing)
              .build();

      Listing response = client.createListing(request);
      System.out.println("Created listing: " + response.getName());
    }
  }
}

Node.js

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

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

'use strict';

const {AnalyticsHubServiceClient} = require('@google-cloud/bigquery-analyticshub');
const {status} = require('@grpc/grpc-js');

const client = new AnalyticsHubServiceClient();

/**
 * Creates a listing in a data exchange to share a BigQuery dataset.
 *
 * @param {string} listingId - The ID of the listing to create. Must contain only Unicode letters, numbers (0-9), underscores (_). Max length: 100 bytes.
 * @param {string} projectId - Google Cloud project ID where the data exchange resides.
 * @param {string} locationId - Location of the data exchange and listing (for example, 'us' or 'us-central1').
 * @param {string} dataExchangeId - ID of the parent data exchange where the listing will be created.
 * @param {string} datasetId - ID of the existing BigQuery dataset to be published as a listing.
 */
async function createListing(listingId, projectId, locationId, dataExchangeId, datasetId) {
  try {
    const parent = `projects/${projectId}/locations/${locationId}/dataExchanges/${dataExchangeId}`;
    const listing = {
      displayName: 'Example Listing',
      bigqueryDataset: {
        dataset: `projects/${projectId}/datasets/${datasetId}`,
      },
    };

    const request = {
      parent,
      listingId,
      listing,
    };

    const [response] = await client.createListing(request);
    console.log(`Created listing: ${response.name}`);
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Listing ${listingId} already exists.`);
    } else if (err.code === status.NOT_FOUND) {
      console.error(`Specified parent resource was not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied creating listing: ${err.message}`);
    } else {
      console.error(`Failed to create listing: ${err.message}`);
    }
  }
}

module.exports = { createListing };

Python

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

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

import google.api_core.exceptions
from google.cloud import bigquery_analyticshub_v1


def create_listing(
    listing_id: str,
    project_id: str,
    location_id: str,
    data_exchange_id: str,
    dataset_id: str,
) -> None:
    """Creates a listing in an Analytics Hub data exchange.

    Args:
        listing_id: The identifier for the listing. Must contain only letters,
          numbers, and underscores (maximum 100 bytes).
        project_id: The Google Cloud project ID hosting the data exchange and
          BigQuery dataset.
        location_id: The Google Cloud region or multi-region (for example, 'us'
          or 'us-central1').
        data_exchange_id: The identifier of the existing DataExchange.
        dataset_id: The identifier of the BigQuery dataset to share in the
          listing.
    """
    client = bigquery_analyticshub_v1.AnalyticsHubServiceClient()

    listing = bigquery_analyticshub_v1.Listing(
        display_name="Example Listing",
        description="Dataset shared via Analytics Hub",
        bigquery_dataset=bigquery_analyticshub_v1.Listing.BigQueryDatasetSource(
            dataset=f"projects/{project_id}/datasets/{dataset_id}"
        ),
    )
    parent = f"projects/{project_id}/locations/{location_id}/dataExchanges/{data_exchange_id}"

    request = bigquery_analyticshub_v1.CreateListingRequest(
        parent=parent,
        listing_id=listing_id,
        listing=listing,
    )

    try:
        response = client.create_listing(request=request)
        print(f"Created listing: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"Failed to create listing: {e}")

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저 참조하기