Crea una asignación de reserva

Crea una asignación para correlacionar un proyecto, una carpeta o una organización con una reserva de BigQuery.

Muestra de código

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.

const {
  ReservationServiceClient,
} = require('@google-cloud/bigquery-reservation').v1;
const {status} = require('@grpc/grpc-js');

const client = new ReservationServiceClient();

/**
 * Creates an assignment to assign a project to a reservation.
 * A reservation assignment lets a project submit jobs of a certain type
 * using slots from the specified reservation.
 *
 * @param {string} projectId Google Cloud Project ID that owns the reservation, for example 'example-project-id'.
 * @param {string} location Google Cloud Location, for example 'us-central1'.
 * @param {string} reservationId The ID of the reservation to which the project will be assigned, for example 'example-reservation'.
 */
async function createAssignment(
  projectId,
  location = 'us-central1',
  reservationId = 'example-reservation',
) {
  const parent = client.reservationPath(projectId, location, reservationId);
  const request = {
    parent,
    assignment: {
      assignee: `projects/${projectId}`,
      jobType: 'QUERY',
    },
  };

  try {
    const [assignment] = await client.createAssignment(request);
    console.log(`Created assignment: ${assignment.name}`);
    console.log(`  Assignee: ${assignment.assignee}`);
    console.log(`  Job Type: ${assignment.jobType}`);
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.log(
        `Assignment for project ${projectId} to reservation ${reservationId} already exists.`,
      );
    } else {
      console.error('Error creating assignment:', err);
    }
  }
}

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.

from google.api_core import exceptions
from google.cloud import bigquery_reservation_v1

client = bigquery_reservation_v1.ReservationServiceClient()


def create_assignment(project_id: str, location: str, reservation_id: str):
    """Creates a new assignment for a reservation.

    This shows how to create an assignment that gives a project access to
    a reservation.

    Args:
        project_id: The Google Cloud project ID of the reservation owner.
        location: The geographic location of the reservation, for example, "US".
        reservation_id: The ID of the reservation to create the assignment in.
    """

    parent = client.reservation_path(project_id, location, reservation_id)
    assignee = f"projects/{project_id}"
    assignment = bigquery_reservation_v1.Assignment(
        assignee=assignee,
        job_type=bigquery_reservation_v1.Assignment.JobType.QUERY,
    )

    try:
        created_assignment = client.create_assignment(
            parent=parent, assignment=assignment
        )
        print(f"Created assignment: {created_assignment.name}")
    except exceptions.AlreadyExists:
        print(f"Assignment for project {project_id} and job type QUERY already exists.")

¿Qué sigue?

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