Instanzpartitionen erstellen und verwalten

Auf dieser Seite wird beschrieben, wie Sie Spanner-Instanzpartitionen erstellen und verwalten.

Hinweise

Wenn Sie Instanzpartitionen verwenden möchten, müssen Sie die Datenbankoption opt_in_dataplacement_preview in Ihrer leeren Datenbank festlegen:

Console

  1. Rufen Sie in der Google Cloud Console die Seite Instanzen auf.

    Instanzen

  2. Wählen Sie die Instanz aus, der Sie Instanzpartitionen hinzufügen möchten.

  3. Wählen Sie die leere Datenbank aus, in der Sie Daten partitionieren möchten.

  4. Klicken Sie im Navigationsmenü auf Spanner Studio.

  5. Klicken Sie auf der Seite Spanner Studio auf  Neuer Tab oder verwenden Sie den leeren Editor-Tab.

  6. Geben Sie die folgende ALTER DATABASE-DDL-Anweisung ein.

    GoogleSQL

    ALTER DATABASE DATABASE_ID SET OPTIONS (opt_in_dataplacement_preview = true);
    

    Ersetzen Sie DATABASE_ID durch die eindeutige Kennung Ihrer Datenbank.

    PostgreSQL

    ALTER DATABASE DATABASE_ID SET "spanner.opt_in_dataplacement_preview" = TRUE;
    

    Ersetzen Sie DATABASE_ID durch die eindeutige Kennung Ihrer Datenbank.

  7. Klicken Sie auf Ausführen.

gcloud

Verwenden Sie gcloud spanner databases ddl update, um die Datenbankoption opt_in_dataplacement_preview festzulegen.

GoogleSQL

gcloud spanner databases ddl update DATABASE_ID \
  --instance=INSTANCE_ID \
  --ddl="ALTER DATABASE DATABASE_ID SET OPTIONS (opt_in_dataplacement_preview = true);"

Ersetzen Sie Folgendes:

  • DATABASE_ID: Die permanente Kennzeichnung Ihrer Spanner-Datenbank.
  • INSTANCE_ID: Die permanente Kennung Ihrer Spanner-Instanz.

PostgreSQL

gcloud spanner databases ddl update DATABASE_ID \
  --instance=INSTANCE_ID \
  --ddl="ALTER DATABASE DATABASE_ID SET "spanner.opt_in_dataplacement_preview" = TRUE"

Ersetzen Sie Folgendes:

  • DATABASE_ID: Die permanente Kennzeichnung Ihrer Spanner-Datenbank.
  • INSTANCE_ID: Die permanente Kennung Ihrer Spanner-Instanz.

Instanzpartition erstellen

Console

  1. Öffnen Sie in der Google Cloud Console die Seite Spanner.

    Spanner aufrufen

  2. Wählen Sie die Instanz aus, der Sie Instanzpartitionen hinzufügen möchten.

  3. Wählen Sie im Navigationsmenü Instanzpartitionen aus.

  4. Klicken Sie auf Instanzpartition erstellen.

  5. Geben Sie eine Partitions-ID ein, um Ihre Instanzpartition dauerhaft zu identifizieren. Die Instanzpartitions-ID darf imGoogle Cloud -Projekt ebenfalls nur einmal vorkommen. Sie können die Instanzpartitions-ID später nicht mehr ändern.

  6. Wählen Sie im Bereich Konfiguration auswählen die Option Regional oder Mehrere Regionen aus. Wenn Sie die Spezifikationen der Regionen vergleichen möchten, klicken Sie auf Regionskonfigurationen vergleichen.

  7. Wählen Sie im Drop-down-Menü eine Konfiguration aus.

  8. Klicken Sie im Bereich Rechenkapazität zuweisen unter Einheit auf eine der folgenden Optionen:

    • Verarbeitungseinheiten für kleine Instanzpartitionen.
    • Knoten für große Instanzen. Ein Knoten entspricht 1.000 Verarbeitungseinheiten.
  9. Geben Sie einen Wert für die ausgewählte Einheit ein.

    Ihre Instanzpartition muss mindestens einen Knoten oder 1.000 Verarbeitungseinheiten haben.

  10. Klicken Sie auf Erstellen, um die Instanzpartition zu erstellen.

