Operations

Native search core

See which search work Narsil does in its C core, what each language needs to build or load that core, how to fail a deployment that lacks it, and how to keep a bundler from leaving it out.

In release 0.4 and later, Narsil does all of its search work in a core written in C. The core splits text into words, matches and scores keyword queries, evaluates filters, counts facets, sorts and groups the hits, marks the matched words, suggests terms, fuses hybrid rankings, and searches vector fields. On Node.js, the TypeScript package loads a prebuilt core. Each Python wheel contains the core, while for Go and Rust, the build compiles the core from the same C sources along with your program. In a browser, and on a Node.js host where the engine can't load the core, the TypeScript package does the same work through WebAssembly and TypeScript, which return the same hits with the same scores. The path therefore affects only how long a search takes, because the hits and the scores are the same on both paths.

What each package needs for the core

PackageWhere the core comes fromWhere the core is missing
TypeScript on Node.js@delali/narsil installs a prebuilt core as an optional dependency for macOS, Linux, and Windows on arm64 and x64, and each Linux package holds a second build for musl.The engine does the work through WebAssembly and TypeScript.
TypeScript in a browserThe browser build contains no C code.The engine always does the work through WebAssembly and TypeScript.
PythonEach wheel on PyPI contains the core, for Linux with glibc or musl, macOS, and Windows, on x64 and arm64.PyPI has these wheels and no source package, so pip finds nothing to install on any other platform.
GoThe module contains the C sources, which cgo compiles with your program, so a build needs a C compiler.A build with CGO_ENABLED=0 stops with compile errors.
RustThe build script of the crate compiles the C sources, so a build needs a C11 compiler, which is clang-cl on Windows with the MSVC toolchain.The build stops with an error.

The six platform packages for Node.js are @delali/narsil-native- followed by darwin-arm64, darwin-x64, linux-arm64, linux-x64, win32-arm64, or win32-x64, and your package manager installs the one that matches the machine. On Linux, the engine loads the musl build when the system has no glibc, as on Alpine. When you install without optional dependencies, as with npm install --omit=optional, the package manager skips the platform package, so the engine falls back. Read the Go and Rust pages for the C compiler to install on each platform.

Get the same answer on either path

This section applies to the TypeScript package, which is the only package that can search without the core. The program below indexes five help-centre articles, each with a 384-number embedding that all-MiniLM-L6-v2 computes in the same process. It then sends the same question as a keyword query, a vector query, and a hybrid query.

same-results.ts
import { createNarsil } from '@delali/narsil'
import { createTransformersEmbedding } from '@delali/narsil-embeddings-transformers'
 
const embedding = createTransformersEmbedding({ dimensions: 384 })
 
const articles = [
  {
    id: 'refund-timing',
    title: 'How a refund reaches your bank',
    body: 'A refund returns to the card that paid for the order, and your bank posts it within five working days.',
  },
  {
    id: 'parcel-tracking',
    title: 'Track a parcel after dispatch',
    body: 'Every dispatched order has a tracking code, and the carrier updates it at each depot.',
  },
  {
    id: 'card-declined',
    title: 'Why a card payment was declined',
    body: 'The issuing bank declines a payment when the card has expired or the billing address does not match.',
  },
  {
    id: 'password-reset',
    title: 'Reset the password on your account',
    body: 'A reset link arrives by email and stays valid for one hour.',
  },
  {
    id: 'billing-statement',
    title: 'Read your monthly billing statement',
    body: 'The statement lists every charge, every refund, and the fees deducted before payout.',
  },
]
 
const vectors = await embedding.embedBatch(
  articles.map((article) => `${article.title}. ${article.body}`),
  'document'
)
 
const narsil = await createNarsil()
 
await narsil.createIndex('articles', {
  schema: { title: 'string', body: 'string', embedding: 'vector[384]' },
})
 
await narsil.insertBatch(
  'articles',
  articles.map((article, position) => ({ ...article, embedding: vectors[position] }))
)
 
const question = 'when does a refund reach my bank'
const questionVector = await embedding.embed(question, 'query')
 
const keyword = await narsil.query('articles', { term: question, limit: 3, document: false })
 
