A language module holds the rules for splitting a language's text into words, dropping the commonest ones, and reducing each word to its , so that a search for one form of a word finds the others. On this page, you'll build articles.ts, a program that indexes French and Chinese articles. You can follow it in TypeScript, Python, Go, or Rust, with all four packages printing the same counts. The next program registers a tokeniser and a stop word set, again in all four languages. The last three programs define a custom language and rebuild an index after a language changes. They are in TypeScript alone, because only the TypeScript package accepts a custom language module. Each code block below holds a whole file, with green lines marking the lines that you add at each step and struck lines marking the lines that you remove.
Load a language and index in it
Set language on an index to the name of a language; when you leave it out, the engine uses English. In TypeScript, you import every other language from a separate entry point, such as @delali/narsil/languages/french, so a bundle holds only the languages that the application loads. After you pass a module to registerLanguage, any index can set that module's name. The Python, Go, and Rust packages include every bundled language, so in those languages you set the name with no import. The engine refuses an index whose language it doesn't hold with LANGUAGE_NOT_SUPPORTED.
import { createNarsil, registerLanguage } from '@delali/narsil'
import { french } from '@delali/narsil/languages/french'
registerLanguage(french)
const narsil = await createNarsil()
await narsil.createIndex('articles-fr', {
schema: { title: 'string', body: 'string' },
language: 'french',
})
await narsil.insertBatch('articles-fr', [
{ id: 'recherche-vectorielle', title: 'La recherche vectorielle expliquée', body: 'Les vecteurs capturent le sens au-delà des mots exacts.' },
{ id: 'cafe-de-quartier', title: 'Un café pour chaque quartier', body: 'Le livreur traverse la ville à vélo avec des cafés chauds.' },
])
for (const term of ['vecteur', 'vectoriel', 'cafe', 'vélo', 'velo', 'le']) {
const results = await narsil.query('articles-fr', { term, limit: 0 })
console.log(term, results.count)
}
await narsil.shutdown()vecteur 1
vectoriel 1
cafe 1
vélo 1
velo 0
le 0The French stemmer reduces vecteurs to vecteur and vectorielle to vectoriel, so a search for either form finds the article. The engine drops le from the index as a stop word. However, the engine keeps every accent under the French module. A search for cafe finds café only because the stemmer strips the final é as an ending. The same stemmer keeps the é in vélo, so a search for velo doesn't find the article that holds vélo. The engine keeps ñ under the Spanish module in the same way, so a Spanish index treats montaña and montana as separate words.
Index a language written without spaces
Under the modules for Chinese, Japanese, Korean, Thai, Lao, Khmer, and Burmese, the engine cuts every run of script into overlapping pairs of characters in place of words, because writers of most of those languages put no spaces between words. The program creates articles-zh on the same engine as the French index. Each index keeps the language that you set when you create it, so the two indexes can share one engine.
import { createNarsil, registerLanguage } from '@delali/narsil'
import { chinese } from '@delali/narsil/languages/chinese'
import { french } from '@delali/narsil/languages/french'
registerLanguage(french)
registerLanguage(chinese)
const narsil = await createNarsil()
await narsil.createIndex('articles-fr', {
schema: { title: 'string', body: 'string' },
language: 'french',
})
await narsil.insertBatch('articles-fr', [
{ id: 'recherche-vectorielle', title: 'La recherche vectorielle expliquée', body: 'Les vecteurs capturent le sens au-delà des mots exacts.' },
{ id: 'cafe-de-quartier', title: 'Un café pour chaque quartier', body: 'Le livreur traverse la ville à vélo avec des cafés chauds.' },
])
await narsil.createIndex('articles-zh', {
schema: { title: 'string', body: 'string' },
language: 'chinese',
})
await narsil.insert('articles-zh', {
id: 'shenzhen-metro',
title: '深圳地铁票价查询',
body: '乘客可以在车站的自助机上查询票价。',
})
for (const term of ['vecteur', 'vectoriel', 'cafe', 'vélo', 'velo', 'le']) {
for (const term of ['地铁', '铁票', '深圳地铁', '地', '票价']) {
const results = await narsil.query('articles-fr', { term, limit: 0 })
const results = await narsil.query('articles-zh', { term, limit: 0 })
console.log(term, results.count)
}
await narsil.shutdown()地铁 1
铁票 1
深圳地铁 1
地 0
票价 1The engine indexes every overlapping pair, so 地铁 and 票价 match the article. 铁票 matches as well, although that pair crosses the boundary between two words. A longer term matches when every pair inside it appears in the document, which is why 深圳地铁 matches too. However, a single character such as 地 matches no document, because the engine indexes only pairs.
Each index has one language, which the engine applies to all of the index's text, so a search on a document that mixes two scripts matches only the text that the language keeps. Under French, the engine drops the Chinese from a document that mixes the two, so a search for 深圳 on a French index matches no document. Under English, the engine keeps the Chinese, but it matches a run of Chinese only as a whole. A search for 深圳地铁 therefore finds the document, while a search for 深圳 doesn't. On a Chinese index, a search for café or caf finds café, while a search for cafe doesn't.
See which languages come with Narsil
Every Narsil package includes the same modules for more than 100 languages. Thirty-seven of them contain a stemmer as well as the rules for splitting words and dropping stop words: Arabic, Armenian, Basque, Bulgarian, Catalan, Czech, Danish, Dutch, English, Esperanto, Estonian, Finnish, French, German, Greek, Hindi, Hungarian, Indonesian, Irish, Italian, Lithuanian, Nepali, Norwegian, Persian, Polish, Portuguese, Romanian, Russian, Sanskrit, Serbian, Slovenian, Spanish, Swahili, Swedish, Tamil, Turkish, and Ukrainian. The seven modules for the languages written without spaces cut text into the overlapping pairs above, while each of the others contains rules for splitting words and dropping stop words but no stemmer. Twenty-one modules also contain a normaliser, which folds the spellings that are optional in a writing system into one form before the stemmer reduces a word. You can load any of them in the same way that articles.ts loads French and Chinese.
Register a tokeniser and a stop word set
A checkpoint can store the name of a tokeniser or a stop word function but none of its code, so a durable engine refuses an inline tokeniser or stop word function with CONFIG_INVALID. The message of that error says to register the code and pass its name. When you register an implementation, the engine stores it under a name, which you can then set on an index in place of the inline form. In TypeScript, you register through the registerTokenizer and registerStopWords functions, while in Python, Go, and Rust, you register through methods on the engine. In the program below, the tokeniser on the parts index splits text on spaces alone, so that it keeps a product code whole. On the listings index, the engine drops refurbished from every search.
import { createNarsil, registerStopWords, registerTokenizer } from '@delali/narsil'
registerTokenizer('product-codes', {
tokenize: (text) =>
text
.toLowerCase()
.split(/\s+/)
.filter((token) => token.length > 0)
.map((token, position) => ({ token, position })),
})
registerStopWords('catalogue-noise', (defaults) => new Set([...defaults, 'refurbished']))
const narsil = await createNarsil()
await narsil.createIndex('parts', { schema: { code: 'string' }, tokenizer: 'product-codes' })
await narsil.createIndex('listings', { schema: { title: 'string' }, stopWords: 'catalogue-noise' })
await narsil.insert('parts', { id: 'brake-set', code: 'SKU-4821 hydraulic brake set' })
await narsil.insert('listings', { id: 'folding-metro', title: 'Refurbished folding bicycle' })
const searches: Array<[string, string]> = [
['parts', 'sku-4821'],
['parts', '4821'],
['listings', 'refurbished'],
['listings', 'folding'],
]
for (const [indexName, term] of searches) {
const results = await narsil.query(indexName, { term, limit: 0 })
console.log(indexName, term, results.count)
}
await narsil.shutdown()parts sku-4821 1
parts 4821 0
listings refurbished 0
listings folding 1On the parts index, a search for the whole code finds the part, while a search for the fragment 4821 doesn't, because the tokeniser keeps SKU-4821 as one token. Under the default English analysis, the engine splits the code at the hyphen, so both searches match. A custom tokeniser takes the place of the whole analysis, so on that index the engine neither stems words nor drops stop words. With a whitespace tokeniser, a search for running finds a document that holds running, while a search for run doesn't. The engine refuses an index whose settings hold the name of an unregistered tokeniser or stop word set with CONFIG_INVALID. In TypeScript, the error's details.available holds the names that you register.
Write a custom language
Only the TypeScript package accepts a custom language module, so the examples from here to the end of the page are in TypeScript. The Python, Go, and Rust packages also report a stale index and rebuild it, which you'll need when an upgrade changes the revision of a bundled language.
registerLanguage accepts any object that fits the exported LanguageModule type. That type holds a name, a revision, a stemmer or null, and a stopWords set, along with an optional normalizer and tokenizer. The shortest module extends a bundled one, so legal.ts keeps the English stemmer and adds three words of legal boilerplate to the English stop words.
import { createNarsil, type LanguageModule, registerLanguage } from '@delali/narsil'
import { english } from '@delali/narsil/languages/english'
const englishLegal: LanguageModule = {
...english,
name: 'english-legal',
revision: '1',
stopWords: new Set([...english.stopWords, 'herein', 'thereof', 'whereas']),
}
registerLanguage(englishLegal)
const narsil = await createNarsil()
await narsil.createIndex('contracts', { schema: { clause: 'string' }, language: 'english-legal' })
await narsil.insert('contracts', {
id: 'clause-12',
clause: 'Whereas the supplier delivers the goods herein described, payment falls due within thirty days.',
})
for (const term of ['whereas', 'supplier', 'delivering']) {
const results = await narsil.query('contracts', { term, limit: 0 })
console.log(term, results.count)
}
await narsil.shutdown()whereas 0
supplier 1
delivering 1A search for whereas matches no document, because the engine drops it as a stop word, while a search for delivering finds delivers through the English stemmer. Give a new module the revision '1'. Change that string whenever you change the module's stemmer, normaliser, stop words, or tokeniser rules, because the engine compares the string to find the indexes whose terms come from the old rules.
Find the indexes that a language change makes stale
With each index, the engine records the revision under which it builds that index's terms. When a durable engine opens the index, it compares that record with the revision that the module holds at that time, and if the two differ, it marks the index stale. A release of @delali/narsil that corrects a stemmer comes with a new revision for that module, so after the upgrade, the engine marks stale every index whose terms come from before the upgrade. revisions.ts builds an index under revision '1' and shuts the engine down. It then opens the index again under revision '2', which is the same change that such an upgrade makes to a bundled module. With rebuild: 'manual', the engine skips the automatic rebuild, so that the index stays stale for you to inspect.
import { mkdirSync, rmSync } from 'node:fs'
import { createNarsil, registerLanguage } from '@delali/narsil'
import { swahili } from '@delali/narsil/languages/swahili'
rmSync('./narsil-revisions', { recursive: true, force: true })
mkdirSync('./narsil-revisions', { recursive: true })
registerLanguage({ ...swahili, name: 'swahili-news', revision: '1' })
const first = await createNarsil({ durability: { directory: './narsil-revisions' } })
await first.createIndex('habari', {
schema: { title: 'string', body: 'string' },
language: 'swahili-news',
})
await first.insert('habari', {
id: 'soko-la-mombasa',
title: 'Soko la Mombasa lafunguliwa upya',
body: 'Wafanyabiashara wa samaki warudi sokoni baada ya ukarabati.',
})
await first.checkpoint('habari')
await first.shutdown()
registerLanguage({ ...swahili, name: 'swahili-news', revision: '2' })
const second = await createNarsil({
durability: { directory: './narsil-revisions' },
analysis: { rebuild: 'manual' },
})
const stale = await second.query('habari', { term: 'soko' })
console.log(JSON.stringify({ indexes: second.listIndexes(), stale: stale.analysisStale }, null, 2))
await second.shutdown(){
"indexes": [
{
"name": "habari",
"documentCount": 1,
"partitionCount": 1,
"language": "swahili-news",
"state": "open",
"reopenCount": 0,
"analysisStale": true
}
],
"stale": true
}The engine keeps answering searches on a stale index from the terms that the index holds, while it marks each result with analysisStale: true, which is the same flag that listIndexes reports for the index.
Rebuild the terms
The engine rebuilds a stale index in the background by default. Under rebuild: 'manual', the engine leaves every stale index as it is until you call rebuildAnalysis(indexName), which resolves once every partition of that index holds current terms. The engine emits an analysisRebuild event as each rebuild starts and again as it completes.
import { mkdirSync, rmSync } from 'node:fs'
import { createNarsil, registerLanguage } from '@delali/narsil'
import { swahili } from '@delali/narsil/languages/swahili'
rmSync('./narsil-revisions', { recursive: true, force: true })
mkdirSync('./narsil-revisions', { recursive: true })
registerLanguage({ ...swahili, name: 'swahili-news', revision: '1' })
const first = await createNarsil({ durability: { directory: './narsil-revisions' } })
await first.createIndex('habari', {
schema: { title: 'string', body: 'string' },
language: 'swahili-news',
})
await first.insert('habari', {
id: 'soko-la-mombasa',
title: 'Soko la Mombasa lafunguliwa upya',
body: 'Wafanyabiashara wa samaki warudi sokoni baada ya ukarabati.',
})
await first.checkpoint('habari')
await first.shutdown()
registerLanguage({ ...swahili, name: 'swahili-news', revision: '2' })
const second = await createNarsil({
durability: { directory: './narsil-revisions' },
analysis: { rebuild: 'manual' },
})
const progress: string[] = []
second.on('analysisRebuild', (event) => {
progress.push(`${event.status} ${event.partitionsRebuilt}/${event.partitionCount}`)
})
const stale = await second.query('habari', { term: 'soko' })
for (const index of second.listIndexes()) {
if (index.analysisStale) await second.rebuildAnalysis(index.name)
}
const current = await second.query('habari', { term: 'soko' })
console.log(JSON.stringify({ indexes: second.listIndexes(), stale: stale.analysisStale }, null, 2))
console.log(
JSON.stringify(
{
beforeRebuild: { count: stale.count, analysisStale: stale.analysisStale },
progress,
afterRebuild: { count: current.count, analysisStale: current.analysisStale },
},
null,
2
)
)
await second.shutdown(){
"beforeRebuild": {
"count": 1,
"analysisStale": true
},
"progress": [
"started 0/1",
"completed 1/1"
],
"afterRebuild": {
"count": 1
}
}The search finds the article before and after the rebuild. Once the index holds current terms, analysisStale is absent from the result, because the engine sets the flag only while stale terms remain. When the rebuild completes, a durable engine writes the new revision into the index, so the engine finds the index current on its next start.
Hear about a stale index at start-up
When the engine opens a directory, it calls onStaleAnalysis once for each stale index that it finds. The callback is the one place where you receive the stored and the current revision together. Its second argument is a function that starts the rebuild for that index. stale-watch.ts opens the directory that revisions.ts writes, under a third revision, so start revisions.ts first.
import { createNarsil, registerLanguage } from '@delali/narsil'
import { swahili } from '@delali/narsil/languages/swahili'
registerLanguage({ ...swahili, name: 'swahili-news', revision: '3' })
const narsil = await createNarsil({
durability: { directory: './narsil-revisions' },
analysis: {
rebuild: 'manual',
onStaleAnalysis: (index) => {
console.log(`${index.indexName} holds terms from revision ${index.storedRevision}, while ${index.language} is at revision ${index.currentRevision}`)
},
},
})
await narsil.shutdown()habari holds terms from revision 2, while swahili-news is at revision 3The engine reports that the index holds terms from revision 2, which come from the rebuild in revisions.ts, while the module holds revision 3.
Where to go next
- Read Full-text search for the ranking and the typo tolerance that the engine applies to these terms.
- Read Indexes and documents for the other index options, such as
stopWordsandtokenizer. - Read Persistence and durability for the recovery, during which the engine compares the revisions.