创建和管理数据集

本页面介绍如何创建、修改、查看、列出和删除数据集。在使用本页面之前,请先熟悉 Cloud Healthcare API 数据模型

创建数据集

创建数据集是使用 Cloud Healthcare API 中的大多数功能的第一步。创建数据集后,您可以创建用于存储电子健康记录、医学影像数据、用户许可等的数据存储区。

以下示例展示了如何创建数据集。

控制台

  1. 在 Google Cloud Console 中,转到数据集页面。

    转到“数据集”页面

  2. 点击创建数据集
  3. 名称字段中,输入数据集的标识符。数据集 ID 必须符合以下条件:
    • 位置中的唯一 ID
    • 由 1-256 个字符组成的 Unicode 字符串,由以下各项组成:
      • 数字
      • 字母
      • 下划线
      • 短划线
      • 英文句点
  4. 位置类型部分,选择以下任一位置类型:
    • 区域:数据集永久位于一个 Google Cloud 区域内。选择完毕后,在区域字段中输入或选择位置。
    • 多区域:数据集永久位于跨越多个 Google Cloud 区域的单个位置。选择后,在多区域字段中输入或选择多区域位置。

新数据集将显示在数据集列表中。

gcloud

要创建数据集,请运行 gcloud healthcare datasets create 命令:

  • DATASET_ID 在该区域内必须是唯一的。它可以是 1 到 256 个字符的任意 Unicode 字符串,由数字、字母、下划线、短划线和句点组成。
  • 区域可以是 us-central1us-west1us-west2us-west3us-east1us-east4europe-west2europe-west3europe-west4europe-west6northamerica-northeast1southamerica-east1asia-east2asia-northeast1asia-northeast3asia-south1asia-southeast1australia-southeast1us。如需使用项目的默认区域,请省略 --location 选项。
gcloud healthcare datasets create DATASET_ID \
    --location=LOCATION

命令行会显示操作 ID,并在操作完成后确认创建了数据集:

Create request issued for: [DATASET_ID]
Waiting for operation [projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/operations/OPERATION_ID] to complete...done.
Created dataset [DATASET_ID].

要查看操作的更多详情,请运行 gcloud healthcare operations describe 命令,并提供响应中的 OPERATION_ID

gcloud healthcare operations describe OPERATION_ID \
    --dataset=DATASET_ID

响应包括 done: true

done: true
metadata:
    '@type': type.googleapis.com/google.cloud.healthcare.v1.OperationMetadata
    apiMethodName: google.cloud.healthcare.v1.dataset.DatasetService.CreateDataset
    createTime: 'CREATE_TIME'
    endTime: 'END_TIME'
name: projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/operations/OPERATION_ID
response:
    '@type': type.googleapis.com/google.cloud.healthcare.v1.dataset.Dataset
    name: projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID

REST 和命令行

  1. 创建数据集。

    在使用任何请求数据之前,请先进行以下替换:

    • PROJECT_ID:您的 Google Cloud 项目的 ID
    • LOCATION:数据集的位置。使用 us-central1us-west1us-west2us-west3us-east1us-east4europe-west2europe-west3europe-west4europe-west6northamerica-northeast1southamerica-east1asia-east2asia-northeast1asia-northeast3asia-south1asia-southeast1australia-southeast1us
    • DATASET_ID:数据集的标识符。数据集 ID 必须符合以下条件:
      • 位置中的唯一 ID
      • 包含 1-256 个字符的 Unicode 字符串,由以下各项组成:
        • 数字
        • 字母
        • 下划线
        • 短划线
        • 英文句点

    如需发送请求,请选择以下方式之一:

    curl

    执行以下命令:

    curl -X POST \
    -H "Authorization: Bearer "$(gcloud auth application-default 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

    执行以下命令:

    $cred = gcloud auth application-default 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

    API Explorer

    打开方法参考页面。API Explorer 面板会在页面右侧打开。您可以与此工具进行互动以发送请求。填写所有必填字段,然后点击执行

    输出如下所示。响应包含长时间运行的操作的标识符。如果方法调用可能需要很长时间才能完成,系统就会返回长时间运行的操作。请记下 OPERATION_ID 的值。下一步中您需要用到此值。

  2. 获取长时间运行的操作的状态。

    在使用任何请求数据之前,请先进行以下替换:

    • PROJECT_ID:您的 Google Cloud 项目的 ID
    • LOCATION:数据集位置
    • DATASET_ID:要创建的数据集 ID
    • OPERATION_ID:长时间运行的操作的 ID

    如需发送请求,请选择以下方式之一:

    curl

    执行以下命令:

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

    PowerShell

    执行以下命令:

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

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

    API Explorer

    打开方法参考页面。API Explorer 面板会在页面右侧打开。您可以与此工具进行互动以发送请求。填写所有必填字段,然后点击执行

    输出如下所示。响应包含 "done": true,表示已成功创建数据集。

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: %v", 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: %v", 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.jackson2.JacksonFactory;
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 JacksonFactory();
  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

def create_dataset(project_id, location, dataset_id):
    """Creates a dataset.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/datasets
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"
    # Instantiates 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'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the dataset's location
    # dataset_id = 'my-dataset'  # replace with your dataset ID
    dataset_parent = "projects/{}/locations/{}".format(project_id, location)

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

    response = request.execute()
    print("Created dataset: {}".format(dataset_id))
    return response

编辑数据集

以下示例展示了如何修改现有数据集。

控制台

Google Cloud Console 不支持修改医疗保健数据集。请改用 curl、Windows PowerShell 或您的首选语言。

gcloud

要修改数据集,请运行 gcloud healthcare datasets update 命令并指定新时区。例如,您可以将时区设置为“加拿大/东部地区”。

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

如果请求成功,命令提示符将显示操作和数据集详情:

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

REST 和命令行

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目的 ID
  • LOCATION:数据集位置
  • DATASET_ID:数据集 ID
  • TIME_ZONE:支持的时区,例如 UTC

请求 JSON 正文:

{
  "timeZone": "TIME_ZONE"
}

如需发送请求,请选择以下方式之一:

curl

  1. 将请求正文保存在名为 request.json 的文件中。复制以下命令,并在终端中运行它以创建此文件。
    cat > request.json << 'EOF'
    {
      "timeZone": "TIME_ZONE"
    }
    EOF
  2. 在终端运行以下命令。它引用您刚刚创建的 request.json 文件。
    curl -X PATCH \
    -H "Authorization: Bearer "$(gcloud auth application-default 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

  1. 将请求正文保存在名为 request.json 的文件中。复制以下命令,并在终端中运行它以创建此文件。
    @'
    {
      "timeZone": "TIME_ZONE"
    }
    '@  | Out-File -FilePath request.json -Encoding utf8
  2. 在终端运行以下命令。它引用您刚刚创建的 request.json 文件。
    $cred = gcloud auth application-default 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

API Explorer

复制请求正文并打开方法参考页面。API Explorer 面板会在页面右侧打开。您可以与此工具进行交互以发送请求。将请求正文粘贴到此工具中,填写任何其他必填字段,然后点击执行

您应该收到类似以下内容的 JSON 响应:

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: %v", 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: %v", 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.jackson2.JacksonFactory;
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 JacksonFactory();
  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

def patch_dataset(project_id, location, dataset_id, time_zone):
    """Updates dataset metadata.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/datasets
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    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'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the dataset's location
    # dataset_id = 'my-dataset'  # replace with your dataset ID
    # time_zone = 'GMT'  # replace with the dataset's time zone
    dataset_parent = "projects/{}/locations/{}".format(project_id, location)
    dataset_name = "{}/datasets/{}".format(dataset_parent, dataset_id)

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

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

    response = request.execute()
    print("Patched dataset {} with time zone: {}".format(dataset_id, time_zone))
    return response

获取数据集详情

以下示例展示了如何获取有关数据集的详细信息。

控制台

如需查看数据集中的数据存储区,请执行以下操作:

  1. 在 Google Cloud Console 中,转到“数据集”页面。

    转到“数据集”页面

  2. 点击要查看其数据存储的数据集的 ID。

gcloud

要查看有关数据集的详细信息,请运行 gcloud healthcare datasets describe 命令。

gcloud healthcare datasets describe DATASET_ID \
    --location=LOCATION

如果请求成功,命令提示符将显示数据集详情。

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

REST 和命令行

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目的 ID
  • LOCATION:数据集位置
  • DATASET_ID:数据集 ID

如需发送请求,请选择以下方式之一:

curl

执行以下命令:

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

PowerShell

执行以下命令:

$cred = gcloud auth application-default 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

API Explorer

打开方法参考页面。API Explorer 面板会在页面右侧打开。您可以与此工具进行互动以发送请求。填写所有必填字段,然后点击执行

您应该会收到类似以下内容的 JSON 响应:

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: %v", 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: %v", 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.jackson2.JacksonFactory;
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 JacksonFactory();
  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

def get_dataset(project_id, location, dataset_id):
    """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."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    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'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the dataset's location
    # dataset_id = 'my-dataset'  # replace with your dataset ID
    dataset_name = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )

    datasets = client.projects().locations().datasets()
    dataset = datasets.get(name=dataset_name).execute()

    print("Name: {}".format(dataset.get("name")))
    print("Time zone: {}".format(dataset.get("timeZone")))

    return dataset

以下示例展示了如何列出项目中的数据集。

控制台

如需列出项目中的数据集,请在 Google Cloud Console 中转到“Healthcare Datasets”页面。

转到“数据集”页面

gcloud

要列出项目中的数据集,请运行 gcloud healthcare datasets list 命令:

gcloud healthcare datasets list

如果请求成功,命令提示符将列出数据集:

ID           LOCATION     TIMEZONE
DATASET_ID   LOCATION       TIME_ZONE

REST 和命令行

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目的 ID
  • LOCATION:数据集位置

如需发送请求,请选择以下方式之一:

curl

执行以下命令:

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

PowerShell

执行以下命令:

$cred = gcloud auth application-default 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

API Explorer

打开方法参考页面。API Explorer 面板会在页面右侧打开。您可以与此工具进行互动以发送请求。填写所有必填字段,然后点击执行

您应该会收到类似以下内容的 JSON 响应:

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: %v", 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: %v", 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.jackson2.JacksonFactory;
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 JacksonFactory();
  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

def list_datasets(project_id, location):
    """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."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    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'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the location of the datasets
    dataset_parent = "projects/{}/locations/{}".format(project_id, location)

    datasets = (
        client.projects()
        .locations()
        .datasets()
        .list(parent=dataset_parent)
        .execute()
        .get("datasets", [])
    )

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

    return datasets

删除数据集

以下示例展示了如何删除数据集。

控制台

要删除数据集,请执行以下操作:

  1. 在 Google Cloud Console 中,转到“数据集”页面。

    转到“数据集”页面

  2. 选择要删除的数据集,然后点击删除
  3. 如要确认,请输入数据集标识符,然后点击删除

gcloud

要删除数据集,请运行 gcloud healthcare datasets delete 命令:

  1. 运行 delete 命令:

    gcloud healthcare datasets delete DATASET_ID \
        --location=LOCATION
    
  2. 要确认,请键入 Y

如果请求成功,命令提示符将显示:

Deleted dataset [DATASET_ID]

REST 和命令行

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目的 ID
  • LOCATION:数据集位置
  • DATASET_ID:数据集 ID

如需发送请求,请选择以下方式之一:

curl

执行以下命令:

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

PowerShell

执行以下命令:

$cred = gcloud auth application-default 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

API Explorer

打开方法参考页面。API Explorer 面板会在页面右侧打开。您可以与此工具进行互动以发送请求。填写所有必填字段,然后点击执行

您应该会收到类似以下内容的 JSON 响应:

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: %v", 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: %v", 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.jackson2.JacksonFactory;
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 JacksonFactory();
  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, location, dataset_id):
    """Deletes a dataset.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/datasets
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    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'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the dataset's location
    # dataset_id = 'my-dataset'  # replace with your dataset ID
    dataset_name = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )

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

    response = request.execute()
    print("Deleted dataset: {}".format(dataset_id))
    return response

后续步骤