
How to Build Patient Report Search on AWS Without Scanning Every Record
Build a patient report search API using DynamoDB and Lambda. Handle date filters, pagination, report corrections, and access checks without exposing another patient’s records.
Series: Healthcare (8 articles)
- …
- 8How to Build Patient Report Search on AWS Without Scanning Every Record This article
A patient report search API can use DynamoDB to retrieve metadata for one authorized patient, filter by date or report type, and return results in pages. AWS Lambda checks the patient’s access before querying, while Amazon S3 stores the private documents. The search response returns report details and identifiers. A separate download endpoint checks current access before issuing a file link.
This design suits a patient portal where the first requirement is finding reports by date, category, and publication status.
1. Define what patients need to find
Imagine a patient has 146 reports accumulated over several years. They remember having a blood test in September but cannot recall the report filename.
A search box that only matches filenames would be difficult to use. A small set of filters can answer the request more reliably:
- A start date and end date.
- A report category, such as laboratory or imaging.
- The date of the clinical service.
- The date the clinic released the report.
- A clear indication when a report has been corrected.
Choose one default sort order and label it. For this example, the portal shows the most recent clinical service date first. The release date remains visible as a separate field.
The distinction helps when a clinic releases a report several days after the appointment. A patient searching for an October appointment should still find the report even if staff published it in November.
2. Store searchable metadata separately from PDFs
The portal needs metadata to find a report. Downloading and inspecting every PDF for each search would add delay and cost.
An illustrative metadata record looks like this:
{ "PK": "CLINIC#c42#PATIENT#p815", "SK": "REPORT#2026-09-18#r209", "reportId": "r209", "category": "LAB", "displayTitle": "Laboratory report", "serviceDate": "2026-09-18", "releasedAt": "2026-09-20T08:15:00Z", "publicationStatus": "READY", "currentVersion": "v3", "objectRef": "private-reference"}The partition key groups one patient’s report metadata within one clinic. The sort key supports date-range queries and distinguishes reports from the same day.
Use a consistent date representation. If the source provides a timestamp, define which clinical time zone determines its displayed service date. Store the underlying timestamp when the application needs it.
Keep patient names, diagnoses, and document text out of keys. Restrict access to the metadata because opaque references and report categories can still be sensitive.
3. Resolve patient access before building the query
Expose a route such as:
GET /me/reports?from=2026-09-01&to=2026-09-30&category=LABLambda obtains the account subject from validated authentication claims and resolves its active patient grants.
For a self-service patient, the server derives the patient reference. For a caregiver managing several patients, the selected patient reference is checked against the caregiver’s current grants.
The backend then:
- Validates the date range and category.
- Resolves the authorized clinic and patient.
- Builds the DynamoDB partition key on the server.
- Queries report metadata within that partition.
- Returns only records permitted by the publication policy.
Apply the same checks to every page request. A caregiver whose access expires between page one and page two should be denied further results.
4. Query the patient partition
The following Python helper illustrates the database operation. Authentication, input validation, response mapping, and cursor validation belong in the endpoint around it.
from boto3.dynamodb.conditions import Key, Attr
def query_report_page( table, *, authorized_partition, from_date, to_date, category=None, exclusive_start_key=None): filters = Attr("publicationStatus").eq("READY")
if category: filters = filters & Attr("category").eq(category)
query_args = { "KeyConditionExpression": ( Key("PK").eq(authorized_partition) & Key("SK").between( f"REPORT#{from_date}#", f"REPORT#{to_date}$" ) ), "FilterExpression": filters, "ScanIndexForward": False, "Limit": 25 }
if exclusive_start_key: query_args["ExclusiveStartKey"] = exclusive_start_key
result = table.query(**query_args)
return { "items": result.get("Items", []), "lastEvaluatedKey": result.get("LastEvaluatedKey") }The upper bound uses
$ immediately after the date so keys beginning with the same date followed by # remain inside the range. This depends on the exact key format shown above. Validate dates and keep the key convention consistent across all writers.The helper queries one authorized patient’s records. Its filter selects released reports and an optional category.
5. Handle pagination when filters remove results
DynamoDB applies the read limit before a filter expression. A page can therefore return fewer than 25 matching reports. It can even return zero matches while providing a continuation key.
Suppose the database reads 25 September reports:
Metadata read | Records |
|---|---|
Reports evaluated | 25 |
Reports still awaiting release | 3 |
Reports outside the selected category | 17 |
Matching released laboratory reports | 5 |
The portal receives five results and a continuation cursor. Display those results and allow the patient to load the next page.
If the product requires a fuller page, the backend can continue querying within a bounded request budget. Limit the number of internal pages and execution time. Preserve a continuation cursor if additional data remains.
For a growing portal where category filters are common, consider a data model that supports category and date in the key. Measure actual query patterns before adding indexes.
6. Protect the continuation cursor
A cursor should preserve the query context without letting the browser choose another partition.
Two practical options are:
- Store the continuation key on the server and return a short-lived random cursor ID.
- Return a signed cursor containing the continuation key, authorized subject, query filters, and expiry.
A signature detects modification. If the cursor contains identifiers that should remain concealed, use encryption or server-side storage.
When the next request arrives, recheck authorization and validate that the cursor belongs to the same subject and filters. Reject a cursor copied from another patient or a different search.
7. Return a deliberate search response
Map database items into the fields the interface needs.
{ "reports": [ { "reportId": "r209", "title": "Laboratory report", "serviceDate": "2026-09-18", "releasedAt": "2026-09-20T08:15:00Z", "category": "LAB", "version": "v3", "corrected": true } ], "nextCursor": "opaque-cursor"}Keep S3 keys and file credentials out of the listing response.
When the patient chooses Download, the backend loads the current report metadata again, verifies access and release status, and generates a short-lived URL for the approved version.
That extra check covers changes between search and download, including withdrawal or correction of a report.
8. Decide how corrected reports appear
A patient can become confused if the same test appears three times without explanation.
For this example, the normal list returns the current released report version. The portal marks it as corrected and shows the latest release date. Earlier versions remain subject to the clinic’s access and retention policies.
Keep a durable report identifier across corrections where the source workflow supports it. Record the current approved object version separately.
If the clinical service date changes during a correction, the key may need to move. Perform the metadata changes consistently so searches do not briefly return two current versions.
9. Test searches that can reveal a defect
Test | Expected result |
|---|---|
Another patient’s identifier is supplied | Server-side authorization prevents access |
First database page contains no matching reports | Continuation remains available when more records exist |
Date range includes several reports on the final day | All qualifying end-date records are eligible |
Cursor is reused after caregiver access expires | Request is denied |
Report is withdrawn after appearing in a list | Download is denied |
Corrected version is published | The current version appears according to clinic policy |
Use synthetic patients with overlapping dates and categories. Similar-looking records across two clinics make it easier to catch an authorization mistake.
Frequently asked questions
Can DynamoDB provide full-text search inside PDF reports?
This design searches structured metadata. Full-text search requires document extraction and a search service designed for text queries, along with authorization controls for indexed content.
Should I use a table scan for a small pilot?
A patient-specific query provides a clear access pattern from the beginning. It also keeps the endpoint’s database work scoped to the authorized patient.
Why can an empty page still have a next cursor?
The database may have evaluated records that the filter removed. Continue using the valid continuation key when the response indicates that more data remains.
Which metrics should I monitor?
Track query duration, records evaluated, matching records returned, empty pages with continuation, and failed authorization checks. These show when filters are becoming expensive or patients are struggling to find reports.
Implementation note — The code demonstrates one metadata query. Integrate authorization, signed or server-stored cursors, input validation, and synthetic-data tests before deployment.
Series: Healthcare (8 articles)
- …
- 8How to Build Patient Report Search on AWS Without Scanning Every Record This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article