Creazione e gestione dei messaggi HL7v2

Questa pagina spiega come importare, creare, etichettare, elencare, visualizzare ed eliminare i messaggi HL7v2. I messaggi HL7v2 vengono utilizzati per trasmettere i dati clinici tra i sistemi. Un messaggio HL7v2 potrebbe contenere informazioni su un risultato di osservazione, una prescrizione da inviare a una farmacia, una transazione finanziaria o altri eventi clinici.

Panoramica della creazione e dell'importazione di messaggi HL7v2

Utilizza uno dei seguenti metodi per archiviare un messaggio HL7v2 nell'API Cloud Healthcare:

Quando utilizzi messages.ingest, il metodo genera una risposta contenente uno dei seguenti elementi:

  • Un messaggio di conferma HL7v2 (ACK) in caso di esito positivo
  • Un messaggio di conferma negativa (NACK) in caso di errore

I messaggi ACK e NACK vengono utilizzati per rispondere ai sistemi di interfaccia HL7v2 che prevedono questi conferme.

Importazione e creazione di messaggi con un adattatore MLLP

I messaggi HL7v2 vengono recapitati tra i sistemi di assistenza e l'API Cloud Healthcare utilizzando il protocollo MLLP (Minimo Lower Layer Protocol). Per ulteriori informazioni, consulta MLLP e l'adattatore MLLP della piattaforma Google Cloud. Per istruzioni su come configurare un adattatore MLLP per comunicare in modo sicuro con l'API Cloud Healthcare, consulta Trasmissione di messaggi HL7v2 su connessioni TCP/IP.

Importazione di messaggi HL7v2

Dopo che l'API Cloud Healthcare ha importato il messaggio da un sistema di assistenza sanitaria, l'API Cloud Healthcare genera una risposta contenente un campo hl7ack contenente un messaggio HL7v2 codificato in base64 con le seguenti caratteristiche:

  • Il tipo di messaggio è ACK.
  • La struttura di invio e la struttura ricevente vengono invertite, mentre la richiesta di invio e la richiesta di ricezione vengono annullate.
  • L'ora di invio del messaggio corrisponde all'ora corrente e viene generato un nuovo ID controllo.
  • Il valore del campo MSH-9.1 definisce il tipo di messaggio.
  • Il valore del campo MSA.1 definisce un tipo di risposta. Un tipo di risposta AA indica Application Accept, il che significa che il messaggio è stato convalidato e importato in modo corretto.
  • Il valore MSA.2 contiene l'ID di controllo del messaggio originale.

Gli esempi riportati di seguito mostrano come importare un messaggio HL7v2 utilizzando il metodo projects.locations.datasets.hl7V2Stores.messages.ingest.

curl

Per importare un messaggio HL7v2, effettua una richiesta POST e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • Un Message

Il seguente esempio mostra una richiesta POST mediante curl e un file JSON di esempio denominato 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"

La seguente risposta di esempio mostra hl7Ack e i dettagli del messaggio.

