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
- Variables
- func BuildPagingLinks(baseURL string, params url.Values, offset, count, pageSize int, total *int) map[string]string
- func EnqueueReindex(ctx context.Context, jobs store.JobStore, resourceType string) (string, error)
- func EnqueueSearchParameterReindex(ctx context.Context, jobs store.JobStore, canonicalURL, version string, ...) (string, error)
- func MatchResourceParameter(ctx context.Context, reg Registry, engine fhirpath.Engine, resourceType string, ...) (matched bool, known bool)
- func ProjectResource(res *types.ResourceEnvelope, summary SummaryMode, elements []string) (*types.ResourceEnvelope, error)
- func UnknownParamCode(err error) (string, bool)
- type BundleEntry
- type ChainClause
- type ChainPlan
- type CompositeComponentInfo
- type DefaultPlanner
- func (DefaultPlanner) Build(q *Query) (*Plan, error)
- func (DefaultPlanner) Parse(resourceType string, params url.Values) (*Query, error)
- func (p DefaultPlanner) PlanSearch(reg Registry, resourceType string, params url.Values) (*Plan, error)
- func (DefaultPlanner) Resolve(reg Registry, q *Query) (*Query, error)
- type ExecuteResult
- type Executor
- type HasClause
- type HasPlan
- type IncludeDirective
- type IncludePlan
- type IncludedEntry
- type IncludedResource
- type Indexer
- type MatchOperator
- type ParamClause
- type ParamPlan
- type ParameterInfo
- type Plan
- type Planner
- type Predicate
- type Query
- type Registry
- type RegistryIndexer
- type RegistryIndexerConfig
- type ReindexJobRunner
- type ReindexNotifier
- type ReindexPayload
- type ReindexWorker
- type Reindexer
- type Request
- type Result
- type RevIncludeDirective
- type RevIncludePlan
- type SearchBundle
- type Service
- func (s *Service) EnabledResourceTypes() []string
- func (s *Service) Search(ctx context.Context, resourceType string, params url.Values) (*Result, error)
- func (s *Service) SearchBundle(ctx context.Context, resourceType string, params url.Values) (*SearchBundle, error)
- func (s *Service) SearchParametersFor(resourceType string) []ParameterInfo
- func (s *Service) SearchRequest(ctx context.Context, req Request) (*Result, error)
- type ServiceConfig
- type SnapshotRegistry
- func (r *SnapshotRegistry) EnabledResourceTypes() []string
- func (r *SnapshotRegistry) HasSearchParameter(resourceType, code string) bool
- func (r *SnapshotRegistry) IsResourceEnabled(resourceType string) bool
- func (r *SnapshotRegistry) ResolveComponentCode(canonicalURL string) (ParameterInfo, bool)
- func (r *SnapshotRegistry) SearchParameter(resourceType, code string) (ParameterInfo, bool)
- func (r *SnapshotRegistry) SearchParametersFor(resourceType string) []ParameterInfo
- func (r *SnapshotRegistry) SetSnapshot(snapshot *registry.Snapshot)
- type SortDirection
- type SortField
- type StoreExecutor
- type SummaryMode
- type UnknownParamError
- type ValueClause
Constants ¶
const ReindexJobType = jobs.TypeReindex
Variables ¶
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 ¶
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 ¶
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 ¶
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 ¶
CompositeComponentInfo describes one component of a composite SearchParameter.
type DefaultPlanner ¶
type DefaultPlanner struct{}
DefaultPlanner implements Planner using package-level parse/plan functions.
func (DefaultPlanner) PlanSearch ¶
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 ¶
IncludeDirective requests direct include expansion for one reference parameter.
type IncludePlan ¶
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 ¶
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 PlanSearch ¶
PlanSearch is a convenience helper that parses, resolves, and builds a plan.
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.
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 ¶
ParseQuery parses raw FHIR search query parameters for one resource type.
func ParseQueryValues ¶
ParseQueryValues is a helper for map-based query params in tests and callers without url.Values.
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 ¶
func (i *RegistryIndexer) Build(ctx context.Context, resource *types.ResourceEnvelope) ([]store.SearchIndexEntry, error)
Build implements search.Indexer.
type RegistryIndexerConfig ¶
RegistryIndexerConfig configures a registry-driven search indexer.
type ReindexJobRunner ¶
ReindexJobRunner claims and executes background reindex jobs through the shared jobs.Runner runtime.
type ReindexNotifier ¶
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) 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 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 ¶
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 ¶
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.
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 ¶
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.