search

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 26, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

README

Registry-driven FHIR search for the haistack monorepo.

What it does

haistack-search is the FHIR search library for HAIStack. It turns registry SearchParameter definitions into typed index rows, parses FHIR query strings, plans lookups against those rows, and returns bundle-ready results.

Think of it as two pipelines:

Pipeline What happens
Write path (indexing) Read enabled SearchParameter metadata from pkg/registry, evaluate FHIRPath expressions on each resource, normalize values into typed field keys, emit store.SearchIndexEntry rows
Read path (search) Parse query params → resolve against registry → build a lookup plan → execute via store.SearchQueryExecutor → load resources and assemble a search bundle

Main components:

Component Role
SnapshotRegistry Wraps a registry snapshot; exposes all registry-backed search parameters
RegistryIndexer search.Indexer for pkg/core write-path indexing
ParseQuery / ResolveQuery / BuildPlan Parse FHIR params and plan typed index lookups
Planner / NewPlanner Default plan builder used by Service
StoreExecutor Execute plans via store.SearchQueryExecutor + sort/pagination
Service High-level entrypoint: Search, SearchRequest, SearchBundle
ReindexWorker / ReindexJobRunner / ReindexNotifier Rebuild index rows and enqueue jobs on registry changes

It implements search logic on top of pkg/store contracts. Backends (pkg/postgres, pkg/sqlite) persist index rows and run lookups; this package does not open databases directly.

It does not:

  • Parse raw FHIR JSON or assign version IDs (pkg/types, pkg/core)
  • Store resources or run SQL (pkg/postgres, pkg/sqlite)
  • Serve HTTP search endpoints (pkg/http delegates here)
  • Compile or install registry definitions (pkg/registry)

How it fits in the ecosystem

  pkg/registry (Snapshot / SearchParameter metadata)
           |
           v
  SnapshotRegistry  +  pkg/fhirpath (expression evaluation)
           |
     +-----+-----+
     v           v
 RegistryIndexer   ParseQuery / ResolveQuery / BuildPlan
 (write path)              |
     |                     v
     v              StoreExecutor / Service (read path)
 store.SearchStore          |
     ^                      v
     |              store.ResourceStore (load hits)
 pkg/core (Indexer hook)     |
     |                      v
 pkg/postgres / pkg/sqlite   bundle-ready Result / SearchBundle
 (typed index tables)              |
                                   v
                            pkg/http SearchServiceAdapter
Direction Package Relationship
Upstream registry Enabled resource types, search parameter codes, FHIRPath expressions
Upstream fhirpath Evaluate expressions during indexing
Upstream store SearchStore, SearchQueryExecutor, ResourceStore contracts
Downstream core Calls Indexer.Build on accepted writes
Downstream http Type-level GET/POST search via SearchService adapter
Downstream subscriptions ParseQuery + MatchResourceParameter for FHIR Subscription.criteria
Sidecar postgres / sqlite Index persistence and lookup execution

When to use it

  • Indexing resources on create/update/delete through pkg/core
  • Executing FHIR search queries against Postgres-backed typed indexes
  • Rebuilding search indexes after registry or SearchParameter changes
  • Tests that need real parse/plan/execute behavior without HTTP
  • Matching resources against simple search criteria inside subscription triggers

Usage modes

1. Registry snapshot for parameters and indexing

Wrap a compiled registry snapshot before wiring indexing or search:

import (
    "github.com/degoke/haistack/pkg/registry"
    "github.com/degoke/haistack/pkg/search"
)

snapshot, _ := manager.RebuildSnapshot(ctx)
reg := search.NewSnapshotRegistry(snapshot)
params := reg.SearchParametersFor("Patient")
enabled := reg.EnabledResourceTypes()
2. Write-path indexing in pkg/core
import (
    "github.com/degoke/haistack/pkg/core"
    "github.com/degoke/haistack/pkg/fhirpath"
)

engine := fhirpath.NewEngine(/* … */)
indexer, err := search.NewRegistryIndexer(search.RegistryIndexerConfig{
    Registry: reg,
    Engine:   engine,
})

