Aidbox User Docs
Run Aidbox locallyRun Aidbox in SandboxTalk to us Ask community
  • Aidbox FHIR platform documentation
    • Features
    • Architecture
  • Getting Started
    • Run Aidbox in Sandbox
    • Run Aidbox locally
    • Run Aidbox on AWS
    • Upload Sample Data
  • Tutorials
    • CRUD, Search Tutorials
      • Delete data
      • Set up uniqueness in Resource
      • Search Tutorials
        • Custom SearchParameter tutorial
        • Create custom Aidbox Search resource
        • Multilingual search tutorial
        • Migrate from Aidbox SearchParameter to FHIR SearchParameter
        • Change sort order by locale collation
    • Bulk API Tutorials
      • 🎓Synthea by Bulk API
      • 🎓$dump-sql tutorial
    • Security & Access Control Tutorials
      • Allow patients to see their own data
      • Restrict operations on resource type
      • Relationship-based access control
      • Creating user & set up full user access
      • Restricting Access to Patient Data
      • Create and test access control
      • RBAC
        • Flexible RBAC built-in to Aidbox
        • RBAC with JWT containing role
        • RBAC with ACL
      • Set-up token introspection
      • Prohibit user to login
      • Debug access control
      • Managing Admin Access to the Aidbox UI Using Okta Groups
      • Run Multibox locally
      • How to enable labels-based access control
      • How to enable patient data access API
      • How to enable SMART on FHIR on Patient Access API
      • How to enable hierarchical access control
      • How to configure Audit Log
    • Terminology Tutorials
      • Load ICD-10 terminology into Aidbox
      • Uploading IG terminology content to external FHIR terminology server
    • Validation Tutorials
      • Upload FHIR Implementation Guide
        • Environment Variable
        • Aidbox UI
          • IG Package from Aidbox Registry
          • Public URL to IG Package
          • Local IG Package
        • Aidbox FHIR API
        • UploadFIG Tool
      • ISiK
      • Carin BB
      • US Core
      • Davinci Pdex
      • mCode
    • Integration Toolkit Tutorials
      • Postmark integration tutorial
      • Mailgun integration tutorial
    • Subscriptions Tutorials
      • AidboxTopicSubscription NATS tutorial
    • Other tutorials
      • Run Aidbox with FHIR R6
      • Migrate from Multibox to Aidbox
      • SDC with Custom Resources
      • How to create FHIR NPM package
      • Migrate from legacy licence portal to Aidbox portal
      • How to run Aidbox in GCP Cloud Run
  • Overview
    • Licensing and Support
    • Aidbox user portal
      • Projects
      • Licenses
      • Members
    • Aidbox UI
      • Aidbox Notebooks
      • REST Console
      • Database Console
      • Attrs stats
      • DB Tables
      • DB Queries
    • Versioning
    • Release Notes
    • Contact us
  • Configuration
    • Settings
    • Configure Aidbox and Multibox
    • Init Bundle
  • API
    • REST API
      • CRUD
        • Create
        • Read
        • Update
        • Patch
        • Delete
      • FHIR Search
        • SearchParameter
        • Include and Revinclude
        • Chaining
      • Aidbox Search
      • Bundle
      • History
      • $everything on Patient
      • Other
        • Aidbox & FHIR formats
        • Capability Statement
        • $document
        • Observation/$lastn
        • $validate
        • SQL endpoints
        • $matcho
        • $to-format
        • Aidbox version
        • Health check
    • Bulk API
      • Configure Access Policies for Bulk API
      • $dump
      • $dump-sql
      • $dump-csv
      • $export
      • $load & /fhir/$load
      • $import & /fhir/$import
      • aidbox.bulk data import
      • Bulk import from an S3 bucket
    • Batch/Transaction
    • GraphQL API
    • Other APIs
      • Plan API
        • Provider Directory API
          • Practitioner
          • PractitionerRole
          • Organization
          • OrganizationAffiliation
        • Plan API Overview
      • Archive/Restore API
        • create-archive
        • restore-archive
        • prune-archived-data
        • delete-archive
      • ETAG support
      • Cache
      • Changes API
      • RPC API
      • Sequence API
      • Encryption API
      • Batch Upsert
  • Modules
    • Profiling and validation
      • FHIR Schema Validator
        • Aidbox FHIR IGs Registry
        • Setup Aidbox with FHIR Schema validation engine
      • Skip validation of references in resource using request header
      • Asynchronous resource validation
    • Security & Access Control
      • Authentication Flows
        • Basic Auth
        • Client Credentials Grant
        • Resource Owner Grant
        • Authorization Code Grant
        • Implicit Grant
        • Two Factor Authentication
        • External OAuth 2.0 Providers
        • Token Exchange
      • External identity providers
        • Aidbox
        • Okta
        • Azure AD
        • Azure AD with certificate authentication
        • Keycloak
        • GitHub
        • Microsoft AD FS
        • Apple
      • Access Control
        • AccessPolicy
        • Evaluation engines
        • Role-Based Access Control (/RBAC)
        • Attribute-based Access Control (/ABAC)
        • Multitenancy
        • Access control lists (/ACL)
        • Access policy dev tool
        • AccessPolicy best practices
      • Audit
        • Audit Log
    • Observability
      • Getting started
        • Run Aidbox with OpenTelemetry locally
        • How to export telemetry to the OTEL collector
      • Logs
        • How-to guides
          • OpenTelemetry logs
          • Elastic Logs and Monitoring Integration
          • Datadog Log management integration
          • Loki Log management integration
        • Tutorials
          • Log analysis and visualization tutorial
          • Export logs to Datadog tutorial
        • Extending Aidbox Logs
        • Technical reference
          • Log appenders
          • Log transformations
          • Log Schema
          • OTEL logs exporter parameters
      • Metrics
        • How-to guides
          • How to export metrics to the OTEL collector
          • Use Aidbox Metrics Server
          • Set-up Grafana integration
        • Technical reference
          • OpenTelemetry Metrics
          • OTEL metrics exporter parameters
      • Traces
        • How to use tracing
        • OTEL traces exporter parameters
    • Subscriptions
      • Aidbox topic-based subscriptions
        • Kafka AidboxTopicDestination
        • Webhook AidboxTopicDestination
        • GCP Pub/Sub AidboxTopicDestination
        • Tutorial: produce QuestionnaireResponse to Kafka topic
      • Aidbox SubSubscriptions
    • Aidbox Forms
      • Getting started
      • Aidbox Forms Interface
      • Aidbox UI Builder
        • UI Builder Interface
        • Form creation
          • Form Settings
          • Widgets
          • Components
          • Versioning
          • Form customisation in Theme Editor
          • Form signature
          • How-to guides
            • How to: populate forms with data
            • How to extract data from forms
            • How to calculate form filling percentage
          • Multilingual forms
          • FHIRPath Editor
        • Import Questionnaire
        • Form sharing
        • Printing forms
          • Template-based PDF generation
        • FHIR versions
        • Offline forms
        • Embedding
          • Request Interception
        • Configuration
        • Forms multitenancy
        • Building reports using SQL on FHIR
        • Integration with external terminology servers
        • External FHIR servers as a data backend
        • Store attachments in S3-like storages
      • Access Control in Forms
      • Audit Logging in Forms
      • Aidbox Form Gallery
    • Define extensions
      • Extensions using StructureDefinition
      • Extensions using FHIRSchema
    • Custom Resources
      • Custom resources using FHIR Schema
      • Custom resources using StructureDefinition
      • Migrate to FHIR Schema
        • Migrate custom resources defined with Entity & Attributes to FHIR Schema
        • Migrate custom resources defined with Zen to FHIR Schema
    • Aidbox terminology module
      • Concept
        • $translate-concepts
        • Handling hierarchies using ancestors
      • ValueSet
        • ValueSet Expansion
        • ValueSet Code Validation
        • Create a ValueSet
      • CodeSystem
        • CodeSystem Concept Lookup
        • CodeSystem Subsumption testing
        • CodeSystem Code Composition
      • Import external terminologies
        • Import flat file (/CSV)
        • $import operation
        • Ready-to-use terminologies
      • $translate on ConceptMap
    • SQL on FHIR
      • Defining flat views with View Definitions
      • Query data from flat views
      • Reference
    • Integration toolkit
      • C-CDA / FHIR Converter
        • List of supported templates
          • Admission Diagnosis Section (/V3)
          • Advance Directives Section (/entries optional) (/V3)
          • Advance Directives Section (/entries required) (/V3)
          • Allergies and Intolerances Section (/entries optional) (/V3)
          • Allergies and Intolerances Section (/entries required) (/V3)
          • Assessment Section
          • Chief Complaint Section
          • Chief Complaint and Reason for Visit Section
          • Complications Section (/V3)
          • Course of Care Section
          • DICOM Object Catalog Section - DCM 121181
          • Default Section Rules
          • Discharge Diagnosis Section (/V3)
          • Document Header
          • Encounters Section (/entries optional) (/V3)
          • Encounters Section (/entries required) (/V3)
          • Family History Section (/V3)
          • Functional Status Section (/V2)
          • General Status Section
          • Goals Section
          • Health Concerns Section (/V2)
          • History of Present Illness Section
          • Hospital Consultations Section
          • Hospital Course Section
          • Hospital Discharge Instructions Section
          • Hospital Discharge Physical Section
          • Hospital Discharge Studies Summary Section
          • Immunizations Section (/entries optional) (/V3)
          • Immunizations Section (/entries required) (/V3)
          • Medical (/General) History Section
          • Medical Equipment Section (/V2)
          • Medications Administered Section (/V2)
          • Medications Section (/entries optional) (/V2)
          • Medications Section (/entries required) (/V2)
          • Mental Status Section (/V2)
          • Notes
          • Nutrition Section
          • Objective Section
          • Operative Note Fluids Section
          • Operative Note Surgical Procedure Section
          • Past Medical History (/V3)
          • Payers Section (/V3)
          • Plan of Treatment Section (/V2)
          • Postprocedure Diagnosis Section (/V3)
          • Preoperative Diagnosis Section (/V3)
          • Problem Section (/entries optional) (/V3)
          • Problem Section (/entries required) (/V3)
          • Procedure Description Section
          • Procedure Disposition Section
          • Procedure Estimated Blood Loss Section
          • Procedure Implants Section
          • Procedure Specimens Taken Section
          • Procedures Section (/entries optional) (/V2)
          • Procedures Section (/entries required) (/V2)
          • Reason for Visit Section
          • Results Section (/entries optional) (/V3)
          • Results Section (/entries required) (/V3)
          • Review of Systems Section
          • Social History Section (/V3)
          • Vital Signs Section (/entries optional) (/V3)
          • Vital Signs Section (/entries required) (/V3)
        • How to deploy the service
        • Producing C-CDA documents
        • How to customize conversion rules
      • HL7 v2 Integration
        • HL7 v2 integration with Aidbox Project
        • Mappings with lisp/mapping
      • X12 message converter
      • Analytics
        • Power BI
      • Mappings
      • Email Providers integration
        • Setup SMTP provider
    • SMARTbox | FHIR API for EHRs
      • Get started
        • Set up Smartbox locally
        • Deploy Smartbox with Kubernetes
      • (/g)(/10) Standardized API for patient and population services
      • The B11 Decision Support Interventions
        • Source attributes
        • Feedback Sections
      • How-to guides
        • Pass Inferno tests with Smartbox
        • Perform EHR launch
        • Pass Inferno Visual Inspection and Attestation
        • Revoke granted access
        • Set up EHR-level customization
        • Check email templates
        • Setup email provider
        • Register users
        • Set up SSO with Auth0
        • Publish Terms of Use link onto the documentation page
        • Find out what resources were exported during the $export operation
        • Find documentation endpoint
      • Background information
        • Considerations for Testing with Inferno ONC
        • Adding Clients for Inferno tests
        • Multitenancy approach
        • What is Tenant
        • Email templating
    • ePrescription
      • Getting started
      • Authentication with mTLS
      • Pharmacies synchronization
      • Prescribing
        • NewRx Message
        • CancelRx Message
        • How to test Callback
      • Directory
        • DirectoryDownload Message
        • GetProviderLocation Message
        • AddProviderLocation Message
        • UpdateProviderLocation Message
        • DisableProviderLocation Message
      • Medications
        • FDB
      • References
        • Environment Variables
      • Frequently Asked Questions
    • Other modules
      • MDM
        • Train model
        • Configure MDM module
        • Find duplicates: $match
        • Mathematical details
      • MCP
  • Database
    • Overview
    • Database schema
    • PostgreSQL Extensions
    • AidboxDB
      • HA AidboxDB
    • Tutorials
      • Migrate to AidboxDB 16
      • Working with pgAgent
  • File storage
    • AWS S3
    • GCP Cloud Storage
    • Azure Blob Storage
    • Oracle Cloud Storage
  • Deployment and maintenance
    • Deploy Aidbox
      • Run Aidbox on Kubernetes
        • Deploy Production-ready Aidbox to Kubernetes
        • Deploy Aidbox with Helm Charts
        • Highly Available Aidbox
        • Self-signed SSL certificates
      • Run Aidbox on managed PostgreSQL
      • How to inject env variables into Init Bundle
    • Backup and Restore
      • Crunchy Operator (/pgBackRest)
      • pg_dump
      • pg_basebackup
      • WAL-G
    • Indexes
      • Get suggested indexes
      • Create indexes manually
  • App development
    • Use Aidbox with React
    • Aidbox SDK
      • Aidbox JavaScript SDK
      • Apps
      • NodeJs SDK
      • Python SDK
    • Examples
  • Reference
    • FHIR Schema reference
    • Settings reference
      • General
      • FHIR
      • Security & Access Control
      • Modules
      • Database
      • Web Server
      • Observability
      • Zen Project
    • Environment variables
      • Aidbox required environment variables
      • Optional environment variables
      • AidboxDB environment variables
    • System resources reference
      • IAM Module Resources
      • SDC Module Resources
      • Base Module Resources
      • Bulk Module Resources
      • AWF Module Resources
      • Cloud Module Resources
      • HL7v2 Module Resources
      • SQL on FHIR Module Resources
    • Email Providers reference
      • Notification resource reference
      • Mailgun environment variables
      • Postmark environment variables
    • Aidbox Forms reference
      • FHIR SDC API
      • Aidbox SDC API
      • Generating Questionnaire from PDF API
    • Aidbox SQL functions
  • Deprecated
    • Deprecated
      • Zen-related
        • RPC reference
          • aidbox
            • mdm
              • aidbox.mdm/update-mdm-tables
              • aidbox.mdm/match
        • FTR
        • Aidbox configuration project
          • Run Aidbox locally using Aidbox Configuraiton project
          • Aidbox configuration project structure
          • Set up and use configuration projects
          • Enable IGs
          • Repository
          • Seed Import
          • Manage Indexes in Zen Project
          • Seed v2
          • 🎓Migrate to git Aidbox Configuration Projects
          • Aidbox Configuration project reference
            • Zen Configuration
            • Aidbox project RPC reference
            • aidbox.config/config
          • Custom resources using Aidbox Project
          • First-Class Extensions using Zen
          • Zen Indexes
        • US Core IG
          • US Core IG support reference
        • Workflow Engine
          • Task
            • Aidbox Built-in Tasks
            • Task Executor API
            • Task User API
          • Workflow
            • Workflow User API
          • Services
          • Monitoring
        • FHIR conformance Deprecated guides
          • Touchstone FHIR 4.0.1 basic server
          • Touchstone FHIR USCore ClinData
          • How to enable US Core IG
            • Start Aidbox locally with US Core IG enabled
            • Add US Core IG to a running Aidbox instance
          • HL7 FHIR Da Vinci PDex Plan Net IG
        • Terminology Deprecated Tutorials
          • Inferno Test-Suite US Core 3.1.1
        • API constructor (/beta)
        • zen-lang validator
          • Write a custom zen profile
          • Load zen profiles into Aidbox
        • FHIR topic-based subscriptions
          • Set up SubscriptionTopic
          • Tutorial: Subscribe to Topic (/R4B)
          • API Reference
            • Subscription API
        • 🏗️FHIR Terminology Repository
          • FTR Specification
          • Create an FTR instance
            • FTR from CSV
            • FTR from FHIR IG
            • FTR from FTR — Direct Dependency
            • FTR from FTR — Supplement
          • FTR Manifest
          • Load SNOMED CT into Aidbox
          • Load LOINC into Aidbox
          • Load ICD-10-CM into Aidbox
          • Load RxNorm into Aidbox
          • Load US VSAC Package to Aidbox
          • Import via FTR
        • Zen Search Parameters
      • Entity / Attribute
        • Entities & Attributes
        • First-Class Extensions using Attribute
        • Custom Resources using Entity
        • Working with Extensions
        • Aidbox Search Parameters
      • Forms
      • Other
        • Custom Search
        • SearchQuery
        • Subscribe to new Patient resource
        • App Development Deprecated Tutorials
          • Receive logs from your app
            • X-Audit header
          • Patient Encounter notification Application
        • Other Deprecated Tutorials
          • Resource generation with map-to-fhir-bundle-task and subscription triggers
          • APM Aidbox
          • Automatically archive AuditEvent resources in GCP storage guide
          • HL7 v2 pipeline with Patient mapping
          • How to migrate to Apline Linux
          • How to migrate transaction id to bigint
          • How to fix broken dates
          • Configure multi-tenancy
        • AidboxProfile
        • GCP Pub/Sub
