Datensätze erstellen und verwalten

Auf dieser Seite wird beschrieben, wie Sie Datasets erstellen, bearbeiten, anzeigen, auflisten und löschen. Nachdem Sie ein Dataset erstellt haben, können Sie Datenspeicher erstellen, die elektronische Gesundheitsdaten und medizinische Bildgebungsdaten enthalten, das Dataset de-identifizieren und vieles mehr.

Hinweise

Weitere Informationen finden Sie unter Datenmodell der Cloud Healthcare API.

Dataset erstellen

Die folgenden Beispiele zeigen, wie Sie ein Dataset erstellen können.

Console

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

    Browser aufrufen

  2. Klicken Sie auf Dataset erstellen. Die Seite Dataset-Attribute wird angezeigt.

  3. Geben Sie im Feld Name eine Kennzeichnung für das Dataset ein. Beachten Sie dabei die zulässigen Zeichen und Größenanforderungen für das Dataset.

  4. Wählen Sie einen der folgenden Standorttypen aus:

    • Region Das Dataset ist dauerhaft in einer Google Cloud-Region gespeichert. Nachdem Sie diese Option ausgewählt haben, geben Sie einen Standort in das Feld Region ein oder wählen Sie einen aus.

    • Mehrere Regionen. Das Dataset ist dauerhaft an einem Standort gespeichert, der sich über mehrere Google Cloud-Regionen erstreckt. Nachdem Sie diese Option ausgewählt haben, geben Sie im Feld Mehrere Regionen einen Standort mit mehreren Regionen ein oder wählen Sie einen aus.

  5. Klicken Sie auf Erstellen. Die Seite Browser wird angezeigt. Das neue Dataset wird in der Liste der Datasets angezeigt.

gcloud

Führen Sie den Befehl gcloud healthcare datasets create aus.

Bevor Sie die folgenden Befehlsdaten verwenden, ersetzen Sie die folgenden Werte:

Führen Sie den folgenden Befehl aus:

Linux, macOS oder Cloud Shell

gcloud healthcare datasets create DATASET_ID \
  --location=LOCATION

Windows (PowerShell)