gcloud

Verwenden Sie zum Erstellen einer Instanzpartition gcloud beta spanner instance-partitions create.

gcloud beta spanner instance-partitions create INSTANCE_PARTITION_ID \
  --config=INSTANCE_PARTITION_CONFIG \
  --description="INSTANCE_PARTITION_DESCRIPTION" \
  --instance=INSTANCE_ID \
  [--nodes=NODE_COUNT | --processing-units=PROCESSING_UNIT_COUNT]

Ersetzen Sie Folgendes:

  • INSTANCE_PARTITION_ID: Die permanente Kennung der Instanzpartition, die in Ihrem Google Cloud -Projekt eindeutig ist. Sie können die Instanzpartitions-ID später nicht mehr ändern.
  • INSTANCE_PARTITION_CONFIG: Die permanente Kennzeichnung Ihrer Instanzpartitionskonfiguration, die den geografischen Standort der Instanzpartition definiert und sich darauf auswirkt, wo Daten gespeichert werden.
  • INSTANCE_PARTITION_DESCRIPTION: Der Name, der in der Google Cloud -Konsole für die Instanzpartition angezeigt werden soll. Der Name der Instanzpartition muss innerhalb Ihres Google Cloud -Projekts eindeutig sein.
  • INSTANCE_ID: Die permanente Kennzeichnung Ihrer Spanner-Instanz, in der sich diese Instanzpartition befindet.
  • NODE_COUNT: Die Rechenkapazität der Instanzpartition, ausgedrückt als Anzahl von Knoten. Ein Knoten entspricht 1.000 Verarbeitungseinheiten.
  • PROCESSING_UNIT_COUNT: Die Rechenkapazität der Instanz, ausgedrückt als Anzahl von Verarbeitungseinheiten. Ihre Instanzpartition muss mindestens 1.000 Verarbeitungseinheiten haben. Geben Sie Mengen als Vielfaches von 1.000 (1.000, 2.000, 3.000 usw.) ein.

Wenn Sie beispielsweise eine Instanzpartition europe-partition in eur3 mit 5 Knoten erstellen möchten, führen Sie Folgendes aus:

  gcloud beta spanner instance-partitions create europe-partition --config=eur3 \
    --description="europe-partition" --instance=test-instance --nodes=5

Clientbibliotheken

C++

Informationen zum Installieren und Verwenden der Clientbibliothek für Spanner finden Sie unter Spanner-Clientbibliotheken.

void CreateInstancePartition(
    google::cloud::spanner_admin::InstanceAdminClient client,
    std::string const& project_id, std::string const& instance_id,
    std::string const& instance_partition_id) {
  auto project = google::cloud::Project(project_id);
  auto in = google::cloud::spanner::Instance(project_id, instance_id);
  auto config = project.FullName() + "/instanceConfigs/nam3";

  google::spanner::admin::instance::v1::CreateInstancePartitionRequest request;
  request.set_parent(in.FullName());
  request.set_instance_partition_id(instance_partition_id);
  request.mutable_instance_partition()->set_display_name(
      "Test instance partition");
  request.mutable_instance_partition()->set_node_count(1);
  request.mutable_instance_partition()->set_config(config);

  auto instance_partition = client.CreateInstancePartition(request).get();
  if (!instance_partition) throw std::move(instance_partition).status();
  std::cout << "Created instance partition [" << instance_partition_id << "]:\n"
            << instance_partition->DebugString();
}

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für Spanner finden Sie unter Spanner-Clientbibliotheken.


using Google.Cloud.Spanner.Admin.Instance.V1;
using Google.Cloud.Spanner.Common.V1;
using Google.LongRunning;
using System;