svc, err := core.NewResourceService(core.ResourceServiceConfig{
    Resources: tdb.ResourceStore(),
    History:   tdb.HistoryStore(),
    Sessions:  tdb,
    Indexer:   indexer,
})

On each accepted write, core calls Indexer.Build and persists the returned entries through SearchStore.

3. High-level search execution (Service)
import "net/url"

searchSvc, err := search.NewService(search.ServiceConfig{
    Registry:  reg,
    Executor:  search.NewStoreExecutor(tdb.SearchStore(), tdb.ResourceStore()),
    Resources: tdb.ResourceStore(),
    BaseURL:   "https://example.com/fhir", // optional paging links
})

params := url.Values{}
params.Set("name", "Smith")
result, err := searchSvc.Search(ctx, "Patient", params)
bundle, err := searchSvc.SearchBundle(ctx, "Patient", params)

ServiceConfig.Planner is optional; when nil, NewPlanner() is used.

4. Low-level parse, resolve, and plan (tests and tooling)
parsed, err := search.ParseQuery("Patient", params)
resolved, err := search.ResolveQuery(reg, "Patient", parsed)
plan, err := search.BuildPlan(reg, "Patient", params)
execResult, err := executor.Execute(ctx, plan)

Use this path when you need to inspect intermediate structures or inject a custom Executor without Service.

5. Reindex after registry changes
manager := registry.NewManager(registry.Config{
    Definitions:   db.DefinitionStore(),
    Installs:      tdb.RegistryInstallStore(),
    SearchReindex: search.NewReindexNotifier(tdb.JobStore()),
})

worker := &search.ReindexWorker{
    Registry:  reg,
    Indexer:   indexer,
    Resources: tdb.ResourceStore(),
    Search:    tdb.SearchStore(),
}
runner := &search.ReindexJobRunner{Jobs: tdb.JobStore(), Worker: worker}
processed, err := runner.RunOnce(ctx)

EnableResource and InstallDefinition on the registry manager enqueue reindex jobs when SearchReindex is configured.

6. Parameter discovery for UIs and validators
params := searchSvc.SearchParametersFor("Patient") // []search.ParameterInfo
enabled := searchSvc.EnabledResourceTypes()

Unknown parameter codes return search.UnknownParamError with a structured Code field (search.UnknownParamCode).

Examples

Chained and advanced query (Postgres backend):

params := url.Values{}
params.Set("subject.name", "Smith")
params.Set("_include", "Observation:subject")
params.Set("_sort", "-date")
params.Set("_count", "25")
result, err := searchSvc.Search(ctx, "Observation", params)

Count-only summary:

params := url.Values{}
params.Set("_summary", "count")
result, err := searchSvc.Search(ctx, "Patient", params)
// result.Total set, result.Entries empty

Match a resource against one search parameter (subscriptions-style):

matched, known := search.MatchResourceParameter(ctx, reg, engine, "Patient", envelope, "active", []string{"true"})

Supported search features

Postgres-first advanced FHIR search:

Feature Status
Registry-backed parameters All installed SearchParameters for enabled resource types
_count / _offset Paging with max _count of 100
_sort Registry-backed fields plus _id and _lastUpdated
Modifiers string:exact, string:contains; uri:below, uri:above; token/reference modifiers per type
Prefixes Date/number comparators: eq, ne, gt, ge, lt, le, sa, eb, ap
Chained search Up to two hops (e.g. subject.name, subject.organization.name)
Reverse chaining _has:Type:ref:param (one extra nested _has)
_include / _revinclude Direct includes plus ResourceType:* and *:* wildcards
Composite search Declared composite SearchParameters from registry
_summary / _elements Response projection at assembly time
Full text Postgres native FTS via indexed text.* documents
Reindexing Background jobs on registry SearchParameter changes

Unsupported semantics return explicit errors (ErrUnsupportedFeature, ErrInvalidQuery).

Query semantics

  • Repeated parameters AND together (?name=Smith&birthdate=1980-01-01)
  • Comma-separated values OR within one occurrence (?name=Smith,Jones)
  • _count and _offset apply to primary matches only (not included resources)
  • _sort uses registry metadata; tiebreak on resource id
  • Chain depth is limited to 2 hops; _include:iterate remains unsupported