gcloud healthcare datasets create DATASET_ID `
  --location=LOCATION

Windows (cmd.exe)

gcloud healthcare datasets create DATASET_ID ^
  --location=LOCATION

Sie sollten eine Antwort ähnlich der folgenden erhalten:

Create request issued for: [DATASET_ID]
Created dataset [DATASET_ID].

REST

Verwenden Sie die Methode projects.locations.datasets.create.

  1. Erstellen Sie das Dataset.

    Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

    Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

    curl

    Führen Sie folgenden Befehl aus:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d "" \
    "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets?datasetId=DATASET_ID"

    PowerShell

    Führen Sie folgenden Befehl aus:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets?datasetId=DATASET_ID" | Select-Object -Expand Content

    APIs Explorer

    Öffnen Sie die Methodenreferenzseite. Der API Explorer wird rechts auf der Seite geöffnet. Sie können mit diesem Tool interagieren, um Anfragen zu senden. Füllen Sie die Pflichtfelder aus und klicken Sie auf Ausführen.

    Die Ausgabe sieht so aus. Die Antwort enthält eine Kennung für einen Vorgang mit langer Ausführungszeit. Lang andauernde Vorgänge werden zurückgegeben, wenn die Ausführung von Methodenaufrufen zusätzliche Zeit in Anspruch nehmen kann. Notieren Sie sich den Wert von OPERATION_ID. Sie benötigen diesen Wert im nächsten Schritt.

  2. Mit der Methode projects.locations.datasets.operations.get können Sie den Status des Vorgangs mit langer Ausführungszeit abrufen.

    Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

    • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
    • LOCATION ist der Standort des Datasets
    • DATASET_ID ist die ID des zu erstellenden Datasets
    • OPERATION_ID ist die ID des Vorgangs mit langer Ausführungszeit

    Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

    curl

    Führen Sie folgenden Befehl aus:

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/operations/OPERATION_ID"

    PowerShell

    Führen Sie folgenden Befehl aus:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method GET `
    -Headers $headers `
    -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/operations/OPERATION_ID" | Select-Object -Expand Content

    APIs Explorer

    Öffnen Sie die Methodenreferenzseite. Der API Explorer wird rechts auf der Seite geöffnet. Sie können mit diesem Tool interagieren, um Anfragen zu senden. Füllen Sie die Pflichtfelder aus und klicken Sie auf Ausführen.

    Die Ausgabe sieht so aus. Die Antwort enthält "done": true; dies bedeutet, dass das Dataset erfolgreich erstellt wurde.

Go

import (
	"context"
	"fmt"
	"io"
	"time"

	healthcare "google.golang.org/api/healthcare/v1"
)

// createDataset creates a dataset.
func createDataset(w io.Writer, projectID, location, datasetID string) error {
	// Set a deadline for the dataset to become initialized.
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %w", err)
	}

	datasetsService := healthcareService.Projects.Locations.Datasets

	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, location)

	resp, err := datasetsService.Create(parent, &healthcare.Dataset{}).DatasetId(datasetID).Context(ctx).Do()
	if err != nil {
		return fmt.Errorf("Create: %w", err)
	}

	// The dataset is not always ready to use immediately, instead a long-running operation is returned.
	// This is how you might poll the operation to ensure the dataset is fully initialized before proceeding.
	// Initialization usually takes less than a minute.
	for !resp.Done {
		time.Sleep(15 * time.Second)
		resp, err = datasetsService.Operations.Get(resp.Name).Context(ctx).Do()
		if err != nil {
			return fmt.Errorf("Operations.Get(%s): %w", resp.Name, err)
		}
	}

	fmt.Fprintf(w, "Created dataset: %q\n", resp.Name)
	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Dataset;
import com.google.api.services.healthcare.v1.model.Operation;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

public class DatasetCreate {
  private static final String DATASET_NAME = "projects/%s/locations/%s/datasets/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void datasetCreate(String projectId, String regionId, String datasetId)
      throws IOException {
    // String projectId = "your-project-id";
    // String regionId = "us-central1";
    // String datasetId = "your-dataset-id";

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Configure the dataset to be created.
    Dataset dataset = new Dataset();
    dataset.setTimeZone("America/Chicago");

    // Create request and configure any parameters.
    String parentName = String.format("projects/%s/locations/%s", projectId, regionId);
    Datasets.Create request = client.projects().locations().datasets().create(parentName, dataset);
    request.setDatasetId(datasetId);

    // Execute the request, wait for the operation to complete, and process the results.
    try {
      Operation operation = request.execute();
      System.out.println(operation.toPrettyString());
      while (operation.getDone() == null || !operation.getDone()) {
        // Update the status of the operation with another request.
        Thread.sleep(500); // Pause for 500ms between requests.
        operation =
            client
                .projects()
                .locations()
                .datasets()
                .operations()
                .get(operation.getName())
                .execute();
      }
      System.out.println("Dataset created. Response content: " + operation.getResponse());
    } catch (Exception ex) {
      System.out.printf("Error during request execution: %s\n", ex.toString());
      ex.printStackTrace(System.out);
    }
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const createDataset = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  const parent = `projects/${projectId}/locations/${cloudRegion}`;
  const request = {parent, datasetId};

  await healthcare.projects.locations.datasets.create(request);
  console.log(`Created dataset: ${datasetId}`);
};

createDataset();

Python

# Imports the Dict type for runtime type hints.
from typing import Dict

def create_dataset(project_id: str, location: str, dataset_id: str) -> Dict[str, str]:
    """Creates a Cloud Healthcare API dataset.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/datasets
    before running the sample.
    See
    https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.html#create
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Google Cloud project you want
          to use.
      location: The name of the dataset's location.
      dataset_id: The ID of the dataset to create.

    Returns:
      A dictionary representing a long-running operation that results from
      calling the 'CreateDataset' method. Dataset creation is typically fast.
    """
    # Imports the Python built-in time module.
    import time

    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    # Imports HttpError from the Google Python API client errors module.
    from googleapiclient.errors import HttpError

    api_version = "v1"
    service_name = "healthcare"
    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    dataset_parent = f"projects/{project_id}/locations/{location}"

    request = (
        client.projects()
        .locations()
        .datasets()
        .create(parent=dataset_parent, body={}, datasetId=dataset_id)
    )

    # Wait for operation to complete.
    start_time = time.time()
    max_time = 600  # 10 minutes, but dataset creation is typically only a few seconds.

    try:
        operation = request.execute()
        while not operation.get("done", False):
            # Poll until the operation finishes.
            print("Waiting for operation to finish...")
            if time.time() - start_time > max_time:
                raise TimeoutError("Timed out waiting for operation to finish.")
            operation = (
                client.projects()
                .locations()
                .datasets()
                .operations()
                .get(name=operation["name"])
                .execute()
            )
            # Wait 5 seconds between each poll to the operation.
            time.sleep(5)

        if "error" in operation:
            raise RuntimeError(f"Create dataset operation failed: {operation['error']}")
        else:
            dataset_name = operation["response"]["name"]
            print(f"Created dataset: {dataset_name}")
            return operation

    except HttpError as err:
        # A common error is when the dataset already exists.
        if err.resp.status == 409:
            print(f"Dataset with ID {dataset_id} already exists.")
            return
        else:
            raise err

Dataset bearbeiten

Die folgenden Beispiele zeigen, wie Sie ein Dataset bearbeiten können.

Console

Die Google Cloud Console unterstützt das Bearbeiten von Datasets nicht. Verwenden Sie stattdessen die Google Cloud CLI oder die REST API.

gcloud

Führen Sie den Befehl gcloud healthcare datasets update aus.

Bevor Sie die folgenden Befehlsdaten verwenden, ersetzen Sie die folgenden Werte:

  • LOCATION ist der Standort des Datasets
  • DATASET_ID ist die Dataset-ID
  • TIME_ZONE ist eine unterstützte Zeitzone, z. B. UTC

Führen Sie den folgenden Befehl aus:

Linux, macOS oder Cloud Shell

gcloud healthcare datasets update DATASET_ID \
  --location=LOCATION \
  --time-zone=TIME_ZONE

Windows (PowerShell)

gcloud healthcare datasets update DATASET_ID `
  --location=LOCATION `
  --time-zone=TIME_ZONE

Windows (cmd.exe)

gcloud healthcare datasets update DATASET_ID ^
  --location=LOCATION ^
  --time-zone=TIME_ZONE

Sie sollten eine Antwort ähnlich der folgenden erhalten:

Updated dataset [DATASET_ID].
name: projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID
timeZone: TIME_ZONE

REST

Verwenden Sie die Methode projects.locations.datasets.patch.

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID ist die Dataset-ID
  • TIME_ZONE ist eine unterstützte Zeitzone, z. B. UTC

JSON-Text anfordern:

{
  "timeZone": "TIME_ZONE"
}

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json und führen Sie den folgenden Befehl aus:

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID?updateMask=timeZone"

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json und führen Sie den folgenden Befehl aus:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method PATCH `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID?updateMask=timeZone" | Select-Object -Expand Content

