The engine settings apply to every index in the process, while the index settings apply to one index. Build the engine once, in a separate module, and import it wherever you need it, because one engine serves every index in the process. On this page, you'll build support-desk, a program that configures an engine for a support desk and then adds a plugin that checks every ticket before the engine stores it. Each code block below contains the whole file, where green lines show the lines that you add at each step and struck lines show the lines that you remove. The two tables at the end contain every option, with its default and the page where you can read more about it.
The Python package accepts the same setting names as the TypeScript package, in a dict. The Go module and the Rust crate accept typed structs whose fields have the same names in the usual style of each language. For example, idleTimeoutMs is IdleTimeout in Go, as a time.Duration, and idle_timeout_ms in Rust.
Configure the engine in one module
The engine in the program below writes its indexes to a directory on the write-ahead-log tier, where it forces every write to disk before the call resolves. With workers.count: 4, the TypeScript engine has a budget of four threads, which it splits into two copies of each large index and two threads for vector search. Under mainCopyQueries: 'none', the TypeScript engine sends every search on an index that has copies to one of those copies so that the main thread is free to answer HTTP requests. The Go module loads one copy of each index and answers the searches on that index from a pool of goroutines once the index contains 1,000 documents. The Rust crate and the Python package check the workers settings in the same way as the TypeScript package, while they store one copy of each index, which every thread searches. The same settings therefore work in all four languages. Under lifecycle, every engine releases an index from memory after ten minutes without a read or a write, and it allows at most 20 open indexes.
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
const narsil = await createNarsil({
durability: { directory: mkdtempSync(join(tmpdir(), 'narsil-support-')) },
workers: { count: 4, mainCopyQueries: 'none' },
lifecycle: { idleTimeoutMs: 600_000, maxOpenIndexes: 20 },
})
await narsil.createIndex('tickets', {
schema: { subject: 'string', body: 'string', priority: 'enum' },
required: ['subject'],
strict: true,
})
await narsil.shutdown()The engine checks each value before it starts, and for a bad value, it throws CONFIG_INVALID with a message that includes the name of the option, such as durability.mode must be "sync" or "async", got "fast". The engine also throws that code for a workers.idleTimeoutMs longer than lifecycle.idleTimeoutMs, because the engine has to drop the worker copies of an index before it closes the index. Only the TypeScript package refuses lifecycle on an engine without durability. The same package is also the only one that refuses a relative workers.bootstrapModule. The TypeScript and Python packages also refuse an unknown key, at the top level or inside a block such as workers, so they refuse a misspelt durabilty. In TypeScript, the message lists every setting that the engine accepts at that level. The TypeScript compiler also rejects the same key when you pass the object straight to createNarsil. In Go and Rust, the compiler rejects a misspelt field.
Check every ticket with a plugin
A plugin is an object of hooks that the engine calls before and after each operation. The engine refuses a plugin without a name with CONFIG_INVALID, because it puts that name in each error that the plugin causes. The engine calls a before hook first, and the hook can reject the operation by throwing or by returning an error. The engine then stores whatever the hook leaves in the document, so the same hook can clean a ticket before the engine indexes it. The engine calls an after hook once the operation succeeds, so you can use one to write an audit log. The TypeScript, Python, and Go packages accept plugins in the engine settings, while in Rust, you add each plugin with add_plugin.
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
import { createNarsil, ErrorCodes, isNarsilError, NarsilError, type NarsilPlugin } from '@delali/narsil'
const searches: Array<{ term: string | undefined; count: number | undefined }> = []
const ticketRules: NarsilPlugin = {
name: 'ticket-rules',
beforeInsert: (context) => {
const subject = String(context.document.subject ?? '').trim()
if (subject === '') {
throw new NarsilError(ErrorCodes.DOC_VALIDATION_FAILED, 'A ticket needs a subject', { field: 'subject' })
}
context.document.subject = subject
},
afterSearch: (context) => {
searches.push({ term: context.params.term, count: context.results?.count })
},
}
const narsil = await createNarsil({
durability: { directory: mkdtempSync(join(tmpdir(), 'narsil-support-')) },
workers: { count: 4, mainCopyQueries: 'none' },
lifecycle: { idleTimeoutMs: 600_000, maxOpenIndexes: 20 },
plugins: [ticketRules],
})
await narsil.createIndex('tickets', {
schema: { subject: 'string', body: 'string', priority: 'enum' },
required: ['subject'],
strict: true,
})
await narsil.insert('tickets', {
id: 'ticket-1001',
subject: ' Refund not received ',
body: 'My refund for order 5521 has not reached my card.',
priority: 'high',
})
let rejected = ''
try {
await narsil.insert('tickets', {
id: 'ticket-1002',
subject: ' ',
body: 'The parcel for order 5530 arrived damaged.',
priority: 'low',
})
} catch (error) {
if (!isNarsilError(error)) throw error
rejected = `${error.code}: ${error.message}`
}
await narsil.query('tickets', { term: 'refund' })
const stored = await narsil.get('tickets', 'ticket-1001')
console.log(JSON.stringify({ storedSubject: stored?.subject, rejected, searches }, null, 2))
await narsil.shutdown(){
"storedSubject": "Refund not received",
"rejected": "DOC_VALIDATION_FAILED: A ticket needs a subject",
"searches": [
{
"term": "refund",
"count": 1
}
]
}The engine stores the first ticket with its subject trimmed but refuses the second ticket before indexing it. The hook raises a Narsil error under DOC_VALIDATION_FAILED, so the caller handles that error in the same way as any other failure of the engine. When a hook raises any other error, such as a plain Error in TypeScript, an exception in Python, or a plain error in Go, the engine converts that error into a Narsil error under DOC_VALIDATION_FAILED, whose message contains the text of the original error. The engine converts the error in the same way for a single insert and in the list of failures from a batch. A Rust hook returns a NarsilError itself, while the engine refuses the write under DOC_VALIDATION_FAILED when the hook panics. When an afterSearch hook fails, the caller receives the results, because the engine finishes the search before it calls the hook.
The engine waits for each hook to return, so slow work inside a hook delays each write or search behind it. The plugin interface has the same before and after pairs for updates, removals, and searches. In every language, the engine also calls a hook when it creates or drops an index, and when a rebalance changes the partition count of an index. The TypeScript engine calls one more hook when it loads worker copies. The engine calls no hook for suggest, because it answers that call from the term dictionary and searches no document.
Every engine option
You pass these options to createNarsil in TypeScript, to Narsil in Python, to engine.New in Go, and to Narsil::open in Rust. The engine uses the default in the second column for each option that you leave out.
| Option | Default | Covered in |
|---|---|---|
durability.directory | None | Persistence and durability |
durability.tier | 'wal' with a directory or a filesystem adapter, and 'snapshot' with any other adapter | Persistence and durability |
durability.mode | 'sync' | Persistence and durability |
durability.flushIntervalMs | 1,000 | Persistence and durability |
durability.checkpointIntervalMs | 300,000 | Persistence and durability |
durability.checkpointMutationThreshold | 100,000 | Persistence and durability |
durability.segmentMaxBytes | 64 MiB | Persistence and durability |
durability.compactionThreshold | 12 | Persistence and durability |
durability.rewriteBytesPerCheckpoint | 256 MiB | Persistence and durability |
persistence | None | Persistence and durability |
invalidation | None | Persistence and durability |
lifecycle.idleTimeoutMs, lifecycle.maxOpenIndexes, and lifecycle.maxOpenBytes | No limit | Persistence and durability |
lifecycle.maxReopenWaiters | 64 | This page |
memory.blockWritesAbove | 0.9 | Observability |
memory.resumeWritesBelow | 0.8 | Observability |
workers.enabled | true, except on a browser page | Partitions and workers |
workers.count | The host's cores minus one in an embedded engine and every core behind createServer, from 2 to 8 | Partitions and workers |
workers.promotionThreshold | 1,000 documents | Partitions and workers |
workers.idleTimeoutMs | Five minutes, or lifecycle.idleTimeoutMs when that is shorter | Partitions and workers |
workers.mainCopyQueries | 'lone', and 'none' behind createServer | Partitions and workers |
workers.bootstrapModule | None | Partitions and workers |
workers.silenceBeforeProbeMs | 10,000 | This page |
workers.silenceBeforeRetirementMs | 90,000 | This page |
workers.maxThreadsLeftRunning | 1 | This page |
embedding and embeddingAdapters | None | Embedding adapters |
rerankAdapters | None | This page |
rerankTimeout | 30,000 | This page |
maxRerankWindow | 100 | This page |
analysis.rebuild | 'auto' | Language support |
patternWorkCap | 25,000,000 units | Filters and facets |
events | None | Observability |
plugins | None | This page |
idGenerator | A UUID v7 for each document inserted without an id | Indexes and documents |
lifecycle.maxReopenWaiters is the number of calls that can wait while the engine loads a closed index back into memory. The engine refuses each call beyond that number with INDEX_REOPEN_CAPACITY_EXHAUSTED, so the queue behind a closed index is at most that long.
The silenceBeforeProbeMs, silenceBeforeRetirementMs, and maxThreadsLeftRunning settings apply to the worker threads of the TypeScript engine. The engine sends a probe to a worker that gives no answer for silenceBeforeProbeMs. When a worker answers neither a request nor a probe for silenceBeforeRetirementMs, the engine retires and replaces that worker. A retired thread with open HTTP connections can go on working in the background, while maxThreadsLeftRunning caps the number of such threads at any one time.
The engine can send the top hits of a query to a rerank adapter, which you register under a name in rerankAdapters. The engine sends at most maxRerankWindow hits from one query, a limit that you can set from 1 to 1,000. The engine cancels a call that takes longer than rerankTimeout milliseconds and fails the query with RERANK_FAILED. In Go and Rust, MaxRerankWindow and RerankTimeout, or max_rerank_window and rerank_timeout_ms, set the same limits.
Some options are only in the TypeScript package. The Python package, the Go module, and the Rust crate accept no invalidation, no workers.bootstrapModule, and none of the three settings above for worker threads. The Go module and the Rust crate accept durability without rewriteBytesPerCheckpoint, while the Python package accepts that option.
Every index option
You pass these options to createIndex in TypeScript, CreateIndex in Go, and create_index in Python and Rust. Only schema is required.
| Option | Default | Covered in |
|---|---|---|
schema | Required | Indexes and documents |
required | None | Indexes and documents |
strict | false | Indexes and documents |
surfaceForms | true | Indexes and documents |
bm25 | k1 of 1.2 and b of 0.75 | Indexes and documents |
language | 'english' | Language support |
stopWords and tokenizer | The ones in the language module | Language support |
synonyms | None | Full-text search |
defaultScoring | 'local' | Full-text search |
partitions.maxPartitions | 1 | Partitions and workers |
partitions.maxDocsPerPartition | No limit | Partitions and workers |
partitions.watermark | None, so the engine emits no partitionWatermark event | Partitions and workers |
textStorage | 'memory' | Persistence and durability |
vectorPromotion | A graph build from 1,024 vectors | Vector search |
embedding | None | Embedding adapters |
patternValueLimit | 8,192 code points | Filters and facets |
trackPositions | true | This page |
With trackPositions, the engine records the position of each term in a field so that it can compare those positions in a phrase search. On an index with trackPositions: false, the engine stores less, but it refuses a phrase search with SEARCH_INVALID_PHRASE. Highlighting works with either setting, because the highlighter analyses the stored text again.
Where to go next
- Read Persistence and durability for the tiers, the checkpoints, and the lifecycle limits.
- Read Partitions and workers for the partition limits and the worker copies.