Index field keys

RegistryIndexer normalizes extracted values into typed keys consumed by store.SearchStore:

Prefix Example key Stored as
token.* token.status Code/system/value tokens
string.* string.family Normalized strings
date.* date.birthdate Comparable date strings
reference.* reference.patient Reference targets (typed/id/canonical forms)
uri.* uri.url Canonical/URI strings (stored with string indexes)
composite.* composite.context-type-value Composite component values
text.* text.document Postgres full-text document

See pkg/sqlite and pkg/postgres for how backends route keys to tables.

Configuration / key types

Type Role
Registry Search parameter metadata and enablement
Indexer Interface implemented by RegistryIndexer
Executor Plan execution (StoreExecutor)
Planner PlanSearch from registry + params
ServiceConfig Registry, Executor, Planner, Resources, BaseURL
Request Structured search input for SearchRequest
Result Entries, total, links, summary mode

Sentinel errors: ErrUnknownParam, ErrUnsupportedParam, ErrUnsupportedFeature, ErrInvalidQuery, ErrResourceTypeDisabled, ErrProjectionFailed.

Where it fits

Layer Role
registry Bundled SearchParameters and enablement snapshot
fhirpath Expression evaluation for indexing
search Index extraction, query parse/plan/execute, reindex
store Search index persistence and lookup contracts
postgres Primary execution backend (LookupMatch, FieldValues)
sqlite Index persistence + lookups for tests and embedded nodes
core Write pipeline; plugs in search.Indexer
http REST search endpoints via adapter

Limits

  • Postgres is the primary complete execution backend; SQLite stores indexes and supports basic lookups but not the full advanced execution surface
  • Chain depth is limited to 2; recursive _include:iterate is deferred
  • OpenSearch adapter seam is preserved via SearchAdvancedExecutor; not implemented yet
  • No HTTP routing in this package — use pkg/http
  • Custom SearchParameters become searchable after snapshot rebuild and reindex completion
  • Max _count is 100 at the service layer

Documentation

Overview

Package search implements haistack-search: registry-driven FHIR search indexing, query parsing/planning, Postgres execution, and bundle-ready search results.

Architecture

haistack-search is the FHIR search library for HAIStack. It keeps reusable lower-level components in this package while exposing search.Service as the main entrypoint for advanced search execution.

  • Registry / SnapshotRegistry — resolve enabled SearchParameters from haistack-registry
  • RegistryIndexer — search.Indexer implementation for pkg/core write-path indexing
  • ParseQuery / ResolveQuery / BuildPlan — parse and plan FHIR query params
  • StoreExecutor — execute typed index lookups via store.SearchQueryExecutor
  • Service — high-level search execution returning bundle-ready Result values
  • ReindexWorker / ReindexJobRunner / ReindexNotifier — rebuild index rows and enqueue on registry changes

Advanced search features

Postgres-first execution supports:

  • _include and _revinclude, including ResourceType:* and *:* wildcards
  • chained search up to two hops (e.g. subject.name, subject.organization.name)
  • reverse chaining via _has:Type:ref:param
  • uri SearchParameters with :below / :above
  • composite SearchParameters from the registry
  • modifiers (:exact, :contains on string; date/number prefixes)
  • _sort on registry-backed parameters plus _id / _lastUpdated
  • _count / _offset paging with deterministic ordering
  • _summary and _elements response projection
  • Postgres full-text search via indexed text documents

Unsupported semantics are rejected explicitly (ErrUnsupportedFeature, ErrInvalidQuery).

Indexing

RegistryIndexer evaluates each installed SearchParameter expression with pkg/fhirpath, normalizes extracted values into typed field keys (token.*, string.*, date.*, reference.*, uri.*, composite.*, text.*), and emits store.SearchIndexEntry rows consumed by store.SearchStore.

Query semantics

  • Repeated parameters AND together
  • Comma-separated values OR within one parameter occurrence
  • _count and _offset provide offset paging; _sort supports registry-backed fields

Backends

