Skip to main content
A search definition decides, for one logical key, which search document a source row becomes and with which index settings and mappings that document is stored. The worker builds documents with the definition’s projection; the administrative handle creates indexes from its settings and mappings.

defineSearch

The example indexes chat messages. It starts with the logical key and the document schema. updated_at is in the document so that search results can be compared with the current row when they are hydrated from the primary.
search/chat-messages.definition.ts
The definition itself is created with defineSearch:
search/chat-messages.definition.ts
defineSearch checks its input, computes the fingerprint, and returns a frozen definition. Unknown keys, a materialize that is not a function, mappings that break the rules, or settings that are not JSON throw SearchConfigurationError with the cause in details.reason. settings and mappings are stored as checked, deeply frozen copies, so changing the original objects afterwards has no effect on the definition.

defineSonamuSearch

Use defineSonamuSearch from @sonamu-kit/opensearch/sonamu when a projection should reuse model methods. It takes the same input as defineSearch and produces the same fingerprint, but runs materialize, captureScanBoundary, and scanSourceIds inside withProjectionScope. That scope registers the worker’s snapshot transaction as Sonamu’s "w" and "r" transaction, so inside the projection getPuri("w"), getPuri("r"), subset queries, and @transactional methods that reuse an existing transaction all read the same snapshot. In the example, the scan functions reuse the defineSearch form’s implementations, which read only the snapshot.
application/chat-message.sonamu-search.ts
The model method that materialize calls reads through getPuri("r"), which inside this scope is the worker’s snapshot transaction:
application/chat-message.model.ts
Both forms have the same fingerprint, so put only one of them in the definitions of the worker and the administrative handle; createIndexer rejects the same (key, fingerprint) given twice. The model methods of defineSonamuSearch need Sonamu’s database configuration, so a separate worker process that does not start Sonamu uses the defineSearch form. Some paths bypass the scope: getDB(), named presets, and separately created Knex instances read newer data on a new connection. Do not use them in a projection.

Projection contract

materialize(context, ids) returns a Map with exactly one result per requested ID. The example looks up only decimal IDs, since no other ID can exist in the source, and returns every ID without a row as deleted.
search/chat-messages.definition.ts
  • A record that exists in the source is { state: "present", document }; a missing record is { state: "deleted" }. A deleted record must come back as deleted so the worker indexes a tombstone.
  • If the Map contains an ID that was not requested, or the result is not a Map, none of that call’s results are used.
  • If a requested ID is missing or one result has the wrong shape (for example deleted carrying a document), only that document fails.
  • If the projection throws, the worker splits the IDs in halves and reruns them to find the document that causes the failure, and quarantines only that document. Database outages such as a dropped connection are not counted against documents. The full classification is in Indexing worker.

What a projection may read

Read only through context.trx, a read-only REPEATABLE READ transaction the worker opened on the primary. The worker reads the ledger revision in the same snapshot before running the projection, so the indexed body and the external version attached to it come from the same moment. Reading from another connection or an external service breaks that correspondence and can index content that does not match the revision. The snapshot has these constraints:
  • Its first statement checks the isolation level, read-only mode, and whether it runs on a replica. On a replica or a mismatch, the drain fails with SearchConfigurationError.
  • Statement, lock, and idle-in-transaction timeouts are set to projectionTimeoutMs.
  • Writes fail (SQLSTATE 25006), and that document is quarantined.
  • If the projection swallowed an SQL error and the transaction aborted, or sent COMMIT or ROLLBACK and replaced the snapshot, the worker notices before using the results and discards that call’s results.
context also carries signal, deadlineAt (epoch ms), namespace, and logicalKey. signal is aborted when the time limit passes; check it in long-running work. In tests, traceProjectionConnections from @sonamu-kit/opensearch/testing finds projections that use connections outside the snapshot.

Envelope and reserved fields

The worker wraps each projection result in an envelope before indexing it. The application document sits under doc, so search bodies refer to fields with the doc. prefix, as in doc.body. A tombstone keeps nothing of the old body. A document may not have sonamu_meta or a name starting with _ at its top level. In a projection result, such a field quarantines the document with reserved_field; in mappings, defineSearch rejects it with reserved_property.

Mapping restrictions

mappings accepts only properties and dynamic at its top level. Top-level-only keys such as _source, _routing, _meta, and dynamic_templates cannot move under doc, so they are rejected with unsupported_mapping_key. The package assembles the index mapping from:
  • Top-level dynamic: "strict", and _meta.sonamu identifying the target
  • A strict sonamu_meta object
  • A doc object holding the definition’s properties. When dynamic is not given it is "strict"
So OpenSearch rejects a document with a field that is not in the mappings (strict_dynamic_mapping_exception), and the worker quarantines that revision. Keep the document schema and the mapped fields in step. If unmapped fields must be accepted, set dynamic explicitly; an explicit dynamic is part of the fingerprint.

Canonical JSON and the projection hash

The worker processes a present document in this order:
  1. It validates the document with the definition’s schema. Every later step uses the value the schema returns, not the original object.
  2. It checks that this value is representable as JSON as is, and makes a copy detached from the input.
  3. It checks for reserved top-level fields.
  4. It computes projection_hash as the SHA-256 of the canonical JSON string, and sends the same copy as doc.
  5. If a single envelope exceeds maxBulkBytes, it quarantines the document (oversized).
The hash and the indexed body come from the same copy, so changing the object the projection returned has no effect on either. Canonical JSON (sonamu-c14n-v1) sorts object keys by UTF-16 code units, keeps array order, adds no whitespace, and writes -0 as 0. It does no Unicode normalization, so NFC and NFD are different values. The state is part of the hash input: present hashes {"document":...,"state":"present"} and deleted hashes {"state":"deleted"}. On rejection the worker quarantines that revision and records one of these reasons: The schema’s output must therefore be JSON. A schema that returns dates as Date objects, for example, is rejected with unsupported_object; the example turns updated_at into a string with toISOString(). In tests, canonicalizeJson and computeProjectionHash from the root entry point apply the same rules.

Fingerprint

defineSearch computes a SHA-256 fingerprint from the canonical JSON of key, projectionVersion, the hash version, the envelope version, settings, mappings, the sorted requiredPlugins, and the input structure version. schema and the functions are not part of it, so whenever you change the meaning of the projection function or the schema, raise projectionVersion. Otherwise one target with one fingerprint ends up holding documents built by both the old and the new rules. A definition with a new fingerprint becomes a new target, because:
  • The package never changes the settings or mappings of an existing index; it only reads mappings.
  • The documents in an existing target were built by the old projection. Overwriting with the new definition would leave every unmarked document in its old state.
  • The worker processes only targets for which it has a definition with a matching (key, fingerprint, hash version), leaves the others untouched, and reports them as unsupportedTargets. A query handle reads only targets whose fingerprint is in its supportedFingerprints.
Changing a definition therefore means deploying the new definition, creating a target with the new fingerprint, filling it from the source, and moving the read pointer. Meanwhile markChanged records intents for every registered write target, so the old and new targets both stay current. Workers with different sets of definitions can run at the same time; each takes only its own targets. The procedure is in Index administration.

Next steps

Transactional indexing

Marking changes together with domain writes

Indexing worker

How projections run and how outcomes are classified