HL7v2-Nachrichten erstellen und verwalten

Auf dieser Seite wird erläutert, wie Sie HL7v2-Nachrichten aufnehmen, erstellen, mit Labels versehen, auflisten, ansehen und löschen. HL7v2-Nachrichten werden für die Übertragung von klinischen Daten zwischen Systemen genutzt. Eine HL7v2-Nachricht kann Informationen zu einem Beobachtungsergebnis, ein an eine Apotheke gesendetes Rezept, eine Finanztransaktion oder andere klinikrelevante Ereignisse enthalten.

Übersicht über das Erstellen und Aufnehmen von HL7v2-Nachrichten

Verwenden Sie eine der folgenden Methoden, um eine HL7v2-Nachricht in der Cloud Healthcare API zu speichern:

Wenn Sie messages.ingest verwenden, generiert die Methode eine Antwort, die Folgendes enthält:

  • Einer HL7v2-Bestätigungsnachricht (ACK) bei Erfolg
  • Einer negative Bestätigungsnachricht (NACK), wenn ein Fehler auftritt

Die Nachrichten ACK und NACK werden für Antworten an HL7v2-Schnittstellensysteme verwendet, die diese Bestätigungen erwarten.

Nachrichtenaufnahme und -erstellung mit einem MLLP-Adapter

HL7v2-Nachrichten werden zwischen Pflegesystemen und der Cloud Healthcare API über das MLLP (Minimal Layer Protocol) übermittelt. Weitere Informationen finden Sie unter MLLP und Google Cloud Platform MLLP-Adapter. Eine Anleitung zum Konfigurieren eines MLLP-Adapters für die sichere Kommunikation mit der Cloud Healthcare API finden Sie unter HL7v2-Nachrichten über TCP/IP-Verbindungen übertragen.

HL7v2-Nachrichten aufnehmen

Nachdem die Cloud Healthcare API die Nachricht aus einem Caret-System aufgenommen hat, generiert die Cloud Healthcare API eine Antwort, die ein hl7ack-Feld mit einer base64-codierten HL7v2-Nachricht mit den folgenden Eigenschaften enthält:

  • Der Nachrichtentyp ist ACK.
  • Die sendende und die empfangende Einrichtung werden getauscht und die sendende Anwendung und die empfangende Anwendung werden getauscht.
  • Die Sendezeit der Nachricht ist die aktuelle Zeit und es wird eine neue Steuerungs-ID generiert.
  • Der Wert des Felds MSH-9.1 definiert den Nachrichtentyp.
  • Der Wert des MSA.1-Felds definiert einen Antworttyp. Der Antworttyp AA gibt Application Accept an, was bedeutet, dass die Nachricht validiert und erfolgreich aufgenommen wurde.
  • Der MSA.2-Wert enthält die Kontroll-ID der ursprünglichen Nachricht.

Die folgenden Beispiele zeigen, wie eine HL7v2-Nachricht mit der Methode projects.locations.datasets.hl7V2Stores.messages.ingest aufgenommen wird.

curl

Wenn Sie eine HL7v2-Nachricht aufnehmen möchten, senden Sie eine POST-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Ein Message

Das folgende Beispiel zeigt eine POST-Anfrage mit curl und einer JSON-Beispieldatei mit dem Namen hl7v2-sample.json.

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

Die folgende Beispielantwort zeigt die hl7Ack- und Nachrichtendetails.

{
  "hl7Ack": "TVNIfF5+XCZ8QXxBfEF8U0VORF9GQUNJTElUWXwyMDIwMDIxNDIxMjAwNXx8QUNLfDFmMmQ1MjQzLTFhOWEtNGE4My05ZmI5LWNlNTIzMTVmZjk2M3xUfDAuMA1NU0F8QUF8MjAxODAxMDEwMDAwMDA=",
  "message": {
    "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
    "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwNDAwMDANUElEfHwxNAExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk9SR05NQlI=",
    "sendFacility": "SEND_FACILITY",
    "sendTime": "2018-01-01T00:00:00Z",
    "messageType": "TYPE",
    "createTime": "CREATE_TIME",
    "patientIds": [
      {
        "value": "14\u0001111",
        "type": "MRN"
      },
      {
        "value": "11111111",
        "type": "MRN"
      },
      {
        "value": "1111111111",
        "type": "ORGNMBR"
      }
    ]
  }
}

PowerShell

Wenn Sie eine HL7v2-Nachricht aufnehmen möchten, senden Sie eine POST-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Ein Message

Das folgende Beispiel zeigt eine POST-Anfrage mit PowerShell und eine JSON-Beispieldatei namens hl7v2-sample.json.

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

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

Die folgende Beispielantwort zeigt die hl7Ack- und Nachrichtendetails.