Postgres is the first complete execution backend via store.SearchAdvancedExecutor. SQLite supports typed index persistence and basic LookupMatch for tests and embedded nodes, but not the full advanced query feature set.

Integration

Wire RegistryIndexer into pkg/core for write-path indexing:

indexer, _ := search.NewRegistryIndexer(search.RegistryIndexerConfig{
    Registry: search.NewSnapshotRegistry(snapshot),
    Engine:   fhirpathEngine,
})

Execute search through Service:

svc, _ := search.NewService(search.ServiceConfig{
    Registry:  search.NewSnapshotRegistry(snapshot),
    Executor:  search.NewStoreExecutor(db.SearchStore(), db.ResourceStore()),
    Resources: db.ResourceStore(),
})
result, err := svc.Search(ctx, "Patient", queryParams)

Index

Constants

View Source
const ReindexJobType = jobs.TypeReindex

Variables

View Source
var (
	// ErrUnsupportedParam indicates a search parameter is not supported in the MVP.
	ErrUnsupportedParam = errors.New("search: unsupported search parameter")
	// ErrUnsupportedFeature indicates a FHIR search feature is not implemented.
	ErrUnsupportedFeature = errors.New("search: unsupported search feature")
	// ErrUnknownParam indicates a parameter is not defined for the resource type.
	ErrUnknownParam = errors.New("search: unknown search parameter")
	// ErrInvalidQuery indicates malformed search input.
	ErrInvalidQuery = errors.New("search: invalid query")
	// ErrResourceTypeDisabled indicates the resource type is not enabled in the registry.
	ErrResourceTypeDisabled = errors.New("search: resource type not enabled")
	// ErrProjectionFailed indicates response projection could not be applied safely.
	ErrProjectionFailed = errors.New("search: projection failed")
)

Functions

func BuildPagingLinks(baseURL string, params url.Values, offset, count, pageSize int, total *int) map[string]string

BuildPagingLinks constructs self and next links preserving the original query parameters.

func EnqueueReindex

func EnqueueReindex(ctx context.Context, jobs store.JobStore, resourceType string) (string, error)

EnqueueReindex schedules a reindex job for one resource type or all types when resourceType is empty.

func EnqueueSearchParameterReindex

func EnqueueSearchParameterReindex(ctx context.Context, jobs store.JobStore, canonicalURL, version string, resourceTypes ...string) (string, error)

EnqueueSearchParameterReindex schedules a reindex job for one SearchParameter definition.

func MatchResourceParameter

func MatchResourceParameter(ctx context.Context, reg Registry, engine fhirpath.Engine, resourceType string, resource *types.ResourceEnvelope, param string, want []string) (matched bool, known bool)

MatchResourceParameter reports whether a resource satisfies one search parameter value set. It uses the same FHIRPath extraction and normalization pipeline as the search indexer.

func ProjectResource

func ProjectResource(res *types.ResourceEnvelope, summary SummaryMode, elements []string) (*types.ResourceEnvelope, error)

ProjectResource applies the same _summary/_elements projection used by search results to a read response.

func UnknownParamCode

func UnknownParamCode(err error) (string, bool)

UnknownParamCode returns the unknown parameter code when err wraps UnknownParamError.

Types

type BundleEntry

type BundleEntry struct {
	FullURL  string
	Resource *types.ResourceEnvelope
	Mode     string
}

BundleEntry is one searchset bundle entry.

type ChainClause

type ChainClause struct {
	RefCode     string
	RefFieldKey string
	TargetType  string
	Param       ParamClause
	Nested      *ChainClause
}

ChainClause is a chained search parameter (e.g. subject.name or subject.organization.name). Nested is set for multi-hop chains; Param is the terminal predicate on the last hop.

type ChainPlan

type ChainPlan struct {
	RefCode     string
	RefFieldKey string
	TargetType  string
	ParamPlan   ParamPlan
	Nested      *ChainPlan
}

ChainPlan is a chained search execution stage. Nested walks one more hop.

type CompositeComponentInfo

type CompositeComponentInfo struct {
	Definition string
	Expression string
	Code       string
	Type       string
}

CompositeComponentInfo describes one component of a composite SearchParameter.

