Crea scheda (v1)

Crea una scheda all'interno di un data exchange per condividere un set di dati BigQuery.

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

// 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

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.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

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();

/**
 * 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

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

Passaggi successivi

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