Operations

Configuration

Set up one engine for production in TypeScript, Python, Go, or Rust, check every write and search with a plugin, and look up each engine and index option with its default.

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.

OptionDefaultCovered in
durability.directoryNonePersistence and durability
durability.tier'wal' with a directory or a filesystem adapter, and 'snapshot' with any other adapterPersistence and durability
durability.mode'sync'Persistence and durability
durability.flushIntervalMs1,000Persistence and durability
durability.checkpointIntervalMs300,000Persistence and durability
durability.checkpointMutationThreshold100,000Persistence and durability
durability.segmentMaxBytes64 MiBPersistence and durability
durability.compactionThreshold12Persistence and durability
durability.rewriteBytesPerCheckpoint256 MiBPersistence and durability
persistenceNonePersistence and durability
invalidationNonePersistence and durability
lifecycle.idleTimeoutMs, lifecycle.maxOpenIndexes, and lifecycle.maxOpenBytesNo limitPersistence and durability
lifecycle.maxReopenWaiters64This page
memory.blockWritesAbove0.9Observability
memory.resumeWritesBelow0.8Observability
workers.enabledtrue, except on a browser pagePartitions and workers
workers.countThe host's cores minus one in an embedded engine and every core behind createServer, from 2 to 8Partitions and workers
workers.promotionThreshold1,000 documentsPartitions and workers
workers.idleTimeoutMsFive minutes, or lifecycle.idleTimeoutMs when that is shorterPartitions and workers
workers.mainCopyQueries'lone', and 'none' behind createServerPartitions and workers
workers.bootstrapModuleNonePartitions and workers
workers.silenceBeforeProbeMs10,000This page
workers.silenceBeforeRetirementMs90,000This page
workers.maxThreadsLeftRunning1This page
embedding and embeddingAdaptersNoneEmbedding adapters
rerankAdaptersNoneThis page
rerankTimeout30,000This page
maxRerankWindow100This page
analysis.rebuild'auto'Language support
patternWorkCap25,000,000 unitsFilters and facets
eventsNoneObservability
pluginsNoneThis page
idGeneratorA UUID v7 for each document inserted without an idIndexes 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.

OptionDefaultCovered in
schemaRequiredIndexes and documents
requiredNoneIndexes and documents
strictfalseIndexes and documents
surfaceFormstrueIndexes and documents
bm25k1 of 1.2 and b of 0.75Indexes and documents
language'english'Language support
stopWords and tokenizerThe ones in the language moduleLanguage support
synonymsNoneFull-text search
defaultScoring'local'Full-text search
partitions.maxPartitions1Partitions and workers
partitions.maxDocsPerPartitionNo limitPartitions and workers
partitions.watermarkNone, so the engine emits no partitionWatermark eventPartitions and workers
textStorage'memory'Persistence and durability
vectorPromotionA graph build from 1,024 vectorsVector search
embeddingNoneEmbedding adapters
patternValueLimit8,192 code pointsFilters and facets
trackPositionstrueThis 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