APIs Explorer

Kopieren Sie den Anfragetext und öffnen Sie die Referenzseite für Methoden. Der API Explorer wird rechts auf der Seite geöffnet. Sie können mit diesem Tool interagieren, um Anfragen zu senden. Fügen Sie den Anfragetext in dieses Tool ein, füllen Sie alle Pflichtfelder aus und klicken Sie auf Ausführen.

Sie sollten in etwa folgende JSON-Antwort erhalten:

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1"
)

// patchDataset updates (patches) a dataset by updating its timezone..
func patchDataset(w io.Writer, projectID, location, datasetID, newTimeZone string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %w", err)
	}

	datasetsService := healthcareService.Projects.Locations.Datasets

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID)

	if _, err := datasetsService.Patch(name, &healthcare.Dataset{
		TimeZone: newTimeZone,
	}).UpdateMask("timeZone").Do(); err != nil {
		return fmt.Errorf("Patch: %w", err)
	}

	fmt.Fprintf(w, "Patched dataset %s with timeZone %s\n", datasetID, newTimeZone)

	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Dataset;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

public class DatasetPatch {
  private static final String DATASET_NAME = "projects/%s/locations/%s/datasets/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void datasetPatch(String datasetName) throws IOException {
    // String datasetName =
    //     String.format(DATASET_NAME, "your-project-id", "your-region-id", "your-dataset-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Fetch the initial state of the dataset.
    Datasets.Get getRequest = client.projects().locations().datasets().get(datasetName);
    Dataset dataset = getRequest.execute();

