Actualiza el intercambio de datos (v1)

Actualiza la descripción de un intercambio de datos existente.

Muestra de código

Go

Antes de probar este ejemplo, sigue las instrucciones de configuración para Go incluidas en la guía de inicio rápido de BigQuery sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de BigQuery para Go.

Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para bibliotecas cliente.


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

Antes de probar este ejemplo, sigue las instrucciones de configuración para Java incluidas en la guía de inicio rápido de BigQuery sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de BigQuery para Java.

Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para bibliotecas cliente.

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

Antes de probar este ejemplo, sigue las instrucciones de configuración para Node.js incluidas en la guía de inicio rápido de BigQuery sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de BigQuery para Node.js.

Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para bibliotecas cliente.

'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

Antes de probar este ejemplo, sigue las instrucciones de configuración para Python incluidas en la guía de inicio rápido de BigQuery sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de BigQuery para Python.

Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para bibliotecas cliente.

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

¿Qué sigue?

Si quieres buscar y filtrar muestras de código para otros productos de Google Cloud , consulta el navegador de muestras deGoogle Cloud .