{
  "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

Per importare un messaggio HL7v2, effettua una richiesta POST e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • Un Message

Il seguente esempio mostra una richiesta POST mediante PowerShell e un file JSON di esempio denominato 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

La seguente risposta di esempio mostra hl7Ack e i dettagli del messaggio.

{
  "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

creazione di messaggi HL7v2

I seguenti esempi mostrano come creare un messaggio HL7v2 utilizzando il metodo projects.locations.datasets.hl7V2Stores.messages.create.

REST

Per creare un messaggio HL7v2, utilizza il metodo projects.locations.datasets.hl7V2Stores.messages.create.

Se hai bisogno di un file di messaggi HL7v2 da utilizzare con i comandi di esempio, puoi scaricare il file JSON hl7v2-sample.json.

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

  • PROJECT_ID: l'ID del tuo progetto Google Cloud
  • LOCATION: la posizione del set di dati
  • DATASET_ID: il set di dati padre dell'archivio HL7v2
  • HL7V2_STORE_ID: l'ID store HL7v2
  • HL7V2_MESSAGE_FILE: il percorso di un file in formato JSON contenente un messaggio HL7v2 sulla tua macchina locale

Per inviare la richiesta, scegli una delle seguenti opzioni:

arricciatura

Esegui questo comando:

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

PowerShell

Esegui questo comando:

$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

Explorer API

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

Quando si crea un messaggio utilizzando il file JSON hl7v2-sample.json, viene restituito il seguente output:

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

Separatori e codifica dei segmenti del messaggio HL7v2

Il separatore di segmento predefinito in HL7v2 è un ritorno a capo (\r). La maggior parte degli editor di testo utilizza i caratteri di nuova riga (\n) come separatori di segmento. Questo genera messaggi HL7v2 che non possono essere importati nell'API Cloud Healthcare utilizzando la configurazione predefinita. Per consentire a un archivio HL7v2 di importare i messaggi che utilizzano caratteri di nuova riga come separatori di segmento, consulta Impostare il carattere di terminazione dei segmenti.

Per convertire i caratteri di nuova riga di un file in ritorni a capo, esegui questo comando in una shell di Linux:

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

I metodi di importazione e creazione prevedono che i messaggi HL7v2 siano stringhe codificate in base64. Per convertire una stringa nella codifica Base64, esegui questo comando in una shell di Linux:

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

Impostazione del carattere di terminazione dei segmenti

Durante la creazione o l'importazione di dati, il formato del messaggio HL7v2 richiede che i segmenti vengano terminati utilizzando il carattere restituito \r. Puoi configurare un archivio HL7v2 per accettare messaggi HL7v2 con un carattere di terminazione non standard, ad esempio \n.

Prendi in considerazione il seguente messaggio HL7v2 che utilizza il valore predefinito \r come terminale di segmento. Questo messaggio è accettato per impostazione predefinita quando si crea un archivio HL7v2.

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

Il seguente messaggio è identico a quello precedente, ad eccezione del fatto che utilizza \n come carattere di terminazione dei segmenti:

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

Per archiviare il messaggio con il carattere di terminazione non standard, configura l'oggetto ParserConfig nell'archivio HL7v2 e imposta il campo segmentTerminator sulla codifica Base64 di \n.

I seguenti esempi mostrano come configurare segmentTerminator in ParserConfig quando crei un archivio HL7v2. Se disponi già di un archivio HL7v2, puoi modificarlo per fornire il corpo ParserConfig. Dopo aver impostato il carattere di terminazione dei segmenti, puoi creare o importare il messaggio.

curl

Per creare un archivio HL7v2 con il carattere di terminazione dei segmenti impostato su \n, effettua una richiesta POST e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • Un oggetto parserConfig con segmentTerminator impostato su Cg== (la codifica Base64 di \n)

Il seguente esempio mostra una richiesta POST che utilizza 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"

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

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

PowerShell

Per creare un archivio HL7v2 con il carattere di terminazione dei segmenti impostato su \n, effettua una richiesta POST e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • Un oggetto parserConfig con segmentTerminator impostato su Cg== (la codifica Base64 di \n)

L'esempio seguente mostra una richiesta POST mediante 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

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

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

Utilizzo di un'intestazione di segmento nulla

Un messaggio HL7v2 senza un segmento di intestazione del messaggio (MSH) ha un'intestazione di segmento nulla. In genere, un messaggio HL7v2 contiene un MSH che definisce metadati come origine, intent, scopo e destinazione del messaggio. L'MSH consente di cercare e filtrare i messaggi. Tuttavia, puoi archiviare i messaggi che non contengono un MSH configurando l'oggetto ParserConfig nell'archivio HL7v2 e impostare il campo allowNullHeader su true.

Il seguente messaggio di esempio contiene un segmento di identificazione del paziente (PID), ma non un segmento MSH:

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

I seguenti esempi mostrano come configurare allowNullHeader in ParserConfig quando crei un archivio HL7v2. Se disponi già di un archivio HL7v2, puoi modificarlo e fornire il corpo ParserConfig. Dopo aver impostato allowNullHeader su true, puoi creare o importare messaggi con intestazioni di segmento nulle.

curl

Per creare un archivio HL7v2 e archiviare i messaggi che non contengono un MSH, effettua una richiesta POST e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • Un oggetto parserConfig con allowNullHeader impostato su true

Il seguente esempio mostra una richiesta POST che utilizza 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"

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

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

PowerShell

Per creare un archivio HL7v2 e archiviare i messaggi che non contengono un MSH, effettua una richiesta POST e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • Un oggetto parserConfig con allowNullHeader impostato su true

L'esempio seguente mostra una richiesta POST mediante 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

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

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

Etichettare un messaggio HL7v2

Puoi aggiungere uno o più etichette chiave-valore a un messaggio. Un caso d'uso delle etichette è l'aggiunta di etichette di stato a un messaggio, in modo che un'applicazione possa eseguire query sui messaggi in base allo stato.

I seguenti esempi mostrano come aggiungere etichette a un messaggio HL7v2 utilizzando il metodo projects.locations.datasets.hl7V2Stores.messages.patch.

curl

Per aggiungere etichette a un messaggio HL7v2, effettua una richiesta PATCH e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • L'ID del messaggio
  • I dati delle etichette da aggiornare
  • Una maschera di aggiornamento

Il seguente esempio mostra una richiesta PATCH che utilizza 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"

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

{
  "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

Per aggiungere etichette a un messaggio HL7v2, effettua una richiesta PATCH e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • L'ID del messaggio
  • I dati delle etichette da aggiornare
  • Una maschera di aggiornamento

L'esempio seguente mostra una richiesta PATCH mediante 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

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

{
  "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

Recupero dei contenuti di un messaggio HL7v2

Gli esempi riportati di seguito mostrano come recuperare i contenuti di un messaggio HL7v2 utilizzando il metodo projects.locations.datasets.hl7V2Stores.messages.get. Per determinare le parti del messaggio da ricevere, fornisci al parametro di query view una delle seguenti opzioni:

  • BASIC: includi solo il campo name.
  • RAW_ONLY: includi tutti i campi del messaggio, tranne il campo parsedData.
  • PARSED_ONLY: includi tutti i campi del messaggio, tranne il campo data.
  • FULL: includi tutti i campi del messaggio. Questa è l'impostazione predefinita.

I seguenti esempi mostrano come ottenere i contenuti di un messaggio HL7v2 utilizzando le viste FULL, RAW_ONLY e PARSED_ONLY.

Utilizzo della vista FULL

Non è necessario impostare esplicitamente la vista FULL, poiché FULL è il valore predefinito. Tuttavia, nei seguenti esempi di curl e PowerShell, la vista FULL viene aggiunta come parametro di query per la completezza.

curl

Per ottenere i contenuti di un messaggio HL7v2 utilizzando la vista FULL, effettua una richiesta GET e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • L'ID del messaggio
  • FULL come view

Il seguente esempio mostra una richiesta GET che utilizza 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"

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

{
  "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

Per ottenere i contenuti di un messaggio HL7v2 utilizzando la vista FULL, effettua una richiesta GET e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • L'ID del messaggio
  • FULL come view

L'esempio seguente mostra una richiesta GET mediante 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

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

{
  "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

Utilizzo della vista RAW_ONLY

Gli esempi riportati di seguito mostrano come recuperare i contenuti di un messaggio HL7v2 utilizzando la visualizzazione RAW_ONLY, che include tutti i campi del messaggio tranne parsedData.

curl

Per ottenere i contenuti di un messaggio HL7v2 utilizzando la vista RAW_ONLY, effettua una richiesta GET e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • L'ID del messaggio
  • RAW_ONLY come visualizzazione

Il seguente esempio mostra una richiesta GET che utilizza 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"

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

{
  "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

Per ottenere i contenuti di un messaggio HL7v2 utilizzando la vista RAW_ONLY, effettua una richiesta GET e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • L'ID del messaggio
  • RAW_ONLY come visualizzazione

L'esempio seguente mostra una richiesta GET mediante 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

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

{
  "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"
    }
  ]
}

Utilizzo della vista PARSED_ONLY

Gli esempi riportati di seguito mostrano come recuperare i contenuti di un messaggio HL7v2 utilizzando la visualizzazione PARSED_ONLY, che include tutti i campi del messaggio tranne data.

curl

Per ottenere i contenuti di un messaggio HL7v2 utilizzando la vista PARSED_ONLY, effettua una richiesta GET e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • L'ID del messaggio
  • PARSED_ONLY come visualizzazione

Il seguente esempio mostra una richiesta GET che utilizza 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"

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

{
  "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

Per ottenere i contenuti di un messaggio HL7v2 utilizzando la vista PARSED_ONLY, effettua una richiesta GET e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • L'ID del messaggio
  • PARSED_ONLY come visualizzazione

L'esempio seguente mostra una richiesta GET mediante 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

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

{
  "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
        }
      }
    ]
  }
}

Utilizzo della vista BASIC

Gli esempi riportati di seguito mostrano come recuperare i contenuti di un messaggio HL7v2 utilizzando la vista BASIC, che include solo il campo name.

curl

Per ottenere i contenuti di un messaggio HL7v2 utilizzando la vista BASIC, effettua una richiesta GET e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • L'ID del messaggio
  • BASIC come visualizzazione

Il seguente esempio mostra una richiesta GET che utilizza 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"

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

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

PowerShell

Per ottenere i contenuti di un messaggio HL7v2 utilizzando la vista BASIC, effettua una richiesta GET e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • L'ID del messaggio
  • BASIC come visualizzazione

L'esempio seguente mostra una richiesta GET mediante 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

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON:

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

Elenco dei messaggi HL7v2

I seguenti esempi mostrano come elencare i messaggi in un archivio HL7v2 utilizzando il metodo. Per determinare le informazioni su ogni messaggio da includere nell'elenco, specifica il parametro di query view con una delle seguenti opzioni:

  • BASIC: includi solo il campo name. Questa è l'impostazione predefinita.
  • RAW_ONLY: includi tutti i campi del messaggio, tranne il campo parsedData.
  • PARSED_ONLY: includi tutti i campi del messaggio, tranne il campo data.
  • FULL: includi tutti i campi del messaggio.

curl

Per elencare i messaggi in un archivio HL7v2, effettua una richiesta GET e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • view, BASIC, RAW_ONLY, PARSED_ONLY o FULL, oppure ometti di utilizzare il valore predefinito di BASIC

Il seguente esempio mostra una richiesta GET che utilizza curl. La richiesta specifica ?view=FULL per includere tutti i campi del messaggio.

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"

Se la richiesta ha esito positivo, il server restituisce un codice di stato HTTP 200 OK e un array di messaggi denominato hl7_v2_messages. La seguente risposta di esempio è troncata.

{
  "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

Per elencare i messaggi in un archivio HL7v2, effettua una richiesta GET e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • view, BASIC, RAW_ONLY, PARSED_ONLY o FULL, oppure ometti di utilizzare il valore predefinito di BASIC

L'esempio seguente mostra una richiesta GET mediante PowerShell. La richiesta specifica ?view=FULL in modo da includere tutti i campi del messaggio.

$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

Se la richiesta ha esito positivo, il server restituisce la risposta in formato JSON. La risposta di esempio è troncata.

{
  "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

Eliminazione di un messaggio HL7v2

Gli esempi riportati di seguito mostrano come eliminare un messaggio HL7v2 utilizzando il metodo projects.locations.datasets.hl7V2Stores.messages.delete.

curl

Per eliminare un messaggio HL7v2, effettua una richiesta DELETE e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • L'ID del messaggio HL7v2

Il seguente esempio mostra una richiesta DELETE che utilizza 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"

Se la richiesta ha esito positivo, il server restituisce la risposta del corpo vuota in formato JSON:

{}

PowerShell

Per eliminare un messaggio HL7v2, effettua una richiesta DELETE e specifica le seguenti informazioni:

  • Il nome e la posizione del set di dati padre
  • Il nome dell'archivio HL7v2
  • L'ID del messaggio HL7v2

L'esempio seguente mostra una richiesta DELETE mediante 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

Se la richiesta ha esito positivo, il server restituisce il corpo della risposta vuoto in formato JSON:

{}

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

Passaggi successivi