Powered by GitBook
On this page
  • Prepare example data
  • Define search query with filtering
  • Define search query with JOIN
  • Add order-by into parameters
  • Include related resources
  • EXPLAIN ANALYZE
  • Debug SearchQuery

Was this helpful?

Edit on GitHub
  1. Deprecated
  2. Deprecated
  3. Other

SearchQuery

Managed SQL for Search API

PreviousCustom SearchNextSubscribe to new Patient resource

Last updated 13 days ago

Was this helpful?

With SearchQuery resource, you can define "managed" SQL for Search API with parameters, paging, sorting, and includes.

Parameter name
Description

_count

A number of records returned per page

_page

Controls pagination

_total

The maximum number of results returned by a search result

_timeout

Defines query timeout

join

Allows you to join related resources for search

order-by

Defines the ordering of the search results

includes

Allows you to predefine included resources

reverse

Includes resources that refer resources from your query

_explain=analyze

Helps to inspect the execution plan of a search query

If you want to use arbitrary SQL (e.g. LEFT JOIN), consider .

Prepare example data

We need some sample data to see the results of example queries. Let's create it. Copy the following snippet to the Aidbox REST Console.

POST /

type: transaction
entry:
- resource:
    id: pr-1
    name:
    - given: [Ted]
      family: 'Scott'
  request:
    method: POST
    url: "/Practitioner"

