建立資料交換作業 (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 範例瀏覽工具。