public class CreateInstancePartitionSample
{
    public InstancePartition CreateInstancePartition(string projectId, string instanceId, string instancePartitionId)
    {
        // Create the InstanceAdminClient instance.
        InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create();

        // Initialize request parameters.
        InstancePartition partition = new InstancePartition
        {
            DisplayName = "This is a display name.",
            NodeCount = 1,
            ConfigAsInstanceConfigName = InstanceConfigName.FromProjectInstanceConfig(projectId, "nam3"),
        };
        InstanceName instanceName = InstanceName.FromProjectInstance(projectId, instanceId);

        // Make the CreateInstancePartition request.
        Operation<InstancePartition, CreateInstancePartitionMetadata> response = instanceAdminClient.CreateInstancePartition(instanceName, partition, instancePartitionId);

        Console.WriteLine("Waiting for the operation to finish.");

        // Poll until the returned long-running operation is complete.
        Operation<InstancePartition, CreateInstancePartitionMetadata> completedResponse = response.PollUntilCompleted();

        if (completedResponse.IsFaulted)
        {
            Console.WriteLine($"Error while creating instance partition: {completedResponse.Exception}");
            throw completedResponse.Exception;
        }

        Console.WriteLine($"Instance created successfully.");

        return completedResponse.Result;
    }
}

Go

Informationen zum Installieren und Verwenden der Clientbibliothek für Spanner finden Sie unter Spanner-Clientbibliotheken.

import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
)

// Example of creating an instance partition with Go.
// projectID is the ID of the project that the new instance partition will be in.
// instanceID is the ID of the instance that the new instance partition will be in.
// instancePartitionID is the ID of the new instance partition to be created.
func createInstancePartition(w io.Writer, projectID, instanceID, instancePartitionID string) error {
	// projectID := "my-project-id"
	// instanceID := "my-instance"
	// instancePartitionID := "my-instance-partition"
	ctx := context.Background()
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer instanceAdmin.Close()

	op, err := instanceAdmin.CreateInstancePartition(ctx, &instancepb.CreateInstancePartitionRequest{
		Parent:              fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID),
		InstancePartitionId: instancePartitionID,
		InstancePartition: &instancepb.InstancePartition{
			Config:          fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, "nam3"),
			DisplayName:     "my-instance-partition",
			ComputeCapacity: &instancepb.InstancePartition_NodeCount{NodeCount: 1},
		},
	})
	if err != nil {
		return fmt.Errorf("could not create instance partition %s: %w", fmt.Sprintf("projects/%s/instances/%s/instancePartitions/%s", projectID, instanceID, instancePartitionID), err)
	}
	// Wait for the instance partition creation to finish.
	i, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("waiting for instance partition creation to finish failed: %w", err)
	}
	// The instance partition may not be ready to serve yet.
	if i.State != instancepb.InstancePartition_READY {
		fmt.Fprintf(w, "instance partition state is not READY yet. Got state %v\n", i.State)
	}
	fmt.Fprintf(w, "Created instance partition [%s]\n", instancePartitionID)
	return nil
}

Java

Informationen zum Installieren und Verwenden der Clientbibliothek für Spanner finden Sie unter Spanner-Clientbibliotheken.


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.CreateInstancePartitionRequest;
import com.google.spanner.admin.instance.v1.InstanceConfigName;
import com.google.spanner.admin.instance.v1.InstanceName;
import com.google.spanner.admin.instance.v1.InstancePartition;
import java.util.concurrent.ExecutionException;

class CreateInstancePartitionSample {