- resource:
    id: pr-2
    name:
    - given: [Tommy]
      family: 'Peterson'
  request:
    method: POST
    url: "/Practitioner"

- resource:
    id: org1
    name: 'Test hospital1'
  request:
    method: POST
    url: "/Organization"

- resource:
    id: org2
    name: 'Test hospital2'
  request:
    method: POST
    url: "/Organization"

- resource:
    id: patient1
    name:
    - given: [Max]
      family: Johnson
    gender: male
    managingOrganization: {resourceType: Organization, id: org1, display: 'Test hospital1'}
    birthDate: '1960-10-10'
  request:
    method: POST
    url: "/Patient"

- resource:
    id: patient2
    name:
    - given: [Alex]
      family: Smith
    gender: male
    managingOrganization: {resourceType: Organization, id: org2, display: 'Test hospital2'}
    birthDate: '1990-01-01'
  request:
    method: POST
    url: "/Patient"

- resource:
    id: enc1
    status: planned
    subject:
      resourceType: Patient
      id: patient1
    class:
      code: abc
  request:
    method: POST
    url: "/Encounter"

- resource:
    id: enc2
    status: finished
    subject:
      resourceType: Patient
      id: patient1
    class:
      code: abc
  request:
    method: POST
    url: "/Encounter"

- resource:
    id: enc3
    status: planned
    subject:
      resourceType: Patient
      id: patient2
    class:
      code: abc
  request:
    method: POST
    url: "/Encounter"