    // Update the Dataset fields as needed as needed. For a full list of dataset fields, see:
    // https://cloud.google.com/healthcare/docs/reference/rest/v1beta1/projects.locations.datasets#Dataset
    dataset.setTimeZone("America/New_York");

    // Create request and configure any parameters.
    Datasets.Patch request =
        client
            .projects()
            .locations()
            .datasets()
            .patch(datasetName, dataset)
            .setUpdateMask("timeZone");

    // Execute the request and process the results.
    dataset = request.execute();
    System.out.println("Dataset patched: \n" + dataset.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const patchDataset = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const timeZone = 'UTC';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}`;
  const request = {
    name,
    updateMask: 'timeZone',
    resource: {timeZone: timeZone},
  };

  await healthcare.projects.locations.datasets.patch(request);
  console.log(`Dataset ${datasetId} patched with time zone ${timeZone}`);
};

patchDataset();

Python

# Imports the Dict type for runtime type hints.
from typing import Dict

def patch_dataset(
    project_id: str, location: str, dataset_id: str, time_zone: str
) -> Dict[str, str]:
    """Updates dataset metadata.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/datasets
    before running the sample.
    See https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.html#patch
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Google Cloud project you want
          to use.
      location: The name of the dataset's location.
      dataset_id: The ID of the dataset to patch.
      time_zone: The default timezone used by the dataset.

    Returns:
      A dictionary representing the patched Dataset resource.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    # Imports HttpError from the Google Python API client errors module.
    from googleapiclient.errors import HttpError

    api_version = "v1"
    service_name = "healthcare"
    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    # time_zone = 'GMT'
    dataset_parent = f"projects/{project_id}/locations/{location}"
    dataset_name = f"{dataset_parent}/datasets/{dataset_id}"

    # Sets the time zone
    patch = {"timeZone": time_zone}

    request = (
        client.projects()
        .locations()
        .datasets()
        .patch(name=dataset_name, updateMask="timeZone", body=patch)
    )

    try:
        response = request.execute()
        print(f"Patched dataset {dataset_id} with time zone: {time_zone}")
        return response
    except HttpError as err:
        raise err

Ruft Dataset-Details ab

Die folgenden Beispiele zeigen, wie Sie Details zu einem Dataset abrufen können.

Console

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

    Browser aufrufen

  2. Wählen Sie das Dataset aus. Die Seite Dataset und die Datenspeicher im Dataset werden angezeigt.

gcloud

Führen Sie den Befehl gcloud healthcare datasets describe aus.

Bevor Sie die folgenden Befehlsdaten verwenden, ersetzen Sie die folgenden Werte:

  • LOCATION ist der Standort des Datasets
  • DATASET_ID ist die Dataset-ID

Führen Sie den folgenden Befehl aus:

Linux, macOS oder Cloud Shell

gcloud healthcare datasets describe DATASET_ID \
  --location=LOCATION

Windows (PowerShell)

gcloud healthcare datasets describe DATASET_ID `
  --location=LOCATION

Windows (cmd.exe)

gcloud healthcare datasets describe DATASET_ID ^
  --location=LOCATION

Sie sollten eine Antwort ähnlich der folgenden erhalten:

name: projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID
timeZone: TIME_ZONE

REST

Verwenden Sie die Methode projects.locations.datasets.get.

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID ist die Dataset-ID

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Führen Sie folgenden Befehl aus:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID"

PowerShell

Führen Sie folgenden Befehl aus:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID" | Select-Object -Expand Content

APIs Explorer

Öffnen Sie die Methodenreferenzseite. Der API Explorer wird rechts auf der Seite geöffnet. Sie können mit diesem Tool interagieren, um Anfragen zu senden. Füllen Sie die Pflichtfelder aus und klicken Sie auf Ausführen.

Sie sollten in etwa folgende JSON-Antwort erhalten:

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1"
)