{
  "hl7Ack": "TVNIfF5+XCZ8QXxBfEF8U0VORF9GQUNJTElUWXwyMDIwMDIxNDIxMjAwNXx8QUNLfDFmMmQ1MjQzLTFhOWEtNGE4My05ZmI5LWNlNTIzMTVmZjk2M3xUfDAuMA1NU0F8QUF8MjAxODAxMDEwMDAwMDA=",
  "message": {
    "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
    "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwNDAwMDANUElEfHwxNAExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk9SR05NQlI=",
    "sendFacility": "SEND_FACILITY",
    "sendTime": "2018-01-01T00:00:00Z",
    "messageType": "TYPE",
    "createTime": "CREATE_TIME",
    "patientIds": [
      {
        "value": "14\u0001111",
        "type": "MRN"
      },
      {
        "value": "11111111",
        "type": "MRN"
      },
      {
        "value": "1111111111",
        "type": "ORGNMBR"
      }
    ]
  }
}

Go

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

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

// ingestHL7V2Message ingests an HL7V2 message.
func ingestHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, 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

	req := &healthcare.IngestMessageRequest{
		Message: &healthcare.Message{
			Data: base64.StdEncoding.EncodeToString(hl7v2message),
		},
	}
	parent := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s", projectID, location, datasetID, hl7V2StoreID)

	resp, err := messagesService.Ingest(parent, req).Do()
	if err != nil {
		return fmt.Errorf("Create: %w", err)
	}

	fmt.Fprintf(w, "Ingested HL7V2 message: %q\n", resp.Message.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.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.IngestMessageRequest;
import com.google.api.services.healthcare.v1.model.IngestMessageResponse;
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.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageIngest {
  private static final String HL7v2_NAME = "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s";
  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 hl7v2MessageIngest(String hl7v2StoreName, String filePath) throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");

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

    // Load the data from file and format it into an ingest request.
    List<String> lines = Files.readAllLines(Paths.get(filePath), Charset.defaultCharset());
    String data = String.join("\n", lines);
    Message message = new Message().setData(data);
    IngestMessageRequest ingestRequest = new IngestMessageRequest().setMessage(message);

    // Create request and configure any parameters.
    Messages.Ingest request =
        client
            .projects()
            .locations()
            .datasets()
            .hl7V2Stores()
            .messages()
            .ingest(hl7v2StoreName, ingestRequest);

    // Execute the request and process the results.
    IngestMessageResponse response = request.execute();
    System.out.println("HL7v2 message ingested: " + response.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 fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);

const ingestHl7v2Message = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // const hl7v2MessageFile = 'hl7v2-message.json';
  const hl7v2Message = JSON.parse(await readFile(hl7v2MessageFile));

  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {parent, resource: hl7v2Message};

  const response =
    await healthcare.projects.locations.datasets.hl7V2Stores.messages.ingest(
      request
    );
  const data = response.data.hl7Ack;
  const buff = new Buffer.from(data, 'base64');
  const hl7Ack = buff.toString('ascii');
  console.log('Ingested HL7v2 message with ACK:\n', hl7Ack);
};

ingestHl7v2Message();

Python

def ingest_hl7v2_message(
    project_id, location, dataset_id, hl7v2_store_id, hl7v2_message_file
):
    """Ingests a new HL7v2 message from the hospital and sends a notification
    to the Cloud Pub/Sub topic. Return is an HL7v2 ACK message if the message
    was successfully stored.

    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

    # Imports Python's built-in "json" module
    import json

    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_file = 'hl7v2-message.json'  # replace with the path to the HL7v2 file
    hl7v2_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_store_name = "{}/datasets/{}/hl7V2Stores/{}".format(
        hl7v2_parent, dataset_id, hl7v2_store_id
    )

    with open(hl7v2_message_file) as hl7v2_message:
        hl7v2_message_content = json.load(hl7v2_message)

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .ingest(parent=hl7v2_store_name, body=hl7v2_message_content)
    )

    response = request.execute()
    print(f"Ingested HL7v2 message from file: {hl7v2_message_file}")
    return response

HL7v2-Nachrichten erstellen

Die folgenden Beispiele zeigen, wie Sie eine HL7v2-Nachricht mit der Methode projects.locations.datasets.hl7V2Stores.messages.create erstellen.

REST

Verwenden Sie die projects.locations.datasets.hl7V2Stores.messages.create-Methode, um eine HL7v2-Nachricht zu erstellen.

Wenn Sie für die Beispielbefehle eine HL7v2-Nachrichtendatei benötigen, können Sie die JSON-Datei hl7v2-sample.json herunterladen.

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

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID ist das übergeordnete Dataset des HL7v2-Speichers
  • HL7V2_STORE_ID ist die HL7v2-Speicher-ID
  • HL7V2_MESSAGE_FILE ist der Pfad zu einer JSON-formatierten Datei, die eine HL7v2-Nachricht auf Ihrem lokalen Computer enthält

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

curl

Führen Sie folgenden Befehl aus:

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

PowerShell

Führen Sie folgenden Befehl aus:

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

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

APIs Explorer

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

Beim Erstellen einer Nachricht mit der JSON-Datei hl7v2-sample.json wird die folgende Ausgabe zurückgegeben:

Go

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

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

// createHL7V2Message creates an HL7V2 message.
func createHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, 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

	req := &healthcare.CreateMessageRequest{
		Message: &healthcare.Message{
			Data: base64.StdEncoding.EncodeToString(hl7v2message),
		},
	}
	parent := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s", projectID, location, datasetID, hl7V2StoreID)
	resp, err := messagesService.Create(parent, req).Do()
	if err != nil {
		return fmt.Errorf("Create: %w", err)
	}

	fmt.Fprintf(w, "Created HL7V2 message: %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.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.CreateMessageRequest;
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.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;

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

  public static void hl7v2MessageCreate(String hl7v2StoreName, String messageId, String filePath)
      throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");
    // String messageId = "your-message-id";
    // String filePath = "path/to/file.txt";

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

    // Load the data from file representing the message.
    List<String> lines = Files.readAllLines(Paths.get(filePath), Charset.defaultCharset());
    String data = String.join("\n", lines);
    Message message = new Message().setData(data).setName(messageId);
    CreateMessageRequest createRequest = new CreateMessageRequest().setMessage(message);

    // Create request and configure any parameters.
    Messages.Create request =
        client
            .projects()
            .locations()
            .datasets()
            .hl7V2Stores()
            .messages()
            .create(hl7v2StoreName, createRequest);

    // Execute the request and process the results.
    Message response = request.execute();
    System.out.println("HL7v2 message created: " + response.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 fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);

const createHl7v2Message = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // const hl7v2MessageFile = 'hl7v2-message.json';
  const hl7v2Message = JSON.parse(await readFile(hl7v2MessageFile));

  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {parent, resource: hl7v2Message};

  const response =
    await healthcare.projects.locations.datasets.hl7V2Stores.messages.create(
      request
    );
  const {data} = response;
  console.log('Created HL7v2 message with data:\n', data);
};

createHl7v2Message();

Python

def create_hl7v2_message(
    project_id, location, dataset_id, hl7v2_store_id, hl7v2_message_file
):
    """Creates an HL7v2 message and sends a notification to the
    Cloud Pub/Sub topic.

    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

    # Imports Python's built-in "json" module
    import json

    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_file = 'hl7v2-message.json'  # replace with the path to the HL7v2 file
    hl7v2_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_store_name = "{}/datasets/{}/hl7V2Stores/{}".format(
        hl7v2_parent, dataset_id, hl7v2_store_id
    )

    with open(hl7v2_message_file) as hl7v2_message:
        hl7v2_message_content = json.load(hl7v2_message)

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .create(parent=hl7v2_store_name, body=hl7v2_message_content)
    )

    response = request.execute()
    print(f"Created HL7v2 message from file: {hl7v2_message_file}")
    return response

