Mengupdate pertukaran data (v1)

Memperbarui deskripsi pertukaran data yang ada.

Contoh kode

Go

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Go API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.


import (
	"context"
	"fmt"
	"io"

	analyticshub "cloud.google.com/go/bigquery/analyticshub/apiv1"
	analyticshubpb "cloud.google.com/go/bigquery/analyticshub/apiv1/analyticshubpb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateDataExchange updates the description of a data exchange.
func updateDataExchange(ctx context.Context, w io.Writer, projectID string, locationID string, dataExchangeID string) error {
	client, err := analyticshub.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("analyticshub.NewClient: %w", err)
	}
	defer client.Close()

	updateMask := &fieldmaskpb.FieldMask{
		Paths: []string{"description"},
	}
	dataExchange := &analyticshubpb.DataExchange{
		Name:        fmt.Sprintf("projects/%s/locations/%s/dataExchanges/%s", projectID, locationID, dataExchangeID),
		Description: "Updated description for this data exchange",
	}

	req := &analyticshubpb.UpdateDataExchangeRequest{
		UpdateMask:   updateMask,
		DataExchange: dataExchange,
	}

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

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

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Java API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

import com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubServiceClient;
import com.google.cloud.bigquery.analyticshub.v1.DataExchange;
import com.google.protobuf.FieldMask;

public class UpdateDataExchange {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project_id";
    String locationId = "example-location_id";
    String dataExchangeId = "example-data_exchange_id";
    updateDataExchange(projectId, locationId, dataExchangeId);
  }

  public static void updateDataExchange(
      String projectId, String locationId, String dataExchangeId) throws Exception {
    // Initialize client that will be automatically closed when finished.
    try (AnalyticsHubServiceClient client = AnalyticsHubServiceClient.create()) {
      // Specify the fields to update to perform a partial update.
      FieldMask updateMask = FieldMask.newBuilder().addPaths("description").build();

      String dataExchangeName =
          String.format(
              "projects/%s/locations/%s/dataExchanges/%s",
              projectId, locationId, dataExchangeId);
      DataExchange dataExchange =
          DataExchange.newBuilder()
              .setName(dataExchangeName)
              .setDescription("Updated description for example-data-exchange")
              .build();

      DataExchange response = client.updateDataExchange(dataExchange, updateMask);
      System.out.println("Updated data exchange: " + response.getName());
    }
  }
}

Node.js

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Node.js API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

'use strict';

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

const client = new AnalyticsHubServiceClient();

/**
 * Use the updateDataExchange method
 *
 * @param {string} projectId - The Google Cloud project ID hosting the data exchange.
 * @param {string} locationId - The Google Cloud region or location for the data exchange (e.g., 'us').
 * @param {string} dataExchangeId - The ID of the data exchange to update. Must contain only Unicode letters, numbers (0-9), and underscores (_), max length 100 bytes.
 */
async function updateDataExchange(projectId, locationId, dataExchangeId) {
  try {
    // Populate the resource name to bind the target path and provide the fields to update.
    const dataExchange = {
      name: client.dataExchangePath(projectId, locationId, dataExchangeId),
      description: 'Updated Data Exchange description',
    };

    // Specify the field mask paths matching the fields to modify.
    const updateMask = {
      paths: ['description'],
    };

    const request = {
      dataExchange,
      updateMask,
    };

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

    console.log(`Updated data exchange: ${response.name}`);
    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 if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument provided: ${err.message}`);
    } else {
      console.error(`Failed to update data exchange: ${err.message}`);
    }
    throw err;
  }
}

module.exports = { updateDataExchange };

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Python API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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


def update_data_exchange(
    project_id: str, location_id: str, data_exchange_id: str
) -> None:
    """Updates an existing data exchange.

    Args:
        project_id: The Google Cloud project ID.
        location_id: The geographic location of the data exchange.
        data_exchange_id: The identifier of the data exchange to update.
    """
    client = bigquery_analyticshub_v1.AnalyticsHubServiceClient()

    update_mask = field_mask_pb2.FieldMask(paths=["description"])
    data_exchange = bigquery_analyticshub_v1.DataExchange(
        name=f"projects/{project_id}/locations/{location_id}/dataExchanges/{data_exchange_id}",
        description="Updated data exchange description.",
    )

    try:
        response = client.update_data_exchange(
            request=bigquery_analyticshub_v1.UpdateDataExchangeRequest(
                data_exchange=data_exchange,
                update_mask=update_mask,
            )
        )
        print(f"Updated data exchange: {response.name}")
        print(f"Description: {response.description}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"Request failed: {e}")

Langkah berikutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contohGoogle Cloud .