- resource:
    id: apt1
    description: "Test appointment 1"
    start: '2020-12-10T09:00:00Z'
    end: '2020-12-10T11:00:00Z'
    status: booked
    participant: [{ actor: { resourceType: Patient, id: patient1}, status: accepted},{ actor: { resourceType: Practitioner, id: pr-1}, status: accepted}]
  request:
    method: POST
    url: "/Appointment"

- resource:
    id: apt2
    description: "Test appointment 2"
    start: '2021-04-10T09:00:00Z'
    end: '2021-04-10T11:00:00Z'
    status: booked
    participant: [{ actor: { resourceType: Patient, id: patient2}, status: accepted}, { actor: { resourceType: Practitioner, id: pr-2}, status: accepted}]
  request:
    method: POST
    url: "/Appointment"
# Status: 200
resourceType: Bundle
type: transaction-response
id: '244'
entry:
  - resource:
      name:
        - given:
            - Ted
          family: Scott
      id: pr-1
      resourceType: Practitioner
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
    response:
      etag: '244'
      cache-control: no-cache
      last-modified: 'Mon, 19 Apr 2021 12:18:14 GMT'
      location: /Practitioner/pr-1/_history/244
      x-duration: 54
      x-request-id: c9481d21-a93e-4bbd-940e-d7221ad45110
      status: '201'
  - resource:
      name:
        - given:
            - Tommy
          family: Peterson
      id: pr-2
      resourceType: Practitioner
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
    response:
      etag: '244'
      cache-control: no-cache
      last-modified: 'Mon, 19 Apr 2021 12:18:14 GMT'
      location: /Practitioner/pr-2/_history/244
      x-duration: 14
      x-request-id: c9481d21-a93e-4bbd-940e-d7221ad45110
      status: '201'
  - resource:
      name: Test hospital1
      id: org1
      resourceType: Organization
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
    response:
      etag: '244'
      cache-control: no-cache
      last-modified: 'Mon, 19 Apr 2021 12:18:14 GMT'
      location: /Organization/org1/_history/244
      x-duration: 16
      x-request-id: c9481d21-a93e-4bbd-940e-d7221ad45110
      status: '201'
  - resource:
      name: Test hospital2
      id: org2
      resourceType: Organization
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
    response:
      etag: '244'
      cache-control: no-cache
      last-modified: 'Mon, 19 Apr 2021 12:18:14 GMT'
      location: /Organization/org2/_history/244
      x-duration: 11
      x-request-id: c9481d21-a93e-4bbd-940e-d7221ad45110
      status: '201'
  - resource:
      name:
        - given:
            - Max
          family: Johnson
      gender: male
      birthDate: '1960-10-10'
      managingOrganization:
        id: org1
        display: Test hospital1
        resourceType: Organization
      id: patient1
      resourceType: Patient
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
    response:
      etag: '244'
      cache-control: no-cache
      last-modified: 'Mon, 19 Apr 2021 12:18:14 GMT'
      location: /Patient/patient1/_history/244
      x-duration: 24
      x-request-id: c9481d21-a93e-4bbd-940e-d7221ad45110
      status: '201'
  - resource:
      name:
        - given:
            - Alex
          family: Smith
      gender: male
      birthDate: '1990-01-01'
      managingOrganization:
        id: org2
        display: Test hospital2
        resourceType: Organization
      id: patient2
      resourceType: Patient
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
    response:
      etag: '244'
      cache-control: no-cache
      last-modified: 'Mon, 19 Apr 2021 12:18:14 GMT'
      location: /Patient/patient2/_history/244
      x-duration: 11
      x-request-id: c9481d21-a93e-4bbd-940e-d7221ad45110
      status: '201'
  - resource:
      status: planned
      subject:
        id: patient1
        resourceType: Patient
      id: enc1
      resourceType: Encounter
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
    response:
      etag: '244'
      cache-control: no-cache
      last-modified: 'Mon, 19 Apr 2021 12:18:14 GMT'
      location: /Encounter/enc1/_history/244
      x-duration: 14
      x-request-id: c9481d21-a93e-4bbd-940e-d7221ad45110
      status: '201'
  - resource:
      status: finished
      subject:
        id: patient1
        resourceType: Patient
      id: enc2
      resourceType: Encounter
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
    response:
      etag: '244'
      cache-control: no-cache
      last-modified: 'Mon, 19 Apr 2021 12:18:14 GMT'
      location: /Encounter/enc2/_history/244
      x-duration: 9
      x-request-id: c9481d21-a93e-4bbd-940e-d7221ad45110
      status: '201'
  - resource:
      status: planned
      subject:
        id: patient2
        resourceType: Patient
      id: enc3
      resourceType: Encounter
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
    response:
      etag: '244'
      cache-control: no-cache
      last-modified: 'Mon, 19 Apr 2021 12:18:14 GMT'
      location: /Encounter/enc3/_history/244
      x-duration: 10
      x-request-id: c9481d21-a93e-4bbd-940e-d7221ad45110
      status: '201'
  - resource:
      end: '2020-12-10T11:00:00.000Z'
      start: '2020-12-10T09:00:00.000Z'
      status: booked
      description: Test appointment 1
      participant:
        - actor:
            id: patient1
            resourceType: Patient
          status: accepted
        - actor:
            id: pr-1
            resourceType: Practitioner
          status: accepted
      id: apt1
      resourceType: Appointment
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
    response:
      etag: '244'
      cache-control: no-cache
      last-modified: 'Mon, 19 Apr 2021 12:18:14 GMT'
      location: /Appointment/apt1/_history/244
      x-duration: 20
      x-request-id: c9481d21-a93e-4bbd-940e-d7221ad45110
      status: '201'
  - resource:
      end: '2021-04-10T11:00:00.000Z'
      start: '2021-04-10T09:00:00.000Z'
      status: booked
      description: Test appointment 2
      participant:
        - actor:
            id: patient2
            resourceType: Patient
          status: accepted
        - actor:
            id: pr-2
            resourceType: Practitioner
          status: accepted
      id: apt2
      resourceType: Appointment
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
    response:
      etag: '244'
      cache-control: no-cache
      last-modified: 'Mon, 19 Apr 2021 12:18:14 GMT'
      location: /Appointment/apt2/_history/244
      x-duration: 21
      x-request-id: c9481d21-a93e-4bbd-940e-d7221ad45110
      status: '201'