  static void createInstancePartition() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    String instancePartitionId = "my-instance-partition";
    createInstancePartition(projectId, instanceId, instancePartitionId);
  }

  static void createInstancePartition(
      String projectId, String instanceId, String instancePartitionId) {
    // Set instance partition configuration.
    int nodeCount = 1;
    String displayName = "Descriptive name";

    // Create an InstancePartition object that will be used to create the instance partition.
    InstancePartition instancePartition =
        InstancePartition.newBuilder()
            .setDisplayName(displayName)
            .setNodeCount(nodeCount)
            .setConfig(InstanceConfigName.of(projectId, "nam3").toString())
            .build();

    try (Spanner spanner =
            SpannerOptions.newBuilder().setProjectId(projectId).build().getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {

      // Wait for the createInstancePartition operation to finish.
      InstancePartition createdInstancePartition =
          instanceAdminClient
              .createInstancePartitionAsync(
                  CreateInstancePartitionRequest.newBuilder()
                      .setParent(InstanceName.of(projectId, instanceId).toString())
                      .setInstancePartitionId(instancePartitionId)
                      .setInstancePartition(instancePartition)
                      .build())
              .get();
      System.out.printf(
          "Instance partition %s was successfully created%n", createdInstancePartition.getName());
    } catch (ExecutionException e) {
      System.out.printf(
          "Error: Creating instance partition %s failed with error message %s%n",
          instancePartition.getName(), e.getMessage());
    } catch (InterruptedException e) {
      System.out.println(
          "Error: Waiting for createInstancePartition operation to finish was interrupted");
    }
  }
}

Node.js

Informationen zum Installieren und Verwenden der Clientbibliothek für Spanner finden Sie unter Spanner-Clientbibliotheken.

// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const instancePartitionId = 'my-instance-partition';

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

// Get the instance admin client
const instanceAdminClient = spanner.getInstanceAdminClient();

// Creates a new instance partition
try {
  console.log(
    `Creating instance partition ${instanceAdminClient.instancePartitionPath(
      projectId,
      instanceId,
      instancePartitionId,
    )}.`,
  );
  const [operation] = await instanceAdminClient.createInstancePartition({
    instancePartitionId: instancePartitionId,
    parent: instanceAdminClient.instancePath(projectId, instanceId),
    instancePartition: {
      config: instanceAdminClient.instanceConfigPath(projectId, 'nam3'),
      nodeCount: 1,
      displayName: 'Test instance partition',
    },
  });

  console.log(
    `Waiting for operation on ${instancePartitionId} to complete...`,
  );
  await operation.promise();

  console.log(`Created instance partition ${instancePartitionId}.`);
} catch (err) {
  console.error('ERROR:', err);
}

PHP

Informationen zum Installieren und Verwenden der Clientbibliothek für Spanner finden Sie unter Spanner-Clientbibliotheken.

use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;
use Google\Cloud\Spanner\Admin\Instance\V1\CreateInstancePartitionRequest;
use Google\Cloud\Spanner\Admin\Instance\V1\InstancePartition;

/**
 * Creates an instance partition.
 * Example:
 * ```
 * create_instance_partition($projectId, $instanceId, $instancePartitionId);
 * ```
 *
 * @param string $projectId The Google Cloud project ID.
 * @param string $instanceId The Spanner instance ID.
 * @param string $instancePartitionId The instance partition ID.
 */
function create_instance_partition(string $projectId, string $instanceId, string $instancePartitionId): void
{
    $instanceAdminClient = new InstanceAdminClient();

    $instanceName = $instanceAdminClient->instanceName($projectId, $instanceId);
    $instancePartitionName = $instanceAdminClient->instancePartitionName($projectId, $instanceId, $instancePartitionId);
    $configName = $instanceAdminClient->instanceConfigName($projectId, 'nam3');

    $instancePartition = (new InstancePartition())
        ->setConfig($configName)
        ->setDisplayName('Test instance partition.')
        ->setNodeCount(1);

    $operation = $instanceAdminClient->createInstancePartition(
        (new CreateInstancePartitionRequest())
        ->setParent($instanceName)
        ->setInstancePartitionId($instancePartitionId)
        ->setInstancePartition($instancePartition)
    );

    print('Waiting for operation to complete...' . PHP_EOL);
    $operation->pollUntilComplete();

    printf('Created instance partition %s' . PHP_EOL, $instancePartitionId);
}

