修补 HL7v2 消息

在 HL7v2 存储区中修补消息。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

Go

在试用此示例之前,请按照使用客户端库的 Cloud Healthcare API 快速入门中的 Go 设置说明进行操作。如需了解详情,请参阅 Cloud Healthcare API Go API 参考文档

如需向 Cloud Healthcare API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"encoding/base64"
	"fmt"
	"io"
	"io/ioutil"

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

// patchHL7V2Message patches an HL7V2 message.
func patchHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID, messageFile string) error {
	ctx := context.Background()

	hl7v2message, err := ioutil.ReadFile(messageFile)
	if err != nil {
		return fmt.Errorf("ReadFile: %w", err)
	}

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

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s", projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID)
	message := &healthcare.Message{
		Data:   base64.StdEncoding.EncodeToString(hl7v2message),
		Labels: map[string]string{"my-label": "true"},
	}

	call := messagesService.Patch(name, message)
	call.UpdateMask("labels")
	resp, err := call.Do()
	if err != nil {
		return fmt.Errorf("Patch: %w", err)
	}

	fmt.Fprintf(w, "Patched HL7V2 message: %q\n", resp.Name)
	return nil
}

Java

在试用此示例之前,请按照使用客户端库的 Cloud Healthcare API 快速入门中的 Java 设置说明进行操作。如需了解详情,请参阅 Cloud Healthcare API Java API 参考文档

如需向 Cloud Healthcare API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Message;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessagePatch {
  private static final String MESSAGE_NAME =
      "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2MessagePatch(String hl7v2MessageName) throws IOException {
    // String hl7v2MessageName =
    //    String.format(
    //        MESSAGE_NAME, "project-id", "region-id", "dataset-id", "hl7v2-id", "message-id");

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

    // Fetch the initial state of the message.
    Messages.Get getRequest =
        client.projects().locations().datasets().hl7V2Stores().messages().get(hl7v2MessageName);
    Message message = getRequest.execute();

    // Update the Message fields as needed as needed. For a full list of Message fields, see:
    // https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.hl7V2Stores.messages
    Map<String, String> labels = new HashMap<>();
    labels.put("key1", "value1");
    labels.put("key2", "value2");
    message.setLabels(labels);

    // Create request and configure any parameters.
    Messages.Patch request =
        client
            .projects()
            .locations()
            .datasets()
            .hl7V2Stores()
            .messages()
            .patch(hl7v2MessageName, message)
            .setUpdateMask("labels");

    // Execute the request and process the results.
    message = request.execute();
    System.out.println("HL7v2 message patched: \n" + message.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

在试用此示例之前,请按照使用客户端库的 Cloud Healthcare API 快速入门中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Cloud Healthcare API Node.js API 参考文档

如需向 Cloud Healthcare API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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 patchHl7v2Message = async () => {
  // TODO(developer): uncomment the lines beginning with 'const' before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // The value for hl7v2MessageId is the server-generated ID returned when you
  // created or ingested the HL7v2 message in an HL7v2 store.
  // const hl7v2MessageId = 'qCnewKno44gTt3oBn4dQ0u8ZA23ibDdV9GpifD2E=';
  // const labelKey = 'status';
  // const labelValue = 'processed';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${hl7v2MessageId}`;
  const request = {
    name,
    updateMask: 'labels',
    resource: {
      labels: {
        labelKey: labelValue,
      },
    },
  };

  await healthcare.projects.locations.datasets.hl7V2Stores.messages.patch(
    request
  );
  console.log('Patched HL7v2 message');
};

patchHl7v2Message();

Python

在试用此示例之前,请按照使用客户端库的 Cloud Healthcare API 快速入门中的 Python 设置说明进行操作。如需了解详情,请参阅 Cloud Healthcare API Python API 参考文档

如需向 Cloud Healthcare API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

def patch_hl7v2_message(
    project_id,
    location,
    dataset_id,
    hl7v2_store_id,
    hl7v2_message_id,
    label_key,
    label_value,
):
    """Updates the message.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    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 parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the HL7v2 store's parent dataset ID
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    # hl7v2_message_id = '2yqbdhYHlk_ucSmWkcKOVm_N0p0OpBXgIlVG18rB-cw='  # replace with the HL7v2 message ID that was returned by the server
    # label_key = 'key1'  # replace with a key
    # label_value = 'label2'  # replace with a key value
    hl7v2_message_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_message_name = "{}/datasets/{}/hl7V2Stores/{}/messages/{}".format(
        hl7v2_message_parent, dataset_id, hl7v2_store_id, hl7v2_message_id
    )

    patch = {"labels": {label_key: label_value}}

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .patch(name=hl7v2_message_name, updateMask="labels", body=patch)
    )

    response = request.execute()
    print(
        "Patched HL7v2 message {} with labels:\n\t{}: {}".format(
            hl7v2_message_id, label_key, label_value
        )
    )
    return response

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器