We created 2 patients, 2 practitioners, 3 encounters, 2 appointments, 2 Managing organizations that are linked to each other.

Define search query with filtering

Let's define the search query to search old patients by the partial match of the family name with the filtering by gender:

PUT /SearchQuery/q-1

# attach this query to Patient resource type
resource: {id: 'Patient', resourceType: 'Entity'}
# give alias to patient table
as: pt
# enable total query
total: true 
# basic query
query:
  where: "(pt.resource->>'birthDate')::date < '1980-01-01'"
  order-by: pt.id desc
params:
   gender:
     type: string
     where: "pt.resource->>'gender' = {{params.gender}}"
   family:
     type: string
     format: '% ?%'
     where: |
       aidbox_text_search(knife_extract_text(pt.resource, $$[["name","family"]]$$)) 
       ilike {{params.family}}

Now we can call this query with /alpha/<resourceType>?query=<query-name>&params....:

GET /alpha/Patient?query=q-1&_page=1&_count=3&_total=none

# 200
resourceType: Bundle
type: searchset
entry: [...]
query-sql: |
  SELECT *
  FROM "patient" pt
  WHERE /* query */ (pt.resource->>'birthDate')::date < '1980-01-01'
  ORDER BY pt.id desc
  LIMIT 100
query-timeout: 60000

You can use count and page parameters for paging and control total query (if enabled) with total parameter. Use _timeout parameter to set query timeout.

If the parameter is provided, another query will be generated on the fly:

GET /alpha/Patient?query=q-1&family=joh

# 200

resourceType: Bundle
type: searchset
entry: [...]
query-sql:
- | 
  SELECT *
  FROM \"patient\" pt
  WHERE /* query */ (pt.resource->>'birthDate')::date < '1980-01-01'
    AND /* family */ aidbox_text_search(knife_extract_text(pt.resource, $$[[\"name\",\"family\"]]$$)) 
    ilike ?\nORDER BY pt.id desc
    LIMIT 100"
- '% joh%'

Define search query with JOIN

Your parameters and basic query can use join attribute to join related resources for search:

PUT /SearchQuery/q-2

resource: {id: 'Encounter', resourceType: 'Entity'}
as: enc
query:
  order-by: pt.id desc
params:
   pt:
     type: string
     format: '% ?%'
     join:
       pt: 
         table: patient
         by: "enc.resource#>>'{subject,id}' = pt.id"
     where: |
        aidbox_text_search(knife_extract_text(pt.resource, $$[["name","family"]]$$)) 
        ilike {{params.pt}}
GET /alpha/Encounter?query=q-2&pt=joh

# 200
resourceType: Bundle
type: searchset
entry: [...]
query-sql:
-  |
  SELECT *
  FROM \"encounter\" enc
  JOIN \"patient\" pt
    ON enc.resource#>>'{subject,id}' = pt.id
  WHERE /* pt */ aidbox_text_search(knife_extract_text(pt.resource, $$[[\"name\",\"family\"]]$$)) 
   ilike ?
  ORDER BY pt.id desc\nLIMIT 100"
- '% joh%'

Add order-by into parameters

Both query and params support order-by. order-by in query has the least precedence. order-by in params are added in top-down order. e.g. order-by in first search parameter has the most precedence.

Example: create search query

PUT /SearchQuery/sq

as: ap
query:
  order-by: "ap.resource->>'start' ASC"
resource:
  id: 'Appointment'
  resourceType: 'Entity'
params:
  ord-dir:
    type: string
    format: '?'
    order-by: |
      CASE WHEN {{params.ord-dir}} = 'asc' THEN ap.resource->>'start' END ASC,
      CASE WHEN {{params.ord-dir}} = 'desc' THEN ap.resource->>'start' END DESC

Example: use this search query

GET /alpha/Appointment?query=sq&ord-dir=desc

#200

resourceType: Bundle
type: searchset
entry:
  - resource:
      start: '2021-04-02T16:02:50.996+03:00'
      # omitted
  - resource:
      start: '2021-02-02T16:02:50.997+03:00'
      # omitted
  - resource:
      start: '2020-02-02T16:02:50.997+03:00'
      # omitted
# omitted

Include related resources

You can predefine included resources for SearchQuery with includes property:

PUT /SearchQuery/inc

resourceType: SearchQuery
resource: {id: Encounter, resourceType: Entity}
as: enc
total: true
includes:
  # name for include
  subject:
    # path to reference
    path: [subject]
    # ref to resource
    resource: {id: Patient, resourceType: Entity}
    # nested includes
    includes:
      organization:
        path: [managingOrganization]
        resource: {id: Organization, resourceType: Entity}
query: {order-by: enc.id}
limit: 40

Use the created query:

GET /alpha/Encounter?query=inc

#200

resourceType: Bundle
type: searchset
entry:
  - resource:
      status: planned
      subject:
        id: patient1
        resourceType: Patient
      id: enc1
      resourceType: Encounter
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
  - resource:
      status: finished
      subject:
        id: patient1
        resourceType: Patient
      id: enc2
      resourceType: Encounter
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
  - resource:
      status: planned
      subject:
        id: patient2
        resourceType: Patient
      id: enc3
      resourceType: Encounter
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
  - resource:
      name:
        - given:
            - Max
          family: Johnson
      gender: male
      birthDate: '1960-10-10'
      managingOrganization:
        id: org1
        display: Test hospital1
        resourceType: Organization
      id: patient1
      resourceType: Patient
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
  - resource:
      name:
        - given:
            - Alex
          family: Smith
      gender: male
      birthDate: '1990-01-01'
      managingOrganization:
        id: org2
        display: Test hospital2
        resourceType: Organization
      id: patient2
      resourceType: Patient
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
  - resource:
      name: Test hospital1
      id: org1
      resourceType: Organization
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
  - resource:
      name: Test hospital2
      id: org2
      resourceType: Organization
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
query-sql:
  - |-
    SELECT enc.*
    FROM "encounter" enc
    ORDER BY enc.id
    LIMIT 40
query-timeout: 60000
total: 3
total-query:
  - |-
    SELECT count(*)
    FROM "encounter" enc

Reverse includes

To include resources that refer resources from your query, you can add reverse: true attribute:

PUT /SearchQuery/revinc

resourceType: SearchQuery
resource: {id: Patient, resourceType: Entity}
as: pt
total: true
includes:
  encounters:
    # means that reference going from Encounter to patient
    reverse: true
    path: [subject]
    resource: {id: Encounter, resourceType: Entity}
    where: "resource->>'status' = 'finished'"
limit: 40

Execute the created query

GET /alpha/Encounter?query=revinc

#200

resourceType: Bundle
type: searchset
entry:
  - resource:
      name:
        - text: Alex
      gender: male
      address:
        - city: New-York
      telecom:
        - value: fhir
      birthDate: '1988-04-16'
      id: b0cab43b-ba3e-4192-9ee6-851fb15ebc5f
      resourceType: Patient
      meta:
        lastUpdated: '2021-04-16T14:01:51.973363Z'
        createdAt: '2021-04-16T11:43:36.524830Z'
        versionId: '143'
  - resource:
      name:
        - given:
            - Max
        - family: Smith
      gender: male
      address:
        - city: Hello
          line:
            - 123 Oxygen St
          state: NY
          district: World
          postalCode: '3212'
      telecom:
        - use: home
        - use: work
          rank: 1
          value: (32) 8934 1234
          system: phone
      birthDate: '1960-10-10'
      id: 6e690b70-c55d-4efc-89d4-38257d37a774
      resourceType: Patient
      meta:
        lastUpdated: '2021-04-19T09:35:48.183189Z'
        createdAt: '2021-04-19T09:35:48.183189Z'
        versionId: '163'
  - resource:
      name:
        - given:
            - Max
          family: Johnson
      gender: male
      birthDate: '1960-10-10'
      managingOrganization:
        id: org1
        display: Test hospital1
        resourceType: Organization
      id: patient1
      resourceType: Patient
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
  - resource:
      name:
        - given:
            - Alex
          family: Smith
      gender: male
      birthDate: '1990-01-01'
      managingOrganization:
        id: org2
        display: Test hospital2
        resourceType: Organization
      id: patient2
      resourceType: Patient
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
  - resource:
      status: finished
      subject:
        id: patient1
        resourceType: Patient
      id: enc2
      resourceType: Encounter
      meta:
        lastUpdated: '2021-04-19T12:18:14.183626Z'
        createdAt: '2021-04-19T12:18:14.183626Z'
        versionId: '244'
query-sql:
  - |-
    SELECT pt.*
    FROM "patient" pt
    LIMIT 40
query-timeout: 60000
total: 4
total-query:
  - |-
    SELECT count(*)
    FROM "patient" pt

Path in includes

Path expression in includes is json_knife extension path, it consists of strings, integers, and objects. If the item is path string, it means get key in object (arrays are implicitly flattened). If key is integer, it is interpreted as index in array. If key is object, it is pattern to filter values in array with inclusion semantic (like PostgreSQL JSONB operator @>).

Here is an example of how to extract a patient (code: PART) from the appointment:

The following example is prepared to be executed in the DB Console

select knife_extract(
  '{
     "resourceType" : "Appointment",
     "status" : "active",
     "participant" : [ {
       "type" : [ {
         "text" : "Patient",
         "coding" : [ {
           "code" : "PART"
         } ]
       } ],
       "actor" : {
         "id" : "patient2",
         "resourceType" : "Patient"
       },
       "status" : "active"
     }, {
       "type" : [ {
         "text" : "Admit",
         "coding" : [ {
           "code" : "ADM"
         } ]
       } ],
       "actor" : {
         "id" : "pr-2",
         "resourceType" : "Practitioner"
       },
       "status" : "active"
     } ]
   }',
   '[["participant", {"type": [{"coding": [{"code": "PART"}]}]}, "actor"]]'
)
knife_extract
- '{"id": "patient2", "resourceType": "Patient"}'

Parametrised includes

Include query can be parametrised if you define include inside params. You can use where key to add additional filter on included resources.

PUT /SearchQuery/cond-incl

resource: {id: 'Patient', resourceType: 'Entity'}
as: pt
query:
  order-by: pt.id desc
params:
   obs-cat:
     type: string
     includes: 
        obs:
          reverse: true
          path: ["patient"]
          resource: {id: 'Observation', resourceType: 'Entity'}
          where: "resource#>>'{category,0,coding,0,code}' = {{params.category}}"
          
---

GET /alpha/Patient?query=cond-incl&category=labs
# will add filtered include

GET /alpha/Patient?query=cond-incl
# will skip include

If you want to provide default include, define include with the same key on query level and in parameter. Parameter include will override the default in case parameter is provided in the request.

PUT /SearchQuery/cond-incl

resource: {id: 'Patient', resourceType: 'Entity'}
as: pt
query:
  order-by: pt.id desc
includes:
  # default include with filter
  obs:
    reverse: true
    path: ["patient"]
    resource: {id: 'Observation', resourceType: 'Entity'}
    where: "resource#>>'{category,0,coding,0,code}' = 'default"

params:
   obs-cat:
     type: string
     # override default include
     includes: 
        obs:
          where: "resource#>>'{category,0,coding,0,code}' = {{params.category}}"
          

EXPLAIN ANALYZE

With the parameter _explain=analyze , you can inspect the execution plan of a search query:

GET /alpha/Encounter?query=q-2&pt=joh&_explain=analyze

# 200

query: |-
  EXPLAIN ANALYZE SELECT *FROM \"encounter\" enc
  JOIN \"patient\" pt
    ON enc.resource#>>'{subject,id}' = pt.id
  WHERE /* pt */ aidbox_text_search(knife_extract_text(pt.resource, $$[[\"name\",\"family\"]]$$)) 
    ilike ?
    ORDER BY pt.id desc
    LIMIT 100"
params: ['% joh%']
explain: |-
  Limit  (cost=1382.90..1382.97 rows=28 width=882) (actual time=4.274..4.274 rows=0 loops=1)
    ->  Sort  (cost=1382.90..1382.97 rows=28 width=882) (actual time=4.272..4.272 rows=0 loops=1)
          Sort Key: pt.id DESC
          Sort Method: quicksort  Memory: 25kB
          ->  Hash Join  (cost=951.07..1382.23 rows=28 width=882) (actual time=4.247..4.248 rows=0 loops=1)
                Hash Cond: ((enc.resource #>> '{subject,id}'::text[]) = pt.id)
                ->  Seq Scan on encounter enc  (cost=0.00..421.60 rows=3460 width=839) (actual time=0.779..1.544 rows=3460 loops=1)
                ->  Hash  (cost=950.95..950.95 rows=10 width=38) (actual time=1.375..1.375 rows=1 loops=1)
                      Buckets: 1024  Batches: 1  Memory Usage: 9kB
                      ->  Seq Scan on patient pt  (cost=0.00..950.95 rows=10 width=38) (actual time=1.370..1.371 rows=1 loops=1)
                            Filter: (immutable_wrap_ws(immutable_unaccent(immutable_array_to_string(knife_extract_text(resource, '[["name", "family"]]'::jsonb), ' '::text))) ~~* '% joh%'::text)
                            Rows Removed by Filter: 1
  Planning Time: 9.345 ms
  Execution Time: 4.564 ms
total-query: "EXPLAIN ANALYZE SELECT count(*)\nFROM \"encounter\" enc\nJOIN \"patient\" pt\n  ON enc.resource#>>'{subject,id}' = pt.id\nWHERE /* pt */ aidbox_text_search(knife_extract_text(pt.resource, $$[[\"name\",\"family\"]]$$)) \nilike ?"
total-explain: |-
  Aggregate  (cost=1382.30..1382.31 rows=1 width=8) (actual time=3.257..3.257 rows=1 loops=1)
    ->  Hash Join  (cost=951.07..1382.23 rows=28 width=0) (actual time=3.254..3.254 rows=0 loops=1)
          Hash Cond: ((enc.resource #>> '{subject,id}'::text[]) = pt.id)
          ->  Seq Scan on encounter enc  (cost=0.00..421.60 rows=3460 width=772) (actual time=0.286..0.910 rows=3460 loops=1)
          ->  Hash  (cost=950.95..950.95 rows=10 width=5) (actual time=1.198..1.199 rows=1 loops=1)
                Buckets: 1024  Batches: 1  Memory Usage: 9kB
                ->  Seq Scan on patient pt  (cost=0.00..950.95 rows=10 width=5) (actual time=1.195..1.195 rows=1 loops=1)
                      Filter: (immutable_wrap_ws(immutable_unaccent(immutable_array_to_string(knife_extract_text(resource, '[["name", "family"]]'::jsonb), ' '::text))) ~~* '% joh%'::text)
                      Rows Removed by Filter: 1
  Planning Time: 6.716 ms
  Execution Time: 3.543 ms

Debug SearchQuery

You can debug SearchQuery with multiple parameters combinations without saving resource by POST /SearchQuery/$debug. You can simulate requests with different parameters by tests attribute. Aidbox will return results and explanation for each test:

POST /SearchQuery/$debug

# explain all queries
explain: true
# timeout for query in ms
timeout: 2000
# test with requests
tests: 
  # name of request
  only-pid:
    # params for request
    params: {pid: 'patient1'}
  only-ts:
    params: {ts: '2019-01-01'}
  both:
    params: {pid: 'patient1', ts: 'ups'}
# SearchQuery defnition
query:
  resource: {id: Patient, resourceType: Entity}
  as: pt
  params:
    pid: {type: string, isRequired: true, where: 'pt.id = {{params.pid}}'}
    ts: {type: date, where: 'pt.tis >= {{params.date}}'}
  query: {order-by: pt.ts desc}
  limit: 40
  
  
  # 200
  
only-pid:
  params:
    pid: patient1
    _timeout: 2000
  result:
    resourceType: Bundle
    type: searchset
    entry:
      - resource:
          name:
            - given:
                - Max
              family: Johnson
          gender: male
          birthDate: '1960-10-10'
          managingOrganization:
            id: org1
            display: Test hospital1
            resourceType: Organization
          id: patient1
          resourceType: Patient
          meta:
            lastUpdated: '2021-04-19T12:18:14.183626Z'
            createdAt: '2021-04-19T12:18:14.183626Z'
            versionId: '244'
    query-timeout: 2000000
  explain:
    query: |-
      EXPLAIN ANALYZE SELECT * FROM "patient" pt
      WHERE /* pid */ pt.id = ?
      ORDER BY pt.ts desc
      LIMIT 40
    params:
      - patient1
    explain: >-
      Limit  (cost=8.18..8.18 rows=1 width=124) (actual time=0.089..0.236 rows=1
      loops=1)

        ->  Sort  (cost=8.18..8.18 rows=1 width=124) (actual time=0.074..0.101
      rows=1 loops=1)

              Sort Key: ts DESC

              Sort Method: quicksort  Memory: 25kB

              ->  Index Scan using patient_pkey on patient pt  (cost=0.15..8.17
      rows=1 width=124) (actual time=0.037..0.053 rows=1 loops=1)

                    Index Cond: (id = 'patient1'::text)

      Planning Time: 0.185 ms

      Execution Time: 0.302 ms
only-ts:
  status: error
  params:
    ts: '2019-01-01'
    _timeout: 2000
  errors:
    - details: Parameter pid is required
both:
  params:
    pid: patient1
    ts: ups
    _timeout: 2000
  result:
    status: error
    query:
      - |-
        SELECT pt.*
        FROM "patient" pt
        WHERE /* pid */ pt.id = ?
          AND /* ts */ pt.tis >= ?
        ORDER BY pt.ts desc
        LIMIT 40
      - patient1
      - null
    error: |-
      ERROR: column pt.tis does not exist
        Hint: Perhaps you meant to reference the column "pt.ts".
        Position: 73
AidboxQuery