const similar = await narsil.query('articles', {
  mode: 'vector',
  vector: { field: 'embedding', value: questionVector },
  limit: 3,
  document: false,
})
 
const fused = await narsil.query('articles', {
  mode: 'hybrid',
  term: question,
  vector: { field: 'embedding', value: questionVector },
  limit: 3,
  document: false,
})
 
const ranked = (hits: { id: string; score?: number }[]): string[] =>
  hits.map((hit) => `${hit.id} ${hit.score?.toFixed(4)}`)
 
console.log(JSON.stringify({ keyword: ranked(keyword.hits), similar: ranked(similar.hits), fused: ranked(fused.hits) }, null, 2))
 
await narsil.shutdown()
{
  "keyword": [
    "refund-timing 4.8246",
    "billing-statement 0.8755",
    "card-declined 0.8755"
  ],
  "similar": [
    "refund-timing 0.7924",
    "billing-statement 0.4142",
    "password-reset 0.2783"
  ],
  "fused": [
    "refund-timing 0.0328",
    "billing-statement 0.0323",
    "card-declined 0.0315"
  ]
}

When you start the program with NARSIL_SEARCH_BACKEND=wasm in the environment, it prints the same panel as it does without the variable. In a larger check with 3,000 articles, which is enough for the engine to build a vector graph, every keyword, vector, and hybrid score matches to the last digit across the two paths. A Node.js server and a browser tab therefore rank the same index in the same order, so a host that falls back answers each query with the same ranking.

Fail a deployment that lacks the core

This section applies to the TypeScript package. By default, the engine loads the core at the first insert or search. When it can't load the core, it writes one line to standard error from each thread that falls back:

Narsil searches through WebAssembly on this thread, because this installation has no "@delali/narsil-native-darwin-arm64" package.

With NARSIL_REQUIRE_NATIVE_CORE=1 in the environment, createNarsil loads the core as it starts, and it fails with CONFIG_INVALID when the core doesn't load. A check therefore only has to start an engine and shut it down.

check-core.ts
import { createNarsil } from '@delali/narsil'
 
const narsil = await createNarsil()
 
await narsil.shutdown()

Start the check with the variable set, as a step before the host receives traffic:

NARSIL_REQUIRE_NATIVE_CORE=1 node check-core.ts

The script exits with 0 when the engine loads the core. When the platform package is missing, the script exits with 1 and prints an error with the message NARSIL_REQUIRE_NATIVE_CORE is 1, yet this installation has no "@delali/narsil-native-darwin-arm64" package, with the platform of that host in the package name. On a host with the HTTP server, GET /version returns a vectorSearch field. The field holds native when the thread that answers the request loads the core, and wasm when that thread falls back.

Choose the path for a process

With two more variables, you can choose the path that a TypeScript process takes.

  • With NARSIL_SEARCH_BACKEND=wasm, the process uses WebAssembly and TypeScript without the warning, which helps when you compare the two paths. The variable also accepts native, which is the default, while createNarsil fails with CONFIG_INVALID for any other value.
  • With NARSIL_NATIVE_CORE_PATH, you give the absolute path of a core that you build from source, so that the engine loads that core in place of the platform package. When no file exists at that path, the engine falls back with the warning.

The engine also falls back when the core reports a different version of its interface from the one that the engine needs, and in that case, it prints both versions in the warning.

Keep Narsil out of your bundle

The engine finds the platform package at run time, starting from the location of its module, so a bundler that follows your imports leaves the package out. When a deployment holds only the bundle, the engine finds no platform package, so it falls back. The bundler also leaves out the file from which the engine starts each worker thread, so a bundled engine answers every query on the main thread and prints a warning as it starts. When you set workers.enabled: true, createNarsil fails with CONFIG_INVALID in place of printing that warning.

Mark @delali/narsil as external in your bundler, so that the application loads it from node_modules at run time. In Next.js, list it in serverExternalPackages:

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  serverExternalPackages: ['@delali/narsil'],
}
 
export default nextConfig

With esbuild, pass --external:@delali/narsil, and with webpack, list the package under externals.

Where to go next

  • Read Vector search for the graph that the core builds and searches for each vector field.
  • Read Partitions and workers for the worker threads, each of which loads a separate instance of the core.