Get data exchange (v1)

אחזור של חילופי נתונים ב-Analytics Hub לפי שם המשאב.

דוגמת קוד

Go

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Go במדריך למתחילים של BigQuery באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של BigQuery Go API.

כדי לבצע אימות ב-BigQuery, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לספריות לקוח.


import (
	"context"
	"fmt"
	"io"

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

// getDataExchange retrieves an Analytics Hub data exchange by resource name.
func getDataExchange(ctx context.Context, w io.Writer, projectID string, locationID string, dataExchangeID string) error {
	name := fmt.Sprintf("projects/%s/locations/%s/dataExchanges/%s", projectID, locationID, dataExchangeID)

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

	req := &analyticshubpb.GetDataExchangeRequest{
		Name: name,
	}

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

	fmt.Fprintf(w, "Retrieved data exchange: %s\n", exchange.GetName())
	return nil
}

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Java במדריך למתחילים של BigQuery באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של BigQuery Java API.

כדי לבצע אימות ב-BigQuery, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לספריות לקוח.

import com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubServiceClient;
import com.google.cloud.bigquery.analyticshub.v1.DataExchange;
import com.google.cloud.bigquery.analyticshub.v1.DataExchangeName;
import java.io.IOException;

public class GetDataExchange {

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

  public static void getDataExchange(String projectId, String locationId, String dataExchangeId)
      throws IOException {
    try (AnalyticsHubServiceClient client = AnalyticsHubServiceClient.create()) {
      String name = DataExchangeName.of(projectId, locationId, dataExchangeId).toString();

      DataExchange response = client.getDataExchange(name);

      System.out.println("Data exchange retrieved successfully: " + response.getName());
      System.out.println("Display name: " + response.getDisplayName());
      System.out.println("Description: " + response.getDescription());
    }
  }
}

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Node.js במדריך למתחילים של BigQuery באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של BigQuery Node.js API.

כדי לבצע אימות ב-BigQuery, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לספריות לקוח.

'use strict';

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

const client = new AnalyticsHubServiceClient();

/**
 * Use the getDataExchange method
 *
 * @param {string} projectId - The Google Cloud project ID.
 * @param {string} locationId - The Google Cloud region or location of the data exchange.
 * @param {string} dataExchangeId - The caller-specified ID of the data exchange.
 */
async function getDataExchange(projectId, locationId, dataExchangeId) {
  try {
    const name = `projects/${projectId}/locations/${locationId}/dataExchanges/${dataExchangeId}`;
    const request = {
      name,
    };

    const [response] = await client.getDataExchange(request);

    console.log(`Retrieved data exchange: ${response.name}`);
    console.log(`Display name: ${response.displayName}`);
    console.log(`Description: ${response.description}`);
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Data exchange not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else {
      console.error(`Failed to retrieve data exchange: ${err.message}`);
    }
  }
}

module.exports = { getDataExchange };

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Python במדריך למתחילים של BigQuery באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של BigQuery Python API.

כדי לבצע אימות ב-BigQuery, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לספריות לקוח.

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


def get_data_exchange(
    project_id: str, location_id: str, data_exchange_id: str
) -> None:
    """Retrieves a data exchange from Analytics Hub.

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

    name = f"projects/{project_id}/locations/{location_id}/dataExchanges/{data_exchange_id}"

    request = bigquery_analyticshub_v1.GetDataExchangeRequest(name=name)

    try:
        response = client.get_data_exchange(request=request)
        print(f"Data exchange name: {response.name}")
        print(f"Display name: {response.display_name}")
        print(f"Description: {response.description}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to retrieve data exchange: {error}")

המאמרים הבאים

כדי לחפש ולסנן דוגמאות קוד למוצרים אחרים של Google Cloud , ראו דפדפן לדוגמה שלGoogle Cloud .