Creazione e gestione dei set di dati

Questa pagina descrive come creare, modificare, visualizzare, elencare ed eliminare i set di dati. Dopo aver creato un set di dati, puoi creare datastore che contengono cartelle cliniche elettroniche e dati di diagnostica per immagini, anonimizza il set di dati e altro ancora.

Prima di iniziare

Consulta il modello dei dati dell'API Cloud Healthcare.

crea un set di dati

Gli esempi riportati di seguito mostrano come creare un set di dati.

Console

  1. Nella console Google Cloud, vai alla pagina Browser.

    Vai al browser

  2. Fai clic su Crea set di dati. Viene visualizzata la pagina Proprietà del set di dati.

  3. Nel campo Nome, inserisci un identificatore per il set di dati soggetto ai requisiti per le dimensioni e i caratteri consentiti per il set di dati.

  4. Seleziona uno dei seguenti tipi di località:

    • Regione. Il set di dati risiede definitivamente all'interno di una regione Google Cloud. Dopo aver selezionato questa opzione, digita o seleziona una località nel campo Regione.

    • Più regioni. Il set di dati risiede in modo permanente in una località che si estende su più regioni Google Cloud. Dopo aver selezionato questa opzione, digita o seleziona una località che include più regioni nel campo Più regioni.

  5. Fai clic su Crea. Viene visualizzata la pagina Browser. Il nuovo set di dati viene visualizzato nell'elenco dei set di dati.

gcloud

Esegui il comando gcloud healthcare datasets create.

Prima di utilizzare uno qualsiasi dei dati di comando riportati di seguito, effettua le seguenti sostituzioni:

Esegui questo comando:

Linux, macOS o 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

Dovresti ricevere una risposta simile alla seguente:

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

REST

Utilizza il metodo projects.locations.datasets.create.

  1. Crea il set di dati.

    Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

    Per inviare la richiesta, scegli una delle seguenti opzioni:

    arricciatura

    Esegui questo comando:

    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

    Esegui questo comando:

    $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

    Explorer API

    Apri la pagina di riferimento del metodo. Il riquadro Explorer API si apre sul lato destro della pagina. Puoi interagire con questo strumento per inviare richieste. Compila tutti i campi obbligatori e fai clic su Esegui.

    L'output è il seguente. La risposta contiene un identificatore per un'operazione a lunga esecuzione (LRO). Le operazioni a lunga esecuzione vengono restituite quando il completamento delle chiamate al metodo potrebbe richiedere più tempo. Prendi nota del valore di OPERATION_ID. Questo valore ti servirà nel passaggio successivo.

  2. Utilizza il metodo projects.locations.datasets.operations.get per ottenere lo stato dell'operazione a lunga esecuzione.

    Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

    • PROJECT_ID: l'ID del tuo progetto Google Cloud
    • LOCATION: la posizione del set di dati
    • DATASET_ID: l'ID del set di dati che viene creato
    • OPERATION_ID: l'ID dell'operazione a lunga esecuzione

    Per inviare la richiesta, scegli una delle seguenti opzioni:

    arricciatura

    Esegui questo comando:

    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

    Esegui questo comando:

    $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

    Explorer API

    Apri la pagina di riferimento del metodo. Il riquadro Explorer API si apre sul lato destro della pagina. Puoi interagire con questo strumento per inviare richieste. Compila tutti i campi obbligatori e fai clic su Esegui.

    L'output è il seguente. La risposta contiene "done": true, che indica che il set di dati è stato creato correttamente.

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

Modifica un set di dati

I seguenti esempi mostrano come modificare un set di dati.

Console

La console Google Cloud non supporta la modifica di un set di dati. Utilizza invece Google Cloud CLI o l'API REST.

gcloud

Esegui il comando gcloud healthcare datasets update.

Prima di utilizzare uno qualsiasi dei dati di comando riportati di seguito, effettua le seguenti sostituzioni:

  • LOCATION: la posizione del set di dati
  • DATASET_ID: l'ID del set di dati
  • TIME_ZONE: un fuso orario supportato, ad esempio UTC

Esegui questo comando:

Linux, macOS o 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

Dovresti ricevere una risposta simile alla seguente:

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

REST

Utilizza il metodo projects.locations.datasets.patch.

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID del tuo progetto Google Cloud
  • LOCATION: la posizione del set di dati
  • DATASET_ID: l'ID del set di dati
  • TIME_ZONE: un fuso orario supportato, ad esempio UTC

Corpo JSON della richiesta:

{
  "timeZone": "TIME_ZONE"
}

Per inviare la richiesta, scegli una delle seguenti opzioni:

arricciatura

Salva il corpo della richiesta in un file denominato request.json ed esegui questo comando:

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