Python

Informationen zum Installieren und Verwenden der Clientbibliothek für Spanner finden Sie unter Spanner-Clientbibliotheken.

def create_instance_partition(instance_id, instance_partition_id):
    """Creates an instance partition."""
    from google.cloud.spanner_admin_instance_v1.types import spanner_instance_admin

    spanner_client = spanner.Client()
    instance_admin_api = spanner_client.instance_admin_api

    config_name = "{}/instanceConfigs/nam3".format(spanner_client.project_name)

    operation = spanner_client.instance_admin_api.create_instance_partition(
        parent=instance_admin_api.instance_path(spanner_client.project, instance_id),
        instance_partition_id=instance_partition_id,
        instance_partition=spanner_instance_admin.InstancePartition(
            config=config_name,
            display_name="Test instance partition",
            node_count=1,
        ),
    )

    print("Waiting for operation to complete...")
    operation.result(OPERATION_TIMEOUT_SECONDS)

    print("Created instance partition {}".format(instance_partition_id))

Instanzpartition beschreiben

gcloud

Verwenden Sie gcloud beta spanner instance-partitions describe, um eine Instanzpartition zu beschreiben.

gcloud beta spanner instance-partitions describe PARTITION_ID \
  --instance=INSTANCE_ID

Ersetzen Sie Folgendes:

  • INSTANCE_PARTITION_ID: Die permanente Kennzeichnung der Instanzpartition.
  • INSTANCE_ID: Die permanente Kennzeichnung der Instanz.

Wenn Sie beispielsweise die Instanzpartition europe-partition beschreiben möchten, führen Sie Folgendes aus:

  gcloud beta spanner instance-partitions describe europe-partition
    --instance=test-instance

Instanzpartitionen auflisten

Console

  1. Öffnen Sie in der Google Cloud Console die Seite Spanner.

    Spanner aufrufen

  2. Wählen Sie eine Instanz aus der Liste aus.

  3. Wählen Sie im Navigationsmenü Instanzpartitionen aus.

    Es wird eine Liste der mit dieser Instanz verknüpften Instanzpartitionen angezeigt.

gcloud

Verwenden Sie gcloud beta spanner instance-partitions list, um Ihre Instanzpartitionen aufzulisten.

gcloud beta spanner instance-partitions list --instance=INSTANCE_ID

Die gcloud CLI gibt eine Liste Ihrer Spanner-Instanzpartitionen zusammen mit der ID, dem Anzeigenamen, der Konfiguration und der Rechenkapazität jeder Instanzpartition aus.

Instanzpartition bearbeiten

Im folgenden Abschnitt wird erläutert, wie Sie die Rechenkapazität Ihrer Instanzpartition ändern. Sie können die Instanzpartitions-ID, den Namen oder die Konfiguration nicht ändern.

Rechenkapazität ändern

Sie müssen genügend Rechenkapazität bereitstellen, um die CPU-Auslastung und die Speicherauslastung unter den empfohlenen Maximalwerten zu halten. Weitere Informationen finden Sie unter Kontingente und Limits für Spanner.

Wenn Sie die Rechenkapazität einer Instanzpartition erhöhen möchten, muss dasGoogle Cloud -Projekt ein ausreichendes Kontingent zum Hinzufügen der Rechenkapazität haben. Die Dauer der Bearbeitung des Antrags auf Erhöhung hängt von der Größe des Antrags ab. In den meisten Fällen werden Anfragen innerhalb weniger Minuten bearbeitet. In seltenen Fällen kann es bis zu einer Stunde dauern, bis eine Skalierung abgeschlossen ist.