type DefaultPlanner

type DefaultPlanner struct{}

DefaultPlanner implements Planner using package-level parse/plan functions.

func (DefaultPlanner) Build

func (DefaultPlanner) Build(q *Query) (*Plan, error)

func (DefaultPlanner) Parse

func (DefaultPlanner) Parse(resourceType string, params url.Values) (*Query, error)

func (DefaultPlanner) PlanSearch

func (p DefaultPlanner) PlanSearch(reg Registry, resourceType string, params url.Values) (*Plan, error)

func (DefaultPlanner) Resolve

func (DefaultPlanner) Resolve(reg Registry, q *Query) (*Query, error)

type ExecuteResult

type ExecuteResult struct {
	IDs      []string
	Total    int
	Scores   map[string]float64
	Included []IncludedResource
}

ExecuteResult holds primary match IDs, total count, optional full-text scores, and includes.

type Executor

type Executor interface {
	Execute(ctx context.Context, plan *Plan) (*ExecuteResult, error)
}

Executor executes a search plan against a typed index backend.

type HasClause

type HasClause struct {
	SourceType  string
	RefCode     string
	RefFieldKey string
	Param       ParamClause
	Chain       *ChainClause
	Nested      *HasClause
}

HasClause is a reverse-chained _has search (e.g. _has:Observation:subject:code=8867-4).

type HasPlan

type HasPlan struct {
	SourceType  string
	RefCode     string
	RefFieldKey string
	ParamPlan   ParamPlan
	ChainPlan   *ChainPlan
	Nested      *HasPlan
}

HasPlan is a reverse-chained _has execution stage.

type IncludeDirective

type IncludeDirective struct {
	SourceType string
	ParamCode  string
	TargetType string
}

IncludeDirective requests direct include expansion for one reference parameter.

type IncludePlan

type IncludePlan struct {
	SourceType  string
	ParamCode   string
	RefFieldKey string
	TargetType  string
}

IncludePlan describes direct include expansion after primary search.

type IncludedEntry

type IncludedEntry struct {
	ResourceType string
	ID           string
	Resource     *types.ResourceEnvelope
	Mode         string
}

IncludedEntry is one included or revincluded resource.

type IncludedResource

type IncludedResource struct {
	ResourceType string
	ID           string
	Mode         string
}

IncludedResource identifies one included or revincluded resource.

type Indexer

type Indexer interface {
	// Build returns index entries to persist via store.SearchStore.
	Build(ctx context.Context, resource *types.ResourceEnvelope) ([]store.SearchIndexEntry, error)
}

Indexer builds search index entries from a resource envelope after writes in pkg/core.

type MatchOperator

type MatchOperator string

MatchOperator identifies how a predicate value is compared.

const (
	OpEqual      MatchOperator = "eq"
	OpNotEqual   MatchOperator = "ne"
	OpGreater    MatchOperator = "gt"
	OpLess       MatchOperator = "lt"
	OpGE         MatchOperator = "ge"
	OpLE         MatchOperator = "le"
	OpStarts     MatchOperator = "sa"
	OpEnds       MatchOperator = "eb"
	OpApprox     MatchOperator = "ap"
	OpContains   MatchOperator = "contains"
	OpExact      MatchOperator = "exact"
	OpText       MatchOperator = "text"
	OpBelow      MatchOperator = "below"
	OpAbove      MatchOperator = "above"
	OpIn         MatchOperator = "in"
	OpNotIn      MatchOperator = "not-in"
	OpNot        MatchOperator = "not"
	OpIdentifier MatchOperator = "identifier"
	OpType       MatchOperator = "type"
)

type ParamClause

type ParamClause struct {
	Code      string
	Modifier  string
	ParamType string
	FieldKey  string
	Values    []ValueClause
}

ParamClause is one resolved search parameter with OR semantics across Values.

type ParamPlan

type ParamPlan struct {
	Code        string
	FieldKey    string
	ParamType   string
	Predicates  []Predicate
	CombineMode combineMode
}

ParamPlan groups OR predicates for one parameter; parameters AND together.

type ParameterInfo

