Crea data exchange (v1)

Crea un nuovo scambio di dati in Analytics Hub.

Esempio di codice

Go

Prima di provare questo esempio, segui le istruzioni di configurazione di Go nella guida rapida di BigQuery per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API BigQuery Go.

Per eseguire l'autenticazione in BigQuery, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configura l'autenticazione per le librerie client.


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

Prima di provare questo esempio, segui le istruzioni di configurazione di Java nella guida rapida di BigQuery per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API BigQuery Java.

Per eseguire l'autenticazione in BigQuery, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configura l'autenticazione per le librerie client.

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

Prima di provare questo esempio, segui le istruzioni di configurazione di Node.js nella guida rapida di BigQuery per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API BigQuery Node.js.

Per eseguire l'autenticazione in BigQuery, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configura l'autenticazione per le librerie client.

'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

Prima di provare questo esempio, segui le istruzioni di configurazione di Python nella guida rapida di BigQuery per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API BigQuery Python.

Per eseguire l'autenticazione in BigQuery, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configura l'autenticazione per le librerie client.

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

Passaggi successivi

Per cercare e filtrare gli esempi di codice per altri prodotti Google Cloud , consulta il browser degli esempi diGoogle Cloud .