데이터 교환 만들기(v1)

Analytics Hub에서 새 데이터 교환을 만듭니다.

코드 샘플

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"
)

// createDataExchange creates a new data exchange in Analytics Hub.
func createDataExchange(ctx context.Context, w io.Writer, dataExchangeID string, projectID string, locationID string) error {
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)
	dataExchange := &analyticshubpb.DataExchange{
		DisplayName: "Example Data Exchange",
		Description: "Data exchange created for analytics demonstration.",
	}

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

	req := &analyticshubpb.CreateDataExchangeRequest{
		Parent:         parent,
		DataExchangeId: dataExchangeID,
		DataExchange:   dataExchange,
	}

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

	fmt.Fprintf(w, "Created data exchange: %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.CreateDataExchangeRequest;
import com.google.cloud.bigquery.analyticshub.v1.DataExchange;
import java.io.IOException;

public class CreateDataExchange {

  public static void main(String[] args) throws IOException {
    String dataExchangeId = "example_data_exchange_id";
    String projectId = "example-project-id";
    String locationId = "example-location-id";
    createDataExchange(dataExchangeId, projectId, locationId);
  }

  public static void createDataExchange(String dataExchangeId, String projectId, String locationId)
      throws IOException {
    try (AnalyticsHubServiceClient client = AnalyticsHubServiceClient.create()) {
      DataExchange dataExchange =
          DataExchange.newBuilder()
              .setDisplayName("Example Data Exchange")
              .setDescription("Example description")
              .build();
      String parent = String.format("projects/%s/locations/%s", projectId, locationId);

      CreateDataExchangeRequest request =
          CreateDataExchangeRequest.newBuilder()
              .setParent(parent)
              .setDataExchangeId(dataExchangeId)
              .setDataExchange(dataExchange)
              .build();

      DataExchange response = client.createDataExchange(request);
      System.out.println("Data exchange created successfully: " + 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();

/**
 * Use the createDataExchange method
 *
 * @param {string} dataExchangeId - ID of the data exchange to create. Must contain only letters, numbers, and underscores (e.g., 'example_data_exchange'). Max length: 100 bytes.
 * @param {string} projectId - Google Cloud project ID where the data exchange will be created.
 * @param {string} locationId - Geographic location of the data exchange (e.g., 'us' or 'us-central1').
 */
async function createDataExchange(dataExchangeId, projectId, locationId) {
  try {
    const parent = `projects/${projectId}/locations/${locationId}`;
    const dataExchange = {
      displayName: 'Example Data Exchange',
      description: 'Analytics Hub data exchange for dataset sharing',
    };

    const request = {
      parent,
      dataExchangeId,
      dataExchange,
    };

    const [response] = await client.createDataExchange(request);
    console.log(`Created data exchange: ${response.name}`);
    return response;
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Data exchange already exists: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument provided: ${err.message}`);
    } else {
      console.error(`Failed to create data exchange: ${err.message}`);
    }
    throw err;
  }
}

module.exports = { createDataExchange };

Python

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

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

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


def create_data_exchange(
    data_exchange_id: str, project_id: str, location_id: str
) -> None:
    """Creates a data exchange in Analytics Hub.

    Args:
        data_exchange_id: The identifier for the data exchange.
        project_id: The Google Cloud project ID.
        location_id: The Google Cloud region or location for the data exchange,
          for example 'us' or 'us-central1'.
    """
    client = bigquery_analyticshub_v1.AnalyticsHubServiceClient()

    parent = f"projects/{project_id}/locations/{location_id}"
    data_exchange = bigquery_analyticshub_v1.DataExchange(
        display_name="Sample Data Exchange",
        description="Data exchange created for analytics sharing",
    )

    request = bigquery_analyticshub_v1.CreateDataExchangeRequest(
        parent=parent,
        data_exchange_id=data_exchange_id,
        data_exchange=data_exchange,
    )

    try:
        response = client.create_data_exchange(request=request)
        print(f"Created data exchange: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Error creating data exchange: {error}")

다음 단계

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