Framework
The query index flattens selected record data into a searchable JSON document. It pays off on a list that repeatedly combines base and custom fields. Follow a write through indexing to understand when an updated value becomes visible.
Goal: make querying base entities together with custom fields fast and simple by maintaining a flat, query-friendly JSONB index per entity record, without breaking module isomorphism or schema agility. See the Hybrid query engine for runtime usage.
entity_indexes
id uuid (PK)entity_type text e.g., example:todoentity_id text base record id as textorganization_id uuid null, tenant_id uuid nulldoc jsonb flattened document of base fields + cf:<key> valuesindex_version int (default 1), created_at, updated_at, deleted_atorganization_id_coalesced uuid generated always as (coalesce(organization_id, '00000000-0000-0000-0000-000000000000')) storedentity_indexes (see data/entities.ts)
Unique: unique(entity_type, entity_id, organization_id_coalesced) – note that tenant_id is not part of the uniqueness key
Btree: (entity_type), (entity_id), (organization_id), (entity_type, tenant_id)
Six hand-written partial covering indexes for customers:customer_entity, customers:customer_person_profile, and customers:customer_company_profile – one org-scoped and one tenant-scoped variant each:
(entity_id, organization_id, tenant_id) include (doc) where deleted_at is null and entity_type = '<id>' and organization_id is not null and tenant_id is not null(tenant_id, entity_id) include (doc) where deleted_at is null and entity_type = '<id>' and organization_id is null and tenant_id is not nullThey are not generated. Any other entity type gets only the generic btrees above.
There is no GIN index on doc. Adding one is a tuning decision you make per deployment – see Performance tips.
cf:<key> values.entity_indexes.doc is treated as “at rest” storage: it should contain the same encrypted values as the source tables / custom_field_values.HybridQueryEngine decrypts entity payload fields via the tenant encryption service and also decrypts cf:* values before returning results.like/ilike token search) may decrypt values transiently to hash the plaintext tokens, but plaintext is never persisted into entity_indexes.doc.
packages/shared/src/lib/encryption/indexDoc.ts (shared by Query Engine, indexers, and vector search).(entity_type, entity_id, organization_id_coalesced), always writing deleted_at = null.markDeleted() hard-deletes the index row and its search_tokens. The deleted_at column exists and readers still filter on it, but the current writers never populate it – a removed base record leaves no index row behind.<module>.<entity>.created|updated → upsert index row.<module>.<entity>.deleted → remove the index row.<module>.<entity>.updated as well, reusing the same subscriber path.HybridQueryEngine prefers the JSONB index and falls back to the basic engine under four specific conditions – see Routing decisions for the full table. "No index rows exist" is only one of them, and it is evaluated only when the query actually asks for cf:*/l10n:* data.cf:* via JSON path extraction and casting for common types.cf:* using casted expressions when possible.organization_id, tenant_id) and soft-delete exclusion by default.CLI: mercato query_index rebuild --entity <module:entity> reindexes existing rows with a live progress bar.
mercato query_index rebuild --entity example:todo --globalmercato query_index rebuild --entity example:todo --org <orgId> --tenant <tenantId>mercato query_index rebuild --entity example:todo --record <entityId>--withDeleted --limit <n> --offset <n> --batch <size>CLI: mercato query_index rebuild-all walks every registered entity index using the same flags as rebuild, making it easy to refresh the entire corpus in one go.
CLI: mercato query_index reindex [--entity <module:entity>] [--tenant <tenantId>] [--force] (shorthand: yarn mercato reindex) now splits work into five partitions by default. Override the granularity with --partitions <n> or target a single shard with --partition-index <i>. Combine with --skipResetCoverage on partitions >0 when running several workers concurrently. The command continues to honour --batch <size> for the inner chunk size (defaults to 500 rows).
mercato query_index reindex --entity example:todo --partitions 5 --partition-index <0-4>; the partition 0 process resets coverage, so the remaining workers should pass --skipResetCoverage.--partition-index and the CLI will iterate every partition sequentially.Each CLI run purges existing index rows before reindexing unless --skipPurge is provided, ensuring a clean rebuild.
The admin status view now tracks per-partition progress and marks jobs as stalled when no heartbeat is recorded for 60 seconds, making it easier to spot a wedged worker.
Scheduling via events remains available: mercato query_index reindex [...] and mercato query_index purge [...] enqueue background jobs when you don’t need immediate writes. API callers can pass partitionCount, partitionIndex, and batchSize to mirror the CLI behaviour; omitting partitionIndex emits one event per partition automatically.
Data migrations: a migration that rewrites a projected column – an update, or an ADD COLUMN with a SQL backfill – leaves entity_indexes.doc and its search_tokens on the pre-migration value forever, with nothing to signal it (no indexer job is created, and neither the record's nor the projection's updated_at moves). Declare the affected entity types in the migration file and mercato db migrate discharges the obligation after the run commits:
import { declareQueryIndexReindex } from '@open-mercato/shared/lib/query/migration-reindex'
export const queryIndexReindexEntityTypes = declareQueryIndexReindex(['customers:customer_dictionary_entry'])
One persistent query_index.reindex is queued per declared entity type, with force: false so the existing subscriber upserts in place rather than purging the entity's rows first. When no event bus is reachable, db migrate prints the equivalent mercato query_index rebuild --entity <type> --global instead of failing. Set OM_MIGRATION_REINDEX=off to suppress the queueing entirely and drive the rebuilds by hand. A migration cannot emit the event itself – it holds no DI container, and the projection must only be refreshed once its own transaction has committed. Repairing an already-applied migration takes a follow-up migration carrying only the declaration.
Bulk imports: build and insert index payloads alongside your ETL transaction with the buildIndexDocument helper (packages/core/src/modules/query_index/lib/document.ts) so large seeders can skip the post-import reindex sweep. The CRM stress-test seeder now follows this pattern.
gin(doc jsonb_path_ops) is a reasonable starting point for containment/path queries, but no migration creates it – you have to add it yourself and measure. It does not help ->> extraction used by cf:* equality, range, and sort predicates.create index on entity_indexes (((doc->>'cf:priority')::int));SCHEDULE_AUTO_REINDEX (defaults to true) if you prefer to manage reindex jobs manually. For smaller datasets (≤10k customers) keep this flag enabled together with OPTIMIZE_INDEX_COVERAGE_STATS=false so coverage updates remain instant.OM_QUERY_INDEX_AUTO_REINDEX_DEBOUNCE_MS window (30 seconds by default). This debounce is process-global within each application process; the reindexer's existing active-job guard remains the cross-process safety net.OM_SEARCH_MAX_FIELD_CHARS, OM_SEARCH_MAX_TOKENS_PER_FIELD, and OM_SEARCH_MAX_TOKENS_PER_RECORD. Set an individual limit to 0 to disable it.buildIndexDocument (the batch reindex path) writes base columns first, then cf:* keys, then the aggregate search_text field last, so search_text – the field global search queries actually hit – is starved first. buildIndexDoc (the incremental single-record write path) additionally inserts l10n:{locale}:{field} translation keys between the cf:* keys and search_text, so those translation keys consume budget the batch path would have spent on search_text: search_text is starved even sooner on the incremental path, and the translation fields are starved next, before any base column. The two paths can therefore keep different fields searchable for an otherwise equivalent record. Raise OM_SEARCH_MAX_TOKENS_PER_RECORD, or blocklist the bulky field, if an entity with very long text goes missing from search results.doc column back is not equivalent: Postgres stores jsonb keys in a canonical order (by key length, then byte order) rather than insertion order, so re-tokenizing a read-back document can truncate at a different field than the write did. Tooling that verifies or recomputes a record's expected tokens should rebuild the document through the builder that matches the write path being checked – buildIndexDoc for incrementally-written records, buildIndexDocument for batch-reindexed ones – instead of reading it from the database.OPTIMIZE_INDEX_COVERAGE_STATS (code default false) controls what happens when a coverage snapshot is stale or missing. With false the snapshot is recomputed inline on the request thread, which keeps counts instant on small installations but means concurrent list queries can herd on the recompute when the TTL expires. With true the engine schedules an asynchronous query_index.coverage.refresh and serves the stale snapshot (or none, if there is no row yet). Snapshot freshness is governed by QUERY_INDEX_COVERAGE_CACHE_MS (default 5 minutes).FORCE_QUERY_INDEX_ON_PARTIAL_INDEXES keeps the indexed path even when a coverage gap is detected. Its code default is false – the shipped .env.example files set it to true, so a deployment that does not copy that file gets the fallback behaviour instead. Either way, list responses carry an x-om-partial-index response header (with entity, baseCount, indexedCount, and scope) so the admin UI can surface a banner prompting the user to reindex via /backend/query-indexes.
query_index.coverage.warmup, which sweeps stale entity types and schedules a coverage.refresh for each. It is a proactive nice-to-have on top of the query engine's own lazy, on-demand refresh (triggered on read when a coverage snapshot is missing or past its TTL) – coverage self-heals even with the warmup disabled.entity_index_coverage.refreshed_at) is actually stale, so a process restart does not repeat the full sweep for scopes a prior warmup, a lazy refresh, or an incremental CRUD delta already kept fresh. Before dispatching any refresh it also batch-primes the shared information_schema.columns cache for every table involved, avoiding a query-per-table cache stampede when many refreshes are dispatched concurrently.QUERY_INDEX_WARMUP_ENABLED, QUERY_INDEX_WARMUP_THROTTLE_MS, QUERY_INDEX_WARMUP_CONCURRENCY, and QUERY_INDEX_WARMUP_STAGGER_MS – see System status variables. All default to the prior always-on, unstaggered behaviour when unset.query_index.delete_one, throttled to once per (entityType, tenant) per 5 minutes – the incremental +1/-1 adjustment already keeps the count correct between recomputes, so the throttle only limits how often the full recount runs. Pass suppressCoverage: true to skip the recount entirely, or an explicit coverageDelayMs to bypass the throttle for a caller that wants a guaranteed (optionally deferred) recompute.OM_QUERY_INDEX_DEBUG=true, or LOG_VERBOSITY/LOG_LEVEL set to debug/trace/silly) and QUERY_ENGINE_DEBUG_SQL=true. Verbosity alone prints nothing from this engine.QUERY_ENGINE_DEBUG_SQL=true also prints the SQL emitted for the count and data queries. It is disabled by default to keep development logs readable.OM_PROFILE instead: the [qe:profile] node reports result: ok | fallback | custom_entity | error plus the fallback reason.OM_SEARCH_DEBUG=true. It logs field names, token hashes, and per-record counts during indexing – never the raw token text, document values, or decrypted PII – so the index shape can be debugged without disclosing data. Query behaviour is unchanged.packages/core/src/modules/query_index/data/entities.tspackages/core/src/modules/query_index/lib/indexer.tspackages/core/src/modules/query_index/lib/engine.tspackages/core/src/modules/query_index/di.tspackages/core/src/modules/query_index/lib/coverage.tspackages/core/src/modules/query_index/migrations/ – Migration20251030150038.ts creates entity_indexes; Migration20260518162054_query_index.ts adds organization_id_coalesced and the uniqueness key