Console

  1. Öffnen Sie in der Google Cloud Console die Seite Spanner.

    Spanner aufrufen

  2. Wählen Sie eine Instanz aus der Liste aus.

  3. Wählen Sie im Navigationsmenü Instanzpartitionen aus.

  4. Klicken Sie in der Liste der Instanzpartitionen in der Spalte Aktionen auf Weitere Aktionen und wählen Sie Bearbeiten aus.

  5. Ändern Sie die Rechenkapazität, indem Sie eine Maßeinheit (Verarbeitungseinheiten oder Knoten) auswählen und dann eine Menge eingeben. Wenn Sie Verarbeitungseinheiten verwenden, geben Sie Mengen als Vielfaches von 1.000 (1.000, 2.000, 3.000 usw.) ein. Jeder Knoten entspricht 1.000 Verarbeitungseinheiten.

    Ihre Instanzpartition muss mindestens einen Knoten (1.000 Verarbeitungseinheiten) haben.

  6. Klicken Sie auf Speichern.

    Wenn in einem Dialogfeld angezeigt wird, dass Sie kein ausreichendes Kontingent haben, um Rechenkapazität hinzuzufügen, folgen Sie der Anleitung, um ein höheres Kontingent anzufordern.

gcloud

Verwenden Sie gcloud beta spanner instance-partitions update, um die Rechenkapazität Ihrer Instanzpartition zu ändern. Geben Sie bei Verwendung dieses Befehls die Rechenkapazität als Anzahl von Knoten oder Verarbeitungseinheiten an.

gcloud beta spanner instance-partitions update INSTANCE_PARTITION_ID \
  --instance=INSTANCE_ID \
  [--nodes=NODE_COUNT | --processing-units=PROCESSING_UNIT_COUNT]
  [--async]

Ersetzen Sie Folgendes:

  • INSTANCE_PARTITION_ID: Die permanente Kennzeichnung der Instanzpartition.
  • INSTANCE_ID: Die permanente Kennzeichnung der Instanz.
  • NODE_COUNT: Die neue Rechenkapazität der Instanzpartition, ausgedrückt als Anzahl von Knoten. Ein Knoten entspricht 1.000 Verarbeitungseinheiten.
  • PROCESSING_UNIT_COUNT: Die neue Rechenkapazität der Instanzpartition, ausgedrückt als Anzahl von Verarbeitungseinheiten. Ihre Instanzpartition muss mindestens 1.000 Verarbeitungseinheiten haben. Geben Sie Mengen als Vielfaches von 1.000 (1.000, 2.000, 3.000 usw.) ein.

Optionale Flags:

  • --async: Verwenden Sie dieses Flag, wenn Ihre Anfrage sofort zurückgegeben werden soll, ohne auf den Abschluss des Vorgangs zu warten.

Sie können den Status Ihrer Anfrage prüfen, indem Sie gcloud spanner operations describe ausführen.

Instanzpartition löschen

Sie können eine Instanzpartition nicht löschen, solange sie mit Platzierungen oder Daten verknüpft ist. Sie müssen zuerst alle Daten in der Instanzpartition verschieben oder die Placement-Tabellen löschen, in denen die Instanzpartition verwendet wird, bevor Sie die Instanzpartition löschen können.

Console

  1. Öffnen Sie in der Google Cloud Console die Seite Spanner.

    Spanner aufrufen

  2. Wählen Sie eine Instanz aus der Liste aus.

  3. Wählen Sie im Navigationsmenü Instanzpartitionen aus.

  4. Klicken Sie in der Liste der Instanzpartitionen in der Spalte Aktionen auf Weitere Aktionen und wählen Sie Löschen aus.

  5. Folgen Sie der Anleitung, um zu bestätigen, dass Sie die Instanzpartition löschen möchten.

  6. Klicken Sie auf Löschen.

gcloud

Führen Sie den Befehl gcloud beta spanner instance-partitions delete aus.

gcloud beta spanner instance-partitions delete INSTANCE_PARTITION_ID
  --instance=INSTANCE_ID

Nächste Schritte