创建和管理数据集

本页面介绍了如何创建、修改、查看和删除数据集。如需简要了解数据集,请参阅数据模型文档。

创建数据集

要使用 Cloud Healthcare API,您必须至少创建一个数据集。

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

控制台

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

    转到“数据集”页面

  2. 点击创建数据集
  3. 选择您项目和区域中唯一的数据集标识符。如果标识符不唯一,则数据集创建将失败。
  4. 选择数据集永久所在的区域,然后点击创建

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

gcloud

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

  • DATASET_ID 在该区域内必须是唯一的。它可以是 1 到 256 个字符的任意 Unicode 字符串,由数字、字母、下划线、短划线和句点组成。
  • 区域可以是 us-central1us-west2us-east4europe-west2europe-west4europe-west6northamerica-northeast1southamerica-east1asia-east2asia-northeast1asia-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

API

要创建数据集,请使用 projects.locations.datasets.create 方法。

curl

要创建数据集,请发出 POST 请求并指定以下信息:

  • 数据集的名称。数据集 ID 在其区域中必须唯一。它可以是 1 到 256 个字符的任意 Unicode 字符串,由数字、字母、下划线、短划线和句点组成。
  • 访问令牌

以下示例展示了使用 curlPOST 请求。

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

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/operations/OPERATION_ID"
}

响应包含操作名称。要跟踪操作状态并查看更多详细信息,请使用操作 get 方法

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/operations/OPERATION_ID"

如果请求成功,服务器将以 JSON 格式返回包含操作状态的响应:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.healthcare.v1.OperationMetadata",
    "apiMethodName": "google.cloud.healthcare.v1.dataset.DatasetService.CreateDataset",
    "createTime": "CREATE_TIME",
    "endTime": "END_TIME",
    "logsUrl": "https://console.cloud.google.com/logs/viewer/CLOUD_LOGGING_URL"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.healthcare.v1.dataset.Dataset",
    "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID"
  }
}

PowerShell

要创建数据集,请发出 POST 请求并指定以下信息:

  • 数据集的名称。数据集 ID 在其区域中必须唯一。它可以是 1 到 256 个字符的任意 Unicode 字符串,由数字、字母、下划线、短划线和句点组成。
  • 访问令牌

以下示例展示了使用 Windows PowerShell 的 POST 请求。

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

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

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/operations/OPERATION_ID"
}

响应包含操作名称。要跟踪操作状态并查看更多详细信息,请使用操作 get 方法

$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/operations/OPERATION_ID" | Select-Object -Expand Content

如果请求成功,服务器将以 JSON 格式返回包含操作状态的响应:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.healthcare.v1.OperationMetadata",
    "apiMethodName": "google.cloud.healthcare.v1.dataset.DatasetService.CreateDataset",
    "createTime": "CREATE_TIME",
    "endTime": "END_TIME",
    "logsUrl": "https://console.cloud.google.com/logs/viewer/CLOUD_LOGGING_URL"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.healthcare.v1.dataset.Dataset",
    "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID"
  }
}

Go

import (
	"context"
	"fmt"
	"io"

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

// createDataset creates a dataset.
func createDataset(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

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

	resp, err := datasetsService.Create(parent, &healthcare.Dataset{}).DatasetId(datasetID).Do()
	if err != nil {
		return fmt.Errorf("Create: %v", 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');
const healthcare = google.healthcare('v1');

const createDataset = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // 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, cloud_region, dataset_id):
    """Creates a dataset."""
    client = get_client()
    dataset_parent = 'projects/{}/locations/{}'.format(
        project_id, cloud_region)

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

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

编辑数据集

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

控制台

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

API

要编辑数据集,请使用 projects.locations.datasets.patch 方法。

curl

要编辑数据集,请发出 PATCH 请求并指定以下信息:

  • 数据集的名称
  • 要更新的元数据
  • 更新掩码
  • 访问令牌

以下示例展示了如何通过使用 curl 发出 PATCH 请求来更新时区。

TIMEZONE 变量替换为一个值,例如 UTC。时区值必须为大写。

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

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID"
  "timeZone": "TIMEZONE"
}

PowerShell

要编辑数据集,请发出 PATCH 请求并指定以下信息:

  • 数据集的名称
  • 要更新的元数据
  • 更新掩码
  • 访问令牌

以下示例展示了如何通过使用 Windows PowerShell 发出 PATCH 请求来更新时区。

TIMEZONE 变量替换为一个值,例如 UTC。时区值必须为大写。

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }
Invoke-WebRequest `
  -Method Patch `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
      'timeZone': 'TIMEZONE'
  }" `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID?updateMask=timeZone" | Select-Object -Expand Content

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID"
  "timeZone": "TIMEZONE"
}

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');
const healthcare = google.healthcare('v1');

const patchDataset = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // 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, cloud_region, dataset_id, time_zone):
    """Updates dataset metadata."""
    client = get_client()
    dataset_parent = 'projects/{}/locations/{}'.format(
        project_id, cloud_region)
    dataset_name = '{}/datasets/{}'.format(dataset_parent, dataset_id)

    # Sets the time zone to GMT
    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. 在 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

API

要获取有关数据集的详细信息,请使用 projects.locations.datasets.get 方法。

curl

要获取有关数据集的详细信息,请发出 GET 请求并指定以下信息:

  • 数据集的名称
  • 访问令牌

以下示例展示了使用 curlGET 请求。

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"

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID"
  "timeZone": "UTC"
}

PowerShell

要获取有关数据集的详细信息,请发出 GET 请求并指定以下信息:

  • 数据集的名称
  • 访问令牌

以下示例展示了使用 Windows PowerShell 的 GET 请求。

$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

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID"
  "timeZone": "UTC"
}

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');
const healthcare = google.healthcare('v1');

const getDataset = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // 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, cloud_region, dataset_id):
    """Gets any metadata associated with a dataset."""
    client = get_client()
    dataset_name = 'projects/{}/locations/{}/datasets/{}'.format(
        project_id, cloud_region, 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

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

控制台

要列出项目中的数据集,请在 Cloud Console 中转到“医疗保健数据集”页面。

转到“数据集”页面

gcloud

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

gcloud healthcare datasets list

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

ID           LOCATION     TIMEZONE
DATASET_ID   LOCATION       TIME_ZONE

API

要列出项目中的数据集,请使用 projects.locations.datasets.list 方法。

curl

要列出项目中的数据集,请发出 GET 请求并指定以下信息:

  • 您的项目的名称
  • 访问令牌

以下示例展示了使用 curlGET 请求。

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

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "datasets": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID",
      "timeZone": "UTC"
    },
    {
      ...
      ...
    }
  ]
}

PowerShell

要列出项目中的数据集,请发出 GET 请求并指定以下信息:

  • 您的项目的名称
  • 访问令牌

以下示例展示了使用 Windows PowerShell 的 GET 请求。

$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

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "datasets": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID",
      "timeZone": "UTC"
    },
    {
      ...
      ...
    }
  ]
}

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');
const healthcare = google.healthcare('v1');

const listDatasets = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // 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, cloud_region):
    """Lists the datasets in the project."""
    client = get_client()
    dataset_parent = 'projects/{}/locations/{}'.format(
        project_id, cloud_region)

    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. 在 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]

API

如要删除数据集,请使用 projects.locations.datasets.delete 方法:

curl

如要删除数据集,请发出 DELETE 请求并指定以下信息:

  • 数据集的名称
  • 访问令牌

以下示例展示了使用 curlDELETE 请求。

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"

如果请求成功,服务器将以 JSON 格式返回响应:

{}

PowerShell

如要删除数据集,请发出 DELETE 请求并指定以下信息:

  • 数据集的名称
  • 访问令牌

以下示例展示了使用 Windows PowerShell 的 DELETE 请求。

$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

如果请求成功,服务器将以 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');
const healthcare = google.healthcare('v1');

const deleteDataset = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // 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, cloud_region, dataset_id):
    """Deletes a dataset."""
    client = get_client()
    dataset_name = 'projects/{}/locations/{}/datasets/{}'.format(
        project_id, cloud_region, dataset_id)

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

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

后续步骤