type ParameterInfo struct {
	CanonicalURL string
	Version      string
	Code         string
	Name         string
	Type         string
	Expression   string
	Target       []string
	Component    []CompositeComponentInfo
}

ParameterInfo is compiled search parameter metadata used by haistack-search.

type Plan

type Plan struct {
	ResourceType string
	ParamPlans   []ParamPlan
	ChainPlans   []ChainPlan
	HasPlans     []HasPlan
	Includes     []IncludePlan
	RevIncludes  []RevIncludePlan
	Count        int
	Offset       int
	Sort         []SortField
	Summary      SummaryMode
	Elements     []string
	FullText     string
}

Plan is a backend-neutral search execution plan.

func BuildPlan

func BuildPlan(q *Query) (*Plan, error)

BuildPlan converts a resolved query into a backend-neutral execution plan.

func PlanSearch

func PlanSearch(reg Registry, resourceType string, params url.Values) (*Plan, error)

PlanSearch is a convenience helper that parses, resolves, and builds a plan.

func PlanSearchRequest

func PlanSearchRequest(reg Registry, req Request) (*Plan, error)

PlanSearchRequest plans a structured search request.

type Planner

type Planner interface {
	Parse(resourceType string, params url.Values) (*Query, error)
	Resolve(reg Registry, q *Query) (*Query, error)
	Build(q *Query) (*Plan, error)
	PlanSearch(reg Registry, resourceType string, params url.Values) (*Plan, error)
}

Planner converts raw FHIR search parameters into backend-neutral plans.

func NewPlanner

func NewPlanner() Planner

NewPlanner returns the default search planner.

type Predicate

type Predicate struct {
	FieldKey string
	Value    string
	Operator MatchOperator
}

Predicate is one backend-neutral search predicate.

type Query

type Query struct {
	ResourceType string
	Params       []ParamClause
	Chains       []ChainClause
	Has          []HasClause
	Includes     []IncludeDirective
	RevIncludes  []RevIncludeDirective
	Count        int
	CountSet     bool
	Offset       int
	Sort         []SortField
	Summary      SummaryMode
	Elements     []string
	FullText     string
}

Query is the normalized internal representation of a FHIR search request.

func ParseQuery

func ParseQuery(resourceType string, params url.Values) (*Query, error)

ParseQuery parses raw FHIR search query parameters for one resource type.

func ParseQueryValues

func ParseQueryValues(resourceType string, params map[string][]string) (*Query, error)

ParseQueryValues is a helper for map-based query params in tests and callers without url.Values.

func ResolveQuery

func ResolveQuery(reg Registry, q *Query) (*Query, error)

ResolveQuery maps parsed parameters to registry metadata and typed field keys.

type Registry

type Registry interface {
	IsResourceEnabled(resourceType string) bool
	SearchParametersFor(resourceType string) []ParameterInfo
	SearchParameter(resourceType, code string) (ParameterInfo, bool)
	HasSearchParameter(resourceType, code string) bool
	EnabledResourceTypes() []string
	ResolveComponentCode(canonicalURL string) (ParameterInfo, bool)
}

Registry resolves enabled SearchParameters for resource types.

type RegistryIndexer

type RegistryIndexer struct {
	// contains filtered or unexported fields
}

RegistryIndexer extracts typed search index rows from registry SearchParameters.

func NewRegistryIndexer

func NewRegistryIndexer(cfg RegistryIndexerConfig) (*RegistryIndexer, error)

NewRegistryIndexer constructs a registry-driven Indexer for pkg/core.

func (*RegistryIndexer) Build

Build implements search.Indexer.

type RegistryIndexerConfig

type RegistryIndexerConfig struct {
	Registry Registry
	Engine   fhirpath.Engine
}

RegistryIndexerConfig configures a registry-driven search indexer.

type ReindexJobRunner

type ReindexJobRunner struct {
	Jobs   store.JobStore
	Worker Reindexer
	Now    func() time.Time
}

ReindexJobRunner claims and executes background reindex jobs through the shared jobs.Runner runtime.

func (*ReindexJobRunner) RunOnce

func (r *ReindexJobRunner) RunOnce(ctx context.Context) (processed bool, err error)