Salva il corpo della richiesta in un file denominato request.json ed esegui questo comando:

$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

Explorer API

Copia il corpo della richiesta e apri la pagina di riferimento del metodo. Il riquadro Explorer API si apre sul lato destro della pagina. Puoi interagire con questo strumento per inviare richieste. Incolla il corpo della richiesta in questo strumento, compila gli altri campi obbligatori e fai clic su Esegui.

Dovresti ricevere una risposta JSON simile alla seguente:

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

Ottieni dettagli set di dati

Gli esempi riportati di seguito mostrano come recuperare i dettagli di un set di dati.

Console

  1. Nella console Google Cloud, vai alla pagina Browser.

    Vai al browser

  2. Seleziona il set di dati. Vengono visualizzati la pagina Set di dati e i datastore nel set di dati.

gcloud

Esegui il comando gcloud healthcare datasets describe.

Prima di utilizzare uno qualsiasi dei dati di comando riportati di seguito, effettua le seguenti sostituzioni:

  • LOCATION: la posizione del set di dati
  • DATASET_ID: l'ID del set di dati

Esegui questo comando:

Linux, macOS o 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

Dovresti ricevere una risposta simile alla seguente:

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

REST

Utilizza il metodo projects.locations.datasets.get.

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID del tuo progetto Google Cloud
  • LOCATION: la posizione del set di dati
  • DATASET_ID: l'ID del set di dati

Per inviare la richiesta, scegli una delle seguenti opzioni:

arricciatura

Esegui questo comando:

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

Esegui questo comando:

$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

Explorer API

Apri la pagina di riferimento del metodo. Il riquadro Explorer API si apre sul lato destro della pagina. Puoi interagire con questo strumento per inviare richieste. Compila tutti i campi obbligatori e fai clic su Esegui.

Dovresti ricevere una risposta JSON simile alla seguente:

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

Creazione di un elenco di set di dati

Gli esempi riportati di seguito mostrano come elencare i set di dati nel progetto.

Console

Nella console Google Cloud, vai alla pagina Browser.

Vai al browser

gcloud

Esegui il comando gcloud healthcare datasets list.

Prima di utilizzare uno qualsiasi dei dati di comando riportati di seguito, effettua le seguenti sostituzioni:

  • LOCATION: la posizione del set di dati

Esegui questo comando:

Linux, macOS o 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

Dovresti ricevere una risposta simile alla seguente:

ID           LOCATION     TIMEZONE
DATASET_ID   LOCATION       TIME_ZONE

REST

Utilizza il metodo projects.locations.datasets.list.

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID del tuo progetto Google Cloud
  • LOCATION: la posizione del set di dati

Per inviare la richiesta, scegli una delle seguenti opzioni:

arricciatura

Esegui questo comando:

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

PowerShell

Esegui questo comando:

$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

Explorer API

Apri la pagina di riferimento del metodo. Il riquadro Explorer API si apre sul lato destro della pagina. Puoi interagire con questo strumento per inviare richieste. Compila tutti i campi obbligatori e fai clic su Esegui.

Dovresti ricevere una risposta JSON simile alla seguente:

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

Eliminazione di un set di dati

Gli esempi riportati di seguito mostrano come eliminare un set di dati.

Console

  1. Nella console Google Cloud, vai alla pagina Browser.

    Vai al browser

  2. Nella stessa riga del set di dati, fai clic sull'opzione Azioni e poi seleziona Elimina.

  3. Nella finestra di dialogo di conferma, inserisci l'ID del set di dati e fai clic su Elimina.

gcloud

Esegui il comando gcloud healthcare datasets delete.

Prima di utilizzare uno qualsiasi dei dati di comando riportati di seguito, effettua le seguenti sostituzioni:

  • LOCATION: la posizione del set di dati
  • DATASET_ID: l'ID del set di dati

Esegui questo comando:

Linux, macOS o 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

Per confermare, digita Y.

L'output è il seguente:

Deleted dataset [DATASET_ID]

REST

Utilizza il metodo projects.locations.datasets.delete.

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID del tuo progetto Google Cloud
  • LOCATION: la posizione del set di dati
  • DATASET_ID: l'ID del set di dati

Per inviare la richiesta, scegli una delle seguenti opzioni:

arricciatura

Esegui questo comando:

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

Esegui questo comando:

$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

Explorer API

Apri la pagina di riferimento del metodo. Il riquadro Explorer API si apre sul lato destro della pagina. Puoi interagire con questo strumento per inviare richieste. Compila tutti i campi obbligatori e fai clic su Esegui.

Dovresti ricevere un codice di stato riuscito (2xx) e una risposta vuota.

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

Passaggi successivi