// getDataset gets a dataset.
func getDataset(w io.Writer, projectID, location, datasetID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %w", err)
	}

	datasetsService := healthcareService.Projects.Locations.Datasets

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID)

	resp, err := datasetsService.Get(name).Do()
	if err != nil {
		return fmt.Errorf("Get: %w", err)
	}

	fmt.Fprintf(w, "Name: %s\n", resp.Name)
	fmt.Fprintf(w, "Time zone: %s\n", resp.TimeZone)

	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Dataset;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

public class DatasetGet {
  private static final String DATASET_NAME = "projects/%s/locations/%s/datasets/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void datasetGet(String datasetName) throws IOException {
    // String datasetName =
    //     String.format(DATASET_NAME, "your-project-id", "your-region-id", "your-dataset-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Create request and configure any parameters.
    Datasets.Get request = client.projects().locations().datasets().get(datasetName);

    // Execute the request and process the results.
    Dataset dataset = request.execute();
    System.out.println("Dataset retrieved: \n" + dataset.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const getDataset = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}`;
  const request = {name: parent};

  const dataset = await healthcare.projects.locations.datasets.get(request);
  console.log(dataset.data);
};

getDataset();

Python

# Imports the Dict type for runtime type hints.
from typing import Dict

def get_dataset(project_id: str, location: str, dataset_id: str) -> Dict[str, str]:
    """Gets any metadata associated with a dataset.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/datasets
    before running the sample.
    See https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.html#get
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Google Cloud project you want
          to use.
      location: The name of the dataset's location.
      dataset_id: The name of the dataset to get.

    Returns:
      A dictionary representing a Dataset resource.
    """
    # Imports HttpError from the Google Python API client errors module.
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery
    from googleapiclient.errors import HttpError

    api_version = "v1"
    service_name = "healthcare"
    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    dataset_name = f"projects/{project_id}/locations/{location}/datasets/{dataset_id}"

    request = client.projects().locations().datasets()

    try:
        dataset = request.get(name=dataset_name).execute()
        print(f"Name: {dataset.get('name')}")
        return dataset
    except HttpError as err:
        raise err

Datasets auflisten

Die folgenden Beispiele zeigen, wie Sie die Datasets in Ihrem Projekt auflisten können.

Console

Rufen Sie in der Google Cloud Console die Seite Browser auf.

Browser aufrufen

gcloud

Führen Sie den Befehl gcloud healthcare datasets list aus.

Bevor Sie die folgenden Befehlsdaten verwenden, ersetzen Sie die folgenden Werte:

  • LOCATION ist der Standort des Datasets

Führen Sie den folgenden Befehl aus:

Linux, macOS oder Cloud Shell

gcloud healthcare datasets list --location=LOCATION

Windows (PowerShell)

gcloud healthcare datasets list --location=LOCATION

Windows (cmd.exe)

gcloud healthcare datasets list --location=LOCATION

Sie sollten eine Antwort ähnlich der folgenden erhalten:

ID           LOCATION     TIMEZONE
DATASET_ID   LOCATION       TIME_ZONE

REST

Verwenden Sie die Methode projects.locations.datasets.list.

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Führen Sie folgenden Befehl aus:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets"

PowerShell

Führen Sie folgenden Befehl aus:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets" | Select-Object -Expand Content

APIs Explorer

Öffnen Sie die Methodenreferenzseite. Der API Explorer wird rechts auf der Seite geöffnet. Sie können mit diesem Tool interagieren, um Anfragen zu senden. Füllen Sie die Pflichtfelder aus und klicken Sie auf Ausführen.

Sie sollten in etwa folgende JSON-Antwort erhalten:

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1"
)

// listDatasets prints a list of datasets to w.
func listDatasets(w io.Writer, projectID string, location string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %w", err)
	}

	datasetsService := healthcareService.Projects.Locations.Datasets

	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, location)

	resp, err := datasetsService.List(parent).Do()
	if err != nil {
		return fmt.Errorf("List: %w", err)
	}

	fmt.Fprintln(w, "Datasets:")
	for _, d := range resp.Datasets {
		fmt.Fprintln(w, d.Name)
	}

	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Dataset;
import com.google.api.services.healthcare.v1.model.ListDatasetsResponse;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DatasetList {
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void datasetList(String projectId, String regionId) throws IOException {
    // String projectId = "your-project-id";
    // String regionId = "us-central1";

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Results are paginated, so multiple queries may be required.
    String parentName = String.format("projects/%s/locations/%s", projectId, regionId);
    String pageToken = null;
    List<Dataset> datasets = new ArrayList<>();
    do {
      // Create request and configure any parameters.
      Datasets.List request =
          client
              .projects()
              .locations()
              .datasets()
              .list(parentName)
              .setPageSize(100) // Specify pageSize up to 1000
              .setPageToken(pageToken);

      // Execute response and collect results.
      ListDatasetsResponse response = request.execute();
      datasets.addAll(response.getDatasets());

      // Update the page token for the next request.
      pageToken = response.getNextPageToken();
    } while (pageToken != null);

    // Print results.
    System.out.printf("Retrieved %s datasets: \n", datasets.size());
    for (Dataset data : datasets) {
      System.out.println("\t" + data.toPrettyString());
    }
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const listDatasets = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  const parent = `projects/${projectId}/locations/${cloudRegion}`;
  const request = {parent};

  const dataset = await healthcare.projects.locations.datasets.list(request);
  console.log(dataset.data);
};

listDatasets();

Python

# Imports the Dict and List types for runtime type hints.
from typing import Dict, List

def list_datasets(project_id: str, location: str) -> List[Dict[str, str]]:
    """Lists the datasets in the project.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/datasets
    before running the sample.
    See https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.html#list
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Google Cloud project you want
          to use.
      location: The name of the location where the datasets are located.

    Returns:
      A list of Dataset resources.
    """
    # Imports HttpError from the Google Python API client errors module.
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery
    from googleapiclient.errors import HttpError

    api_version = "v1"
    service_name = "healthcare"
    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    dataset_parent = f"projects/{project_id}/locations/{location}"

    datasets = []
    request = client.projects().locations().datasets().list(parent=dataset_parent)
    while request is not None:
        try:
            response = request.execute()
            if response and "datasets" in response:
                datasets.extend(response["datasets"])
            # Paginate over results until the list_next() function returns None.
            request = (
                client.projects()
                .locations()
                .datasets()
                .list_next(previous_request=request, previous_response=response)
            )

            for dataset in datasets:
                print(
                    f"Dataset: {dataset.get('name')}\nTime zone: {dataset.get('timeZone')}"
                )

            return datasets

        except HttpError as err:
            raise err

Dataset löschen

Die folgenden Beispiele zeigen, wie Sie ein Dataset löschen können.

Console

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

    Browser aufrufen

  2. Klicken Sie in derselben Zeile wie das Dataset auf die Option Aktionen und wählen Sie dann Löschen aus.

  3. Geben Sie im Bestätigungsdialogfeld die Dataset-ID ein und klicken Sie auf Löschen.

gcloud

Führen Sie den Befehl gcloud healthcare datasets delete aus.

Bevor Sie die folgenden Befehlsdaten verwenden, ersetzen Sie die folgenden Werte:

  • LOCATION ist der Standort des Datasets
  • DATASET_ID ist die Dataset-ID

Führen Sie den folgenden Befehl aus:

Linux, macOS oder Cloud Shell

gcloud healthcare datasets delete DATASET_ID \
  --location=LOCATION

Windows (PowerShell)

gcloud healthcare datasets delete DATASET_ID `
  --location=LOCATION

Windows (cmd.exe)

gcloud healthcare datasets delete DATASET_ID ^
  --location=LOCATION

Geben Sie zur Bestätigung Y ein.

Die Ausgabe sieht so aus:

Deleted dataset [DATASET_ID]

REST

Verwenden Sie die Methode projects.locations.datasets.delete.

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID ist die Dataset-ID

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Führen Sie folgenden Befehl aus:

curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID"

PowerShell

Führen Sie folgenden Befehl aus:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID" | Select-Object -Expand Content

APIs Explorer

Öffnen Sie die Methodenreferenzseite. Der API Explorer wird rechts auf der Seite geöffnet. Sie können mit diesem Tool interagieren, um Anfragen zu senden. Füllen Sie die erforderlichen Felder aus und klicken Sie auf Ausführen.

Sie sollten einen erfolgreichen Statuscode (2xx) und eine leere Antwort als Ausgabe erhalten.

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1"
)

