Narsil is a search engine that answers each query inside the process that sends it, so a program in TypeScript, Python, Go, or Rust searches its indexes through a function call, with no server to set up. The four packages compute the same scores for the same query, which is why the four panels of each step on this page show the same bicycles with the same scores. If other programs have to reach your indexes over HTTP, see HTTP server for how a TypeScript process can serve them.
On this page, you'll build one file in which you create a typed index, fill it with a bicycle shop's catalogue, and read a ranked answer. The file is search.ts in TypeScript, search.py in Python, main.go in Go, and src/main.rs in Rust. When you pick a language on any code block, the site shows that language in every code block on these pages until you pick another. Each code block shows the whole file, with green lines marking the lines that you add at each step and red lines marking the lines that you remove.
Install the package
pnpm add -E @delali/narsilThe TypeScript package requires Node.js 22 or later in a server process. It declares a Node.js build and a browser build under one entry point, so that Node.js and a browser bundler each resolve the same import to the build that suits them. The Python package requires Python 3.11 or later, and a Python program imports it as narsil. Because PyPI publishes wheels for Linux, macOS, and Windows on x64 and arm64, pip installs the Python package on those platforms without a compiler. The Go module requires Go 1.26 or later and a C compiler, because the Go toolchain compiles Narsil's C core through cgo along with your program. The Rust crate requires Rust 1.88 or later and a C11 compiler, since Cargo compiles the same C core when it builds the crate. A Rust program imports the crate's library as narsil. The full list of platforms for each language is on the Python, Go, and Rust pages.
Create an engine and an index
You open an engine with one call in each package, which is createNarsil() in TypeScript, Narsil() in Python, engine.New in Go, and Narsil::open in Rust. An engine that you open without settings stores every index in memory. When you create an index, you declare a schema that gives each field a type, which controls which filters can test the field and how the engine tokenises its text. The Python and Rust packages take the schema as the same object of field names and type names that TypeScript takes, while the Go package declares a constant for each type, such as engine.FieldString for string.
import { createNarsil } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: {
name: 'string',
summary: 'string',
maker: 'string',
category: 'enum',
price: 'number',
inStock: 'boolean',
},
language: 'english',
})The base types are string, verbatim, number, boolean, enum, and geopoint, with the list forms string[], verbatim[], number[], boolean[], and enum[], and vector[N] for an of N numbers. The engine splits a string value into words for keyword search, while it indexes a verbatim value as one whole term, which suits a product code or an order number. A string type can take the options sortable, pattern, and partial after a colon, as in string:sortable. A query can sort on a text field only when the field's type includes sortable. A filter can compare the whole value of a text field, as eq and startsWith do, only when the field's type includes pattern. You add each option yourself, because for each option the engine builds an extra index in memory over every document. Every type and option is on Indexes and documents.
The language option, which defaults to english, sets the analyser that tokenises and every text field. Because the English analyser stems both bicycles and bicycle to one term, a search for bicycles returns a document that contains the word bicycle.
Fill the index with documents
insertBatch takes a list of documents and returns a result for each one, while insert stores a single document and returns the id under which the engine stores it. The batch call returns succeeded, which lists the ids that the engine stores, and failed, in which each entry contains the id of one document and the error that the engine raises for it. The engine therefore stores the rest of a batch when it rejects one document. If the middle document in a batch of three contains the string 'nine hundred' in price, for example, the engine stores the other two documents and reports DOC_VALIDATION_FAILED for the middle one. The method is insert_batch in Python and Rust and InsertBatch in Go, where it takes each document as a *engine.Document that engine.DocumentFromMap builds from a map.
import { createNarsil } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: {
name: 'string',
summary: 'string',
maker: 'string',
category: 'enum',
price: 'number',
inStock: 'boolean',
},
language: 'english',
})
await narsil.insertBatch('bicycles', [
{
id: 'urban-commuter',
name: 'Urban commuter',
summary: 'A lightweight aluminium commuter bicycle with hydraulic disc brakes and mudguards fitted as standard.',
maker: 'city-bike-maker',
category: 'city',
price: 749,
inStock: true,
},
{
id: 'folding-metro',
name: 'Metro folding bicycle',
summary: 'A folding bicycle that fits under a train seat and unfolds in fifteen seconds.',
maker: 'folding-bike-maker',
category: 'folding',
price: 899,
inStock: true,
},
{
id: 'folding-tourer',
name: 'Tourer folding bicycle',
summary: 'A folding bicycle with a rear rack and eight gears, sold with a travel bag.',
maker: 'touring-bike-maker',
category: 'folding',
price: 1150,
inStock: false,
},
{
id: 'gravel-explorer',
name: 'Gravel explorer',
summary: 'A steel gravel bicycle built for long unpaved rides, with clearance for 45 millimetre tyres.',
maker: 'gravel-bike-maker',
category: 'gravel',
price: 1299,
inStock: true,
},
{
id: 'cargo-hauler',
name: 'Cargo hauler',
summary: 'An electric cargo bicycle rated to carry two children and a week of shopping.',
maker: 'cargo-bike-maker',
category: 'cargo',
price: 3499,
inStock: true,
},
])Ask the index for a match
query takes the term and returns the hits in ranked order. The document projection lists the fields that the engine returns with each hit. The engine returns at most limit hits, which is three here and 10 when a query leaves limit out. In Python, query takes a dict with the same keys that TypeScript uses. In Go, Query takes a QueryParams struct, in which engine.IncludeFields builds the projection and engine.Some(3) sets an optional number. In Rust, query takes a QueryParams struct of Option fields, in which DocumentProjection::Fields lists the fields to return.
import { createNarsil } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: {
name: 'string',
summary: 'string',
maker: 'string',
category: 'enum',
price: 'number',
inStock: 'boolean',
},
language: 'english',
})
await narsil.insertBatch('bicycles', [
{
id: 'urban-commuter',
name: 'Urban commuter',
summary: 'A lightweight aluminium commuter bicycle with hydraulic disc brakes and mudguards fitted as standard.',
maker: 'city-bike-maker',
category: 'city',
price: 749,
inStock: true,
},
{
id: 'folding-metro',
name: 'Metro folding bicycle',
summary: 'A folding bicycle that fits under a train seat and unfolds in fifteen seconds.',
maker: 'folding-bike-maker',
category: 'folding',
price: 899,
inStock: true,
},
{
id: 'folding-tourer',
name: 'Tourer folding bicycle',
summary: 'A folding bicycle with a rear rack and eight gears, sold with a travel bag.',
maker: 'touring-bike-maker',
category: 'folding',
price: 1150,
inStock: false,
},
{
id: 'gravel-explorer',
name: 'Gravel explorer',
summary: 'A steel gravel bicycle built for long unpaved rides, with clearance for 45 millimetre tyres.',
maker: 'gravel-bike-maker',
category: 'gravel',
price: 1299,
inStock: true,
},
{
id: 'cargo-hauler',
name: 'Cargo hauler',
summary: 'An electric cargo bicycle rated to carry two children and a week of shopping.',
maker: 'cargo-bike-maker',
category: 'cargo',
price: 3499,
inStock: true,
},
])
const results = await narsil.query('bicycles', {
term: 'folding bicycle',
document: { include: ['name', 'maker', 'price'] },
limit: 3,
})
console.log(
JSON.stringify(
results,
(key, value) => (key === 'elapsed' ? undefined : typeof value === 'number' ? Number(value.toFixed(2)) : value),
2
)
)
await narsil.shutdown(){
"hits": [
{
"id": "folding-metro",
"score": 2.77,
"document": {
"name": "Metro folding bicycle",
"maker": "folding-bike-maker",
"price": 899
}
},
{
"id": "folding-tourer",
"score": 1.85,
"document": {
"name": "Tourer folding bicycle",
"maker": "touring-bike-maker",
"price": 1150
}
},
{
"id": "cargo-hauler",
"score": 0.09,
"document": {
"name": "Cargo hauler",
"maker": "cargo-bike-maker",
"price": 3499
}
}
],
"count": 5,
"countExact": true,
"cursor": "eyJ2Ijo0LCJhIjoiY2FyZ28taGF1bGVyIiwicyI6MC4wODg1NTI5MTcxMzMxNDY3NCwiZCI6MywicSI6IjIxZDk4MmFjIn0=",
"coverage": {
"totalPartitions": 1,
"queriedPartitions": 1,
"timedOutPartitions": 0,
"failedPartitions": 0
}
}All five bicycles match, because by default the engine matches a document that contains any one of the query's terms, and every summary contains the word bicycle. The two folding bicycles score 2.77 and 1.85 while the cargo bicycle scores 0.09, since gives a term more weight when fewer documents contain it, and only two of the five documents contain the word folding. The Metro scores above the Tourer because its maker, folding-bike-maker, contains the word folding as well.
Besides the hits, the result contains count, which is the number of documents that match across the index, and countExact, which is true when the engine counts every match. Two more documents match beyond these three hits, so the engine returns a cursor, which you can pass as searchAfter in a later query to fetch them. coverage gives the number of partitions in the index, the number that return results, and the number that time out or fail. This index has one partition. The engine also returns elapsed, which is the time that the query takes. The TypeScript replacer and the Python rounded function drop elapsed so that the panel shows the same output on every run. The Python package returns every key of the result, with None for each part that you don't request, such as facets, and json.dumps prints each None as null. The Go and Rust packages return the result as a struct, with fields such as CountExact in Go and count_exact in Rust, so the Go and Rust programs print each hit and then the count, whether the count is exact, and the cursor.
Narrow the search and mark the matched words
Four options change that answer:
- With
termMatch: 'all', the engine returns only the documents that contain every term. - With
filters.fields, the engine tests one field against a value. - With
boost, the engine multiplies what one field contributes to the score. - With
highlight, the engine wraps each matched word in a tag, which is<mark>unless you setpreTagandpostTag.
The first option is engine.MatchAllTerms() in Go and TermMatch::All in Rust, while the Python package takes the TypeScript names unchanged.
import { createNarsil } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: {
name: 'string',
summary: 'string',
maker: 'string',
category: 'enum',
price: 'number',
inStock: 'boolean',
},
language: 'english',
})
await narsil.insertBatch('bicycles', [
{
id: 'urban-commuter',
name: 'Urban commuter',
summary: 'A lightweight aluminium commuter bicycle with hydraulic disc brakes and mudguards fitted as standard.',
maker: 'city-bike-maker',
category: 'city',
price: 749,
inStock: true,
},
{
id: 'folding-metro',
name: 'Metro folding bicycle',
summary: 'A folding bicycle that fits under a train seat and unfolds in fifteen seconds.',
maker: 'folding-bike-maker',
category: 'folding',
price: 899,
inStock: true,
},
{
id: 'folding-tourer',
name: 'Tourer folding bicycle',
summary: 'A folding bicycle with a rear rack and eight gears, sold with a travel bag.',
maker: 'touring-bike-maker',
category: 'folding',
price: 1150,
inStock: false,
},
{
id: 'gravel-explorer',
name: 'Gravel explorer',
summary: 'A steel gravel bicycle built for long unpaved rides, with clearance for 45 millimetre tyres.',
maker: 'gravel-bike-maker',
category: 'gravel',
price: 1299,
inStock: true,
},
{
id: 'cargo-hauler',
name: 'Cargo hauler',
summary: 'An electric cargo bicycle rated to carry two children and a week of shopping.',
maker: 'cargo-bike-maker',
category: 'cargo',
price: 3499,
inStock: true,
},
])
const results = await narsil.query('bicycles', {
term: 'folding bicycle',
termMatch: 'all',
filters: { fields: { inStock: { eq: true }, price: { lte: 1500 } } },
boost: { name: 3 },
highlight: { fields: ['name'] },
document: { include: ['name', 'maker', 'price'] },
limit: 3,
})
console.log(
JSON.stringify(
results,
(key, value) => (key === 'elapsed' ? undefined : typeof value === 'number' ? Number(value.toFixed(2)) : value),
2
)
)
await narsil.shutdown(){
"hits": [
{
"id": "folding-metro",
"score": 4.52,
"document": {
"name": "Metro folding bicycle",
"maker": "folding-bike-maker",
"price": 899
},
"highlights": {
"name": {
"snippet": "Metro <mark>folding</mark> <mark>bicycle</mark>",
"positions": [
{
"start": 6,
"end": 13
},
{
"start": 14,
"end": 21
}
]
}
}
}
],
"count": 1,
"countExact": true,
"coverage": {
"totalPartitions": 1,
"queriedPartitions": 1,
"timedOutPartitions": 0,
"failedPartitions": 0
}
}Both folding bicycles contain the two words, but the Tourer fails the inStock filter, so the engine returns one bicycle. The filters and termMatch change which documents match without changing any score, so the boost of 3 on name accounts for the rise from 2.77 to 4.52. highlights.name.snippet contains the name with each match wrapped in <mark>, ready to render, while positions gives the start and end offset of each match in the stored text, so that you can mark those spans in the markup of your page.
The search on this site uses Narsil. One route handler indexes every article, project, study, and documentation page, so that it can answer each search query inside the server process.
Upgrade from Narsil 0.3
Every change in 0.4 that can break a 0.3 application or change its results is on Upgrading to 0.4.
Where to go next
- Read Indexes and documents for the full schema, nested fields, and the calls that fetch, update, and remove a document.
- Read Full-text search for how the engine ranks results, tolerates typos, completes prefixes, and suggests corrections.
- Read Vector search to search by meaning, which can find the article that answers a question even when the two share no word.
- Read the Python, Go, and Rust pages for how each package maps the names in these docs onto its language and where it differs from the TypeScript package.