HL7v2-Nachrichtensegment-Trennzeichen und -Kodierung

Das standardmäßige Segmenttrennzeichen in HL7v2 ist ein Zeilenumbruch (\r). Die meisten Texteditoren verwenden Zeilenumbruchzeichen (\n) als Segmenttrennzeichen. Dies erzeugt HL7v2-Nachrichten, die nicht mit der Standardkonfiguration in die Cloud Healthcare API aufgenommen werden können. Wie Sie zulassen, dass ein HL7v2-Speicher Nachrichten mit Zeilenvorschubzeichen als Segmenttrennzeichen aufnehmen kann, erfahren Sie unter Segmentabschlusszeichen festlegen.

Führen Sie den folgenden Befehl in einer Linux-Shell aus, um die Zeilenumbruchzeichen in einer Datei in Zeilenumbrüche umzuwandeln:

sed -z 's/\n/\r/g' INPUT_FILENAME > OUTPUT_FILENAME

Die Methoden Aufnehmen und Erstellen erwarten, dass HL7v2-Nachrichten base64-codierte Strings sind. Führen Sie den folgenden Befehl in einer Linux-Shell aus, um einen String in eine Base64-Codierung umzuwandeln:

openssl base64 -A -in ./INPUT_FILENAME -out ./OUTPUT_FILENAME

Segmentabschluss festlegen