// deleteDataset deletes the given dataset.
func deleteDataset(w io.Writer, projectID, location, datasetID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %w", err)
	}

	datasetsService := healthcareService.Projects.Locations.Datasets

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID)
	if _, err := datasetsService.Delete(name).Do(); err != nil {
		return fmt.Errorf("Delete: %w", err)
	}

	fmt.Fprintf(w, "Deleted dataset: %q\n", name)
	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

public class DatasetDelete {
  private static final String DATASET_NAME = "projects/%s/locations/%s/datasets/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void datasetDelete(String datasetName) throws IOException {
    // String datasetName =
    //     String.format(DATASET_NAME, "your-project-id", "your-region-id", "your-dataset-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Create request and configure any parameters.
    Datasets.Delete request = client.projects().locations().datasets().delete(datasetName);

    // Execute the request and process the results.
    request.execute();
    System.out.println("Dataset deleted.");
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const deleteDataset = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}`;
  const request = {name: parent};

  await healthcare.projects.locations.datasets.delete(request);
  console.log(`Deleted dataset: ${datasetId}`);
};

deleteDataset();

Python

def delete_dataset(project_id: str, location: str, dataset_id: str) -> None:
    """Deletes a dataset.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/datasets
    before running the sample.
    See https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.html#delete
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Google Cloud project you want
          to use.
      location: The name of the dataset's location.
      dataset_id: The name of the dataset to delete.

    Returns:
      An empty response body.
    """
    # Imports HttpError from the Google Python API client errors module.
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery
    from googleapiclient.errors import HttpError

    api_version = "v1"
    service_name = "healthcare"
    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    dataset_name = f"projects/{project_id}/locations/{location}/datasets/{dataset_id}"

    request = client.projects().locations().datasets().delete(name=dataset_name)

    try:
        request.execute()
        print(f"Deleted dataset: {dataset_id}")
    except HttpError as err:
        raise err

Nächste Schritte