RunOnce claims at most one pending reindex job and executes it.

type ReindexNotifier

type ReindexNotifier struct {
	Jobs store.JobStore
}

ReindexNotifier enqueues background reindex jobs when search parameters change.

func NewReindexNotifier

func NewReindexNotifier(jobs store.JobStore) *ReindexNotifier

NewReindexNotifier constructs a notifier backed by JobStore.

func (*ReindexNotifier) ScheduleReindex

func (n *ReindexNotifier) ScheduleReindex(ctx context.Context, resourceTypes ...string) error

ScheduleReindex implements registry.SearchReindexNotifier.

func (*ReindexNotifier) ScheduleSearchParameterReindex

func (n *ReindexNotifier) ScheduleSearchParameterReindex(ctx context.Context, canonicalURL, version string, resourceTypes ...string) error

ScheduleSearchParameterReindex implements registry.SearchParameterReindexNotifier.

type ReindexPayload

type ReindexPayload struct {
	ResourceType           string `json:"resourceType,omitempty"`
	SearchParameterURL     string `json:"searchParameterUrl,omitempty"`
	SearchParameterVersion string `json:"searchParameterVersion,omitempty"`
}

ReindexPayload is the background job payload for search reindexing.

type ReindexWorker

type ReindexWorker struct {
	Registry  Registry
	Indexer   Indexer
	Resources store.ResourceStore
	Search    store.SearchStore
	BatchSize int
}

ReindexWorker rebuilds search index rows using the same registry-driven indexer as writes.

func (*ReindexWorker) HandleJob

func (w *ReindexWorker) HandleJob(ctx context.Context, job store.JobRecord) error

HandleJob processes one background reindex job.

func (*ReindexWorker) ReindexAll

func (w *ReindexWorker) ReindexAll(ctx context.Context, resourceType string) error

ReindexAll rebuilds search rows for one resource type or all enabled types when resourceType is empty.

func (*ReindexWorker) ReindexResource

func (w *ReindexWorker) ReindexResource(ctx context.Context, resource *types.ResourceEnvelope) error

ReindexResource rebuilds search rows for one resource instance.

type Reindexer

type Reindexer interface {
	ReindexAll(ctx context.Context, resourceType string) error
	ReindexResource(ctx context.Context, resource *types.ResourceEnvelope) error
	HandleJob(ctx context.Context, job store.JobRecord) error
}

Reindexer rebuilds search index rows using registry-driven extraction.

type Request

type Request struct {
	ResourceType string
	Params       url.Values
}

Request is a FHIR search request for one resource type.

type Result

type Result struct {
	ResourceType string
	Resources    []*types.ResourceEnvelope
	Included     []IncludedEntry
	Total        *int
	Offset       int
	Count        int
	Summary      SummaryMode
	Elements     []string
	Links        map[string]string
}

Result holds search matches and paging metadata for bundle assembly.

type RevIncludeDirective

type RevIncludeDirective struct {
	SourceType string
	ParamCode  string
	TargetType string
}

RevIncludeDirective requests reverse include expansion.

type RevIncludePlan

type RevIncludePlan struct {
	SourceType  string
	ParamCode   string
	RefFieldKey string
	TargetType  string
}

RevIncludePlan describes reverse include expansion after primary search.

type SearchBundle

type SearchBundle struct {
	ResourceType string
	Total        *int
	Offset       int
	Count        int
	Links        map[string]string
	Entries      []BundleEntry
}

SearchBundle is a bundle-ready searchset payload.

func AssembleBundle

func AssembleBundle(result *Result) *SearchBundle

AssembleBundle converts a search Result into bundle-ready output.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service is the main entrypoint for FHIR search execution.

func NewService

func NewService(cfg ServiceConfig) (*Service, error)

NewService constructs a search service.

func (*Service) EnabledResourceTypes

func (s *Service) EnabledResourceTypes() []string

EnabledResourceTypes returns resource types enabled in the search registry.

func (*Service) Search

func (s *Service) Search(ctx context.Context, resourceType string, params url.Values) (*Result, error)

Search executes a FHIR search for one resource type and returns bundle-ready results.