Beim Erstellen oder Aufnehmen von Daten erfordert das HL7v2-Nachrichtenformat, dass Segmente mit dem Rückgabezeichen \r beendet werden. Sie können einen HL7v2-Speicher so konfigurieren, dass HL7v2-Nachrichten mit einem nicht standardmäßigen Abschlusszeichen wie \n akzeptiert werden.

Betrachten Sie die folgende HL7v2-Nachricht, die den standardmäßigen \r als Segmentabschluss verwendet. Diese Nachricht wird standardmäßig akzeptiert, wenn Sie einen HL7v2-Speicher erstellen.

MSH|^~\\&|FROM_APP|FROM_FACILITY|TO_APP|TO_FACILITY|20150503223000||ADT^A01|20150503223000|P|2.5|\r
EVN|A01|20110613083617|\r
PID|1||21004053^^^^MRN||SULLY^BRIAN||19611209|M|||123 MAIN ST^^MOUNTAIN SPRINGS^CO^80439|\r
PV1||I|H73 RM1^1^^HIGHWAY 73 CLINIC||||5148^MARY QUINN|||||||||Y||||||||||||||||||||||||||||20150503223000|\r

Die folgende Nachricht ist mit der vorherigen Nachricht identisch, außer dass sie \n als Segmentabschlusszeichen verwendet:

MSH|^~\\&|FROM_APP|FROM_FACILITY|TO_APP|TO_FACILITY|20150503223000||ADT^A01|20150503223000|P|2.5|\n
EVN|A01|20110613083617|\n
PID|1||21004053^^^^MRN||SULLY^BRIAN||19611209|M|||123 MAIN ST^^MOUNTAIN SPRINGS^CO^80439|\n
PV1||I|H73 RM1^1^^HIGHWAY 73 CLINIC||||5148^MARY QUINN|||||||||Y||||||||||||||||||||||||||||20150503223000|\n

Zum Speichern der Nachricht mit dem nicht standardmäßigen Abschlusszeichen konfigurieren Sie das Objekt ParserConfig im HL7v2-Speicher und legen das Feld segmentTerminator auf die base64-Codierung von \n fest.

Die folgenden Beispiele zeigen, wie Sie segmentTerminator in ParserConfig konfigurieren, wenn Sie einen HL7v2-Speicher erstellen. Wenn Sie bereits einen HL7v2-Speicher haben, können Sie ihn bearbeiten, um den Text ParserConfig anzugeben. Nachdem Sie das Segmentabschlusszeichen festgelegt haben, können Sie die Nachricht erstellen oder aufnehmen.

curl

Wenn Sie einen HL7v2-Speicher mit dem Segmentabschlusszeichen \n erstellen möchten, senden Sie eine POST-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Ein parserConfig-Objekt, bei dem segmentTerminator auf Cg== gesetzt ist (die Base64-Codierung von \n)

Das folgende Beispiel zeigt eine POST-Anfrage mit curl.

curl -X POST \
    --data "{
      'parserConfig': {
        'segmentTerminator': 'Cg=='
      }
    }" \
    -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/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID"

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "segmentTerminator": "Cg=="
  }
}

PowerShell

Wenn Sie einen HL7v2-Speicher mit dem Segmentabschlusszeichen \n erstellen möchten, senden Sie eine POST-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Ein parserConfig-Objekt, bei dem segmentTerminator auf Cg== gesetzt ist (die Base64-Codierung von \n)

Das folgende Beispiel zeigt eine POST-Anfrage mit PowerShell.

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

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
      'parserConfig': {
        'segmentTerminator': 'Cg=='
      }
  } `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID" | Select-Object -Expand Content

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "segmentTerminator": "Cg=="
  }
}

Einen Null-Segment-Header verwenden

Eine HL7v2-Nachricht ohne Message Header Segment (MSH) hat einen Nullsegment-Header. In der Regel enthält eine HL7v2-Nachricht eine MSH-Datei, die Metadaten wie Quelle, Intent, Zweck und Ziel der Nachricht definiert. Mit dem MSH können Sie Nachrichten suchen und filtern. Sie können jedoch Nachrichten ohne MSH speichern, indem Sie das Objekt ParserConfig im HL7v2-Speicher konfigurieren und das Feld allowNullHeader auf true setzen.

Die folgende Beispielnachricht enthält ein PID-Segment (Patientenidentifizierung), aber keine MSH:

PID|1||21004053^^^^MRN||SULLY^BRIAN||19611209|M|||123 MAIN ST^^MOUNTAIN SPRINGS^CO^80439

Die folgenden Beispiele zeigen, wie Sie allowNullHeader in ParserConfig konfigurieren, wenn Sie einen HL7v2-Speicher erstellen. Wenn Sie bereits einen HL7v2-Speicher haben, können Sie ihn bearbeiten und den Text ParserConfig angeben. Nachdem Sie allowNullHeader auf true gesetzt haben, können Sie Nachrichten mit Null-Segment-Headern erstellen oder aufnehmen.

curl

Wenn Sie einen HL7v2-Speicher erstellen und Nachrichten ohne MSH speichern möchten, senden Sie eine POST-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Ein parserConfig-Objekt, bei dem allowNullHeader auf true gesetzt ist

Das folgende Beispiel zeigt eine POST-Anfrage mit curl.

curl -X POST \
    --data "{
      'parserConfig': {
        'allowNullHeader': true
      }
    }" \
    -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/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID"

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "allowNullHeader": true
  }
}

PowerShell

Wenn Sie einen HL7v2-Speicher erstellen und Nachrichten ohne MSH speichern möchten, senden Sie eine POST-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Ein parserConfig-Objekt, bei dem allowNullHeader auf true gesetzt ist

Das folgende Beispiel zeigt eine POST-Anfrage mit PowerShell.

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

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
      'parserConfig': {
        'nullTerminator': true
      }
  } `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID" | Select-Object -Expand Content

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "allowNullHeader": true
  }
}

Eine HL7v2-Nachricht hinzufügen

Sie können einer Nachricht ein oder mehrere Schlüssel/Wert-Labels hinzufügen. Ein Anwendungsfall für Labels ist das Hinzufügen von Statuslabels zu einer Nachricht, damit eine Anwendung Nachrichten nach Status abfragen kann.

In den folgenden Beispielen wird gezeigt, wie Sie einer HL7v2-Nachricht mithilfe der Methode projects.locations.datasets.hl7V2Stores.messages.patch Labels hinzufügen.

curl

Wenn Sie einer HL7v2-Nachricht Labels hinzufügen möchten, senden Sie eine PATCH-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Die Nachrichten-ID
  • Die zu aktualisierenden Labeldaten
  • Eine Aktualisierungsmaske

Das folgende Beispiel zeigt eine PATCH-Anfrage mit curl.

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

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    }
  ],
  "labels": {
    "KEY": "VALUE"
  }
}

PowerShell

Wenn Sie einer HL7v2-Nachricht Labels hinzufügen möchten, senden Sie eine PATCH-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Die Nachrichten-ID
  • Die zu aktualisierenden Labeldaten
  • Eine Aktualisierungsmaske

Das folgende Beispiel zeigt eine PATCH-Anfrage mit PowerShell.

$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 "{
      'labels': {
        'KEY': 'VALUE'
      }
  }" `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?updateMask=labels" | Select-Object -Expand Content

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    }
  ],
  "labels": {
    "KEY": "VALUE"
  }
}

Go

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

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

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

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

Inhalt von HL7v2-Nachrichten abrufen

In den folgenden Beispielen wird gezeigt, wie Sie den Inhalt einer HL7v2-Nachricht mit der Methode projects.locations.datasets.hl7V2Stores.messages.get abrufen. Geben Sie eine der folgenden Optionen an, um den Abfrageparameter view zu bestimmen:

  • BASIC: Nur das Feld name wird eingeschlossen.
  • RAW_ONLY: Schließen Sie alle Nachrichtenfelder mit Ausnahme des Felds parsedData ein.
  • PARSED_ONLY: Schließen Sie alle Nachrichtenfelder mit Ausnahme des Felds data ein.
  • FULL: Schließen Sie alle Nachrichtenfelder ein. Dies ist die Standardeinstellung.

In den folgenden Beispielen wird gezeigt, wie Sie den Inhalt einer HL7v2-Nachricht mit den Ansichten FULL, RAW_ONLY und PARSED_ONLY abrufen.

In der Ansicht FULL

Sie müssen die Ansicht FULL nicht explizit festlegen, da FULL der Standardwert ist. In den folgenden curl- und PowerShell-Beispielen wird die Ansicht FULL jedoch der Vollständigkeit halber als Abfrageparameter hinzugefügt.

curl

Um den Inhalt einer HL7v2-Nachricht mit der Ansicht FULL abzurufen, stellen Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Die Nachrichten-ID
  • FULL als view

Das folgende Beispiel zeigt eine GET-Anfrage mit 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/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=FULL"

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ],
  "parsedData": {
    "segments": [
      {
        ""segmentId": "SEGMENT_ID_1",
        "fields": {
          FIELDS_1
        }
      },
      {
        "segmentId": "SEGMENT_ID_2",
        "fields": {
          FIELDS_2
        }
      },
      {
        "segmentId": "SEGMENT_ID_3",
        "fields": {
          FIELDS_3
        }
      }
    ]
  }
}

PowerShell

Um den Inhalt einer HL7v2-Nachricht mit der Ansicht FULL abzurufen, stellen Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Die Nachrichten-ID
  • FULL als view

Das folgende Beispiel zeigt eine GET-Anfrage mit 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/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=FULL" | Select-Object -Expand Content

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ],
  "parsedData": {
    "segments": [
      {
        ""segmentId": "SEGMENT_ID_1",
        "fields": {
          FIELDS_1
        }
      },
      {
        "segmentId": "SEGMENT_ID_2",
        "fields": {
          FIELDS_2
        }
      },
      {
        "segmentId": "SEGMENT_ID_3",
        "fields": {
          FIELDS_3
        }
      }
    ]
  }
}

Go

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

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

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

	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, err := messagesService.Get(name).Do()
	if err != nil {
		return fmt.Errorf("Get: %w", err)
	}

	rawData, err := base64.StdEncoding.DecodeString(message.Data)
	if err != nil {
		return fmt.Errorf("base64.DecodeString: %w", err)
	}

	fmt.Fprintf(w, "Got HL7V2 message.\n")
	fmt.Fprintf(w, "Raw length: %d.\n", len(rawData))
	fmt.Fprintf(w, "Parsed data:\n")
	parsedJSON, _ := json.MarshalIndent(message.ParsedData, "", "  ")
	fmt.Fprintf(w, "%s", parsedJSON)
	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.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;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageGet {
  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 hl7v2MessageGet(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();

    // Create request and configure any parameters.
    Messages.Get request =
        client.projects().locations().datasets().hl7V2Stores().messages().get(hl7v2MessageName);

    // Execute the request and process the results.
    Message store = request.execute();
    System.out.println("HL7v2 message retrieved: \n" + store.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 getHl7v2Message = 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 name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${hl7v2MessageId}`;
  // Use the 'FULL' enum to include all of the message fields in the response.
  const view = 'FULL';
  const request = {name, view};

  const hl7v2Message =
    await healthcare.projects.locations.datasets.hl7V2Stores.messages.get(
      request
    );
  console.log('Got HL7v2 message:\n', hl7v2Message.data);
};

getHl7v2Message();

Python

def get_hl7v2_message(
    project_id, location, dataset_id, hl7v2_store_id, hl7v2_message_id
):
    """Gets an HL7v2 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
    hl7v2_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_message_name = "{}/datasets/{}/hl7V2Stores/{}/messages/{}".format(
        hl7v2_parent, dataset_id, hl7v2_store_id, hl7v2_message_id
    )

    msgs = client.projects().locations().datasets().hl7V2Stores().messages()
    message = msgs.get(name=hl7v2_message_name).execute()

    print("Name: {}".format(message.get("name")))
    print("Data: {}".format(message.get("data")))
    print("Creation time: {}".format(message.get("createTime")))
    print("Sending facility: {}".format(message.get("sendFacility")))
    print("Time sent: {}".format(message.get("sendTime")))
    print("Message type: {}".format(message.get("messageType")))
    print("Patient IDs:")
    patient_ids = message.get("patientIds")
    for patient_id in patient_ids:
        print("\tPatient value: {}".format(patient_id.get("value")))
        print("\tPatient type: {}".format(patient_id.get("type")))
    print("Labels: {}".format(message.get("labels")))

    print(message)
    return message

In der Ansicht RAW_ONLY

In den folgenden Beispielen wird gezeigt, wie Sie den Inhalt einer HL7v2-Nachricht mit der Ansicht RAW_ONLY abrufen, die alle Nachrichtenfelder außer parsedData enthält.

curl

Um den Inhalt einer HL7v2-Nachricht mit der Ansicht RAW_ONLY abzurufen, stellen Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Die Nachrichten-ID
  • RAW_ONLY als Ansicht festlegen

Das folgende Beispiel zeigt eine GET-Anfrage mit 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/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=RAW_ONLY"

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ]
}

PowerShell

Um den Inhalt einer HL7v2-Nachricht mit der Ansicht RAW_ONLY abzurufen, stellen Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Die Nachrichten-ID
  • RAW_ONLY als Ansicht festlegen

Das folgende Beispiel zeigt eine GET-Anfrage mit 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/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=RAW_ONLY" | Select-Object -Expand Content

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ]
}

In der Ansicht PARSED_ONLY

In den folgenden Beispielen wird gezeigt, wie Sie den Inhalt einer HL7v2-Nachricht mit der Ansicht PARSED_ONLY abrufen, die alle Nachrichtenfelder außer data enthält.

curl

Um den Inhalt einer HL7v2-Nachricht mit der Ansicht PARSED_ONLY abzurufen, stellen Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Die Nachrichten-ID
  • PARSED_ONLY als Ansicht festlegen

Das folgende Beispiel zeigt eine GET-Anfrage mit 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/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=PARSED_ONLY"

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ],
  "parsedData": {
    "segments": [
      {
        "segmentId": "SEGMENT_ID_1",
        "fields": {
          FIELDS_1
        }
      },
      {
        "segmentId": "SEGMENT_ID_2",
        "fields": {
          FIELDS_2
        }
      },
      {
        "segmentId": "SEGMENT_ID_3",
        "fields": {
          FIELDS_3
        }
      }
    ]
  }
}

PowerShell

Um den Inhalt einer HL7v2-Nachricht mit der Ansicht PARSED_ONLY abzurufen, stellen Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Die Nachrichten-ID
  • PARSED_ONLY als Ansicht festlegen

Das folgende Beispiel zeigt eine GET-Anfrage mit 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/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=PARSED_ONLY" | Select-Object -Expand Content

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ],
  "parsedData": {
    "segments": [
      {
        "segmentId": "SEGMENT_ID_1",
        "fields": {
          FIELDS_1
        }
      },
      {
        "segmentId": "SEGMENT_ID_2",
        "fields": {
          FIELDS_2
        }
      },
      {
        "segmentId": "SEGMENT_ID_3",
        "fields": {
          FIELDS_3
        }
      }
    ]
  }
}

In der Ansicht BASIC

In den folgenden Beispielen wird gezeigt, wie Sie den Inhalt einer HL7v2-Nachricht mit der Ansicht BASIC abrufen, die nur das Feld name enthält.

curl

Um den Inhalt einer HL7v2-Nachricht mit der Ansicht BASIC abzurufen, stellen Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Die Nachrichten-ID
  • BASIC als Ansicht festlegen

Das folgende Beispiel zeigt eine GET-Anfrage mit 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/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=BASIC"

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID"
}

PowerShell

Um den Inhalt einer HL7v2-Nachricht mit der Ansicht BASIC abzurufen, stellen Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Die Nachrichten-ID
  • BASIC als Ansicht festlegen

Das folgende Beispiel zeigt eine GET-Anfrage mit 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/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=BASIC" | Select-Object -Expand Content

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID"
}

HL7v2-Nachrichten auflisten

In den folgenden Beispielen wird gezeigt, wie die Nachrichten mithilfe der Methode in einem HL7v2-Speicher aufgelistet werden. Geben Sie den Abfrageparameter view mit einer der folgenden Optionen an, um die Informationen zu den einzelnen Nachrichten in der Liste zu bestimmen:

  • BASIC: Nur das Feld name wird eingeschlossen. Dies ist die Standardeinstellung.
  • RAW_ONLY: Schließen Sie alle Nachrichtenfelder mit Ausnahme des Felds parsedData ein.
  • PARSED_ONLY: Schließen Sie alle Nachrichtenfelder mit Ausnahme des Felds data ein.
  • FULL: Schließen Sie alle Nachrichtenfelder ein.

curl

Wenn Sie die Nachrichten in einem HL7v2-Speicher auflisten möchten, senden Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • view, BASIC, RAW_ONLY, PARSED_ONLY oder FULL oder weglassen, um den Standardwert BASIC zu verwenden

Das folgende Beispiel zeigt eine GET-Anfrage mit curl. In der Anfrage wird ?view=FULL angegeben, um alle Nachrichtenfelder einzuschließen.

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/hl7V2Stores/HL7V2_STORE_ID/messages?view=FULL"

Wenn die Anfrage erfolgreich ist, gibt der Server den HTTP-Statuscode 200 OK und ein Nachrichtenarray namens hl7_v2_messages zurück. Die folgende Beispielantwort ist abgeschnitten.

{
  "hl7_v2_messages": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
      "data": "DATA",
      "sendFacility": "SEND_FACILITY",
      "sendTime": "SEND_TIME",
      "messageType": "MESSAGE_TYPE",
      "createTime": "CREATE_TIME",
      ...
    },
    ...
  ]
}

PowerShell

Wenn Sie die Nachrichten in einem HL7v2-Speicher auflisten möchten, senden Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • view, BASIC, RAW_ONLY, PARSED_ONLY oder FULL oder weglassen, um den Standardwert BASIC zu verwenden

Das folgende Beispiel zeigt eine GET-Anfrage mit PowerShell. In der Anfrage wird ?view=FULL angegeben, um alle Nachrichtenfelder einzuschließen.

$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/hl7V2Stores/HL7V2_STORE_ID/messages?view=FULL" | Select-Object -Expand Content

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück. Die Beispielantwort ist abgeschnitten.

{
  "hl7_v2_messages": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
      "data": "DATA",
      "sendFacility": "SEND_FACILITY",
      "sendTime": "SEND_TIME",
      "messageType": "MESSAGE_TYPE",
      "createTime": "CREATE_TIME",
      ...
    },
    ...
  ]
}

Go

import (
	"context"
	"fmt"
	"io"

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

// listHL7V2Messages prints a list of HL7V2 messages to w.
func listHL7V2Messages(w io.Writer, projectID, location, datasetID, hl7V2StoreID string) error {
	ctx := context.Background()

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

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

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

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

	fmt.Fprintln(w, "HL7V2 messages:")
	for _, s := range resp.Hl7V2Messages {
		fmt.Fprintln(w, s.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.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.ListMessagesResponse;
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;

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

  public static void hl7v2MessageList(String hl7v2StoreName) throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");

    // 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 pageToken = null;

    do {
      // Create request and execute.
      ListMessagesResponse messageResponse =
          client
              .projects()
              .locations()
              .datasets()
              .hl7V2Stores()
              .messages()
              .list(hl7v2StoreName)
              .setPageSize(100)
              .setPageToken(pageToken)
              .execute();

      if (messageResponse.getHl7V2Messages() != null) {
        // Print results.
        System.out.printf(
            "Retrieved %s HL7v2 messages: \n", messageResponse.getHl7V2Messages().size());
        for (Message message : messageResponse.getHl7V2Messages()) {
          System.out.println(message);
        }
      }
      // Update the page token for the next request.
      pageToken = messageResponse.getNextPageToken();
    } while (pageToken != null);
  }

  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 listHl7v2Messages = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {parent};

  const response =
    await healthcare.projects.locations.datasets.hl7V2Stores.messages.list(
      request
    );
  const hl7v2Messages = response.data.hl7V2Messages;
  console.log(`HL7v2 messages: ${hl7v2Messages.length}`);
  for (const hl7v2Message of hl7v2Messages) {
    console.log(hl7v2Message);
  }
};

listHl7v2Messages();

Python

def list_hl7v2_messages(project_id, location, dataset_id, hl7v2_store_id):
    """Lists all the messages in the given HL7v2 store with support for
    filtering.

    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_messages_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    hl7v2_message_path = "{}/hl7V2Stores/{}".format(
        hl7v2_messages_parent, hl7v2_store_id
    )

    hl7v2_messages = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .list(parent=hl7v2_message_path)
        .execute()
        .get("hl7V2Messages", [])
    )

    for hl7v2_message in hl7v2_messages:
        print(hl7v2_message)

    return hl7v2_messages

Eine HL7v2-Nachricht löschen

In den folgenden Beispielen wird gezeigt, wie Sie eine HL7v2-Nachricht mit der Methode projects.locations.datasets.hl7V2Stores.messages.delete löschen.

curl

Um eine HL7v2-Nachricht zu löschen, senden Sie eine DELETE-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Die HL7v2-Nachrichten-ID

Das folgende Beispiel zeigt eine DELETE-Anfrage mit 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/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID"

Wenn die Anfrage erfolgreich ist, gibt der Server die leere Antwort im JSON-Format zurück:

{}

PowerShell

Um eine HL7v2-Nachricht zu löschen, senden Sie eine DELETE-Anfrage und geben Sie die folgenden Informationen an:

  • Name und Speicherort des übergeordneten Datasets
  • Der Name des HL7v2-Speichers
  • Die HL7v2-Nachrichten-ID

Das folgende Beispiel zeigt eine DELETE-Anfrage mit 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/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID" | Select-Object -Expand Content

Wenn die Anfrage erfolgreich ist, gibt der Server den leeren Antworttext im JSON-Format zurück:

{}

Go

import (
	"context"
	"fmt"
	"io"

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

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

	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)
	if _, err := messagesService.Delete(name).Do(); err != nil {
		return fmt.Errorf("Delete: %w", err)
	}

	fmt.Fprintf(w, "Deleted HL7V2 message: %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.Hl7V2Stores.Messages;
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;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageDelete {
  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 hl7v2MessageDelete(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();

    // Create request and configure any parameters.
    Messages.Delete request =
        client.projects().locations().datasets().hl7V2Stores().messages().delete(hl7v2MessageName);

    // Execute the request and process the results.
    request.execute();
    System.out.println("HL7v2 message 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 deleteHl7v2Message = 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 name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${hl7v2MessageId}`;
  const request = {name};

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

deleteHl7v2Message();

Python

def delete_hl7v2_message(
    project_id, location, dataset_id, hl7v2_store_id, hl7v2_message_id
):
    """Deletes an HL7v2 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
    hl7v2_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_message = "{}/datasets/{}/hl7V2Stores/{}/messages/{}".format(
        hl7v2_parent, dataset_id, hl7v2_store_id, hl7v2_message_id
    )

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .delete(name=hl7v2_message)
    )

    response = request.execute()
    print(f"Deleted HL7v2 message with ID: {hl7v2_message_id}")
    return response

Nächste Schritte