Querying Compositions by Template and EHR

In this lesson, we will cover common AQL queries to filter compositions by template and by patient (EHR).

Filtering by Template

Let’s find the template ID from a composition. You can select it using the Ad-hoc query request from the query folder.

Using the request:

POST {{openehrBaseUrl}}/query/aql

And the query below in the body:

SELECT c/archetype_details/template_id/value FROM COMPOSITION c

Click Send, and it should return a 200 OK response along with the template IDs for each composition in the system.

Using the WHERE clause

To filter for only a specific template, for example vital_signs.v0, simply add a WHERE clause as shown below:

SELECT c/archetype_details/template_id/value FROM COMPOSITION c WHERE c/archetype_details/template_id/value = 'vital_signs.v0'

Filtering by EHR with CONTAINS clause

A composition is stored inside an EHR, not by itself. So when you query, you start at the EHR and then go to the composition.

SELECT e/ehr_id/value FROM EHR e CONTAINS COMPOSITION c

This query returns the ‘EHR ID’ for every EHR that has at least one composition.

To filter by the template ID, use the query below:

SELECT e/ehr_id/value, c
FROM EHR e CONTAINS COMPOSITION c
WHERE c/archetype_details/template_id/value = 'vital_signs.v0'

It returns every composition in the system created from a particular template (for example, vital_signs.v0), regardless of which EHR it belongs to.

Adding the EHR ID filter

When you want the query to return only compositions created from a particular template (for example, vital_signs.v0) within one specific EHR, use the query below:

SELECT e/ehr_id/value, c
FROM EHR e CONTAINS COMPOSITION c
WHERE c/archetype_details/template_id/value = 'vital_signs.v0'
AND e/ehr_id/value = 'ehrId'

Replace ehrId with the actual EHR ID, either pasted directly as a string, or referenced as an environment variable in Postman.

Lesson summary

In this lesson, we learned two essential AQL query patterns that you will use regularly in practice. First, we saw how to filter by template using the template_id in the WHERE clause to retrieve compositions created from a specific template.

Second, we learned how to filter by EHR (patient) by querying from EHR, using CONTAINS COMPOSITION, and restricting results with a specific ehr_id.

Comments (0)

No comments yet. Be the first to comment!