func (*Service) SearchBundle

func (s *Service) SearchBundle(ctx context.Context, resourceType string, params url.Values) (*SearchBundle, error)

SearchBundle executes search and returns a bundle-ready payload.

func (*Service) SearchParametersFor

func (s *Service) SearchParametersFor(resourceType string) []ParameterInfo

SearchParametersFor returns compiled search parameter metadata for a resource type.

func (*Service) SearchRequest

func (s *Service) SearchRequest(ctx context.Context, req Request) (*Result, error)

SearchRequest executes a FHIR search from a structured request.

type ServiceConfig

type ServiceConfig struct {
	Registry  Registry
	Executor  Executor
	Planner   Planner
	Resources store.ResourceStore
	BaseURL   string
}

ServiceConfig configures the high-level search service.

type SnapshotRegistry

type SnapshotRegistry struct {
	// contains filtered or unexported fields
}

SnapshotRegistry adapts a registry.Snapshot for search indexing and query resolution.

func NewSnapshotRegistry

func NewSnapshotRegistry(snapshot *registry.Snapshot) *SnapshotRegistry

NewSnapshotRegistry wraps a compiled registry snapshot.

func (*SnapshotRegistry) EnabledResourceTypes

func (r *SnapshotRegistry) EnabledResourceTypes() []string

func (*SnapshotRegistry) HasSearchParameter

func (r *SnapshotRegistry) HasSearchParameter(resourceType, code string) bool

func (*SnapshotRegistry) IsResourceEnabled

func (r *SnapshotRegistry) IsResourceEnabled(resourceType string) bool

func (*SnapshotRegistry) ResolveComponentCode

func (r *SnapshotRegistry) ResolveComponentCode(canonicalURL string) (ParameterInfo, bool)

func (*SnapshotRegistry) SearchParameter

func (r *SnapshotRegistry) SearchParameter(resourceType, code string) (ParameterInfo, bool)

func (*SnapshotRegistry) SearchParametersFor

func (r *SnapshotRegistry) SearchParametersFor(resourceType string) []ParameterInfo

func (*SnapshotRegistry) SetSnapshot

func (r *SnapshotRegistry) SetSnapshot(snapshot *registry.Snapshot)

SetSnapshot replaces the backing registry snapshot.

type SortDirection

type SortDirection int

SortDirection is the order for one sort field.

const (
	SortAsc SortDirection = iota
	SortDesc
)

type SortField

type SortField struct {
	Code      string
	FieldKey  string
	Direction SortDirection
}

SortField identifies one sort key in a search request.

type StoreExecutor

type StoreExecutor struct {
	Backend   store.SearchQueryExecutor
	Advanced  store.SearchAdvancedExecutor
	Resources store.ResourceStore
}

StoreExecutor executes search plans using store.SearchQueryExecutor.

func NewStoreExecutor

func NewStoreExecutor(backend store.SearchQueryExecutor, resources store.ResourceStore) *StoreExecutor

NewStoreExecutor constructs an executor backed by SearchQueryExecutor.

func (*StoreExecutor) Execute

func (e *StoreExecutor) Execute(ctx context.Context, plan *Plan) (*ExecuteResult, error)

Execute runs the plan and returns matching resource IDs in deterministic order.

type SummaryMode

type SummaryMode string

SummaryMode controls _summary projection behavior.

const (
	SummaryNone  SummaryMode = ""
	SummaryFalse SummaryMode = "false"
	SummaryTrue  SummaryMode = "true"
	SummaryText  SummaryMode = "text"
	SummaryData  SummaryMode = "data"
	SummaryCount SummaryMode = "count"
)

type UnknownParamError

type UnknownParamError struct {
	ResourceType string
	Code         string
}

UnknownParamError identifies an unknown search parameter code for a resource type.

func (UnknownParamError) Error

func (e UnknownParamError) Error() string

func (UnknownParamError) Unwrap

func (e UnknownParamError) Unwrap() error

type ValueClause

type ValueClause struct {
	Raw      string
	Prefix   string
	Operator MatchOperator
}

ValueClause is one search value with an optional comparator prefix.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL