query performs a full-text search unless you choose another mode. The engine breaks the term into words, stems each word, and ranks every document that contains a match with . On this page, you'll build one file that refines a single search step by step, and a second short file at the end that scores a search across partitions. Every option on this page is in all four packages, which print the same scores because they share one native core. Each code block below shows the whole file, with green lines marking the lines that you add at each step and struck lines marking the lines that you remove.
Rank the documents that match
With no other option, the engine searches every text field in the schema, which here means name, summary, maker, and each entry in tags. A small show function sends a search with document turned off, so that the engine returns each hit as only its id and its score, and then prints both.
import { createNarsil, type QueryParams } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: { name: 'string', summary: 'string:partial', maker: 'string', tags: 'string[]' },
})
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',
tags: ['commuter', 'aluminium'],
},
{
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',
tags: ['gravel', 'steel'],
},
{
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',
tags: ['folding', 'commuter'],
},
{
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',
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting, weighed at 7.4 kilograms.',
maker: 'road-bike-maker',
tags: ['road', 'carbon'],
},
{
id: 'city-step',
name: 'Step-through city bicycle',
summary: 'A step-through city bicycle with a chain guard, a basket, and a hub dynamo.',
maker: 'city-bike-maker',
tags: ['commuter', 'steel'],
},
])
const show = async (params: QueryParams): Promise<void> => {
const results = await narsil.query('bicycles', { ...params, document: false })
for (const hit of results.hits) {
console.log(hit.id, hit.score?.toFixed(2))
for (const [field, match] of Object.entries(hit.highlights ?? {})) {
console.log(` ${field}: ${match.snippet}`)
}
}
}
await show({ term: 'commuter bicycle' })
await narsil.shutdown()urban-commuter 2.17
city-step 0.84
folding-metro 0.84
cargo-hauler 0.07
road-racer 0.07
gravel-explorer 0.07Six bicycles match, because by default the engine matches a document that contains any one of the words, and every summary contains the word 'bicycle'. The urban commuter scores 2.17 since it contains 'commuter' in its name, its summary, and its tags, while the step-through and folding bicycles contain that word only in their tags and score 0.84. The other three score 0.07, since they contain only the word 'bicycle', and BM25 gives almost no weight to a word that every document contains. The English analyser also drops such as 'the', so a search for 'the' alone matches no document.
Search the fields that matter, and weight one of them
fields limits the search to the fields that you list, while boost multiplies what one field adds to a score. The engine refuses a number or enum field in fields with SEARCH_INVALID_FIELD, because those fields contain no words to search, and it refuses a field that the schema doesn't declare with the same code.
import { createNarsil, type QueryParams } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: { name: 'string', summary: 'string:partial', maker: 'string', tags: 'string[]' },
})
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',
tags: ['commuter', 'aluminium'],
},
{
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',
tags: ['gravel', 'steel'],
},
{
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',
tags: ['folding', 'commuter'],
},
{
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',
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting, weighed at 7.4 kilograms.',
maker: 'road-bike-maker',
tags: ['road', 'carbon'],
},
{
id: 'city-step',
name: 'Step-through city bicycle',
summary: 'A step-through city bicycle with a chain guard, a basket, and a hub dynamo.',
maker: 'city-bike-maker',
tags: ['commuter', 'steel'],
},
])
const show = async (params: QueryParams): Promise<void> => {
const results = await narsil.query('bicycles', { ...params, document: false })
for (const hit of results.hits) {
console.log(hit.id, hit.score?.toFixed(2))
for (const [field, match] of Object.entries(hit.highlights ?? {})) {
console.log(` ${field}: ${match.snippet}`)
}
}
}
await show({ term: 'commuter bicycle' })
await show({
term: 'commuter bicycle',
fields: ['name', 'summary'],
boost: { name: 4 },
})
await narsil.shutdown()urban-commuter 3.68
city-step 0.34
folding-metro 0.34
cargo-hauler 0.07
road-racer 0.07
gravel-explorer 0.07With tags out of the search, the engine finds 'commuter' in neither the step-through bicycle nor the folding bicycle, so each one scores only for the word 'bicycle', and the boost of 4 on its name raises that score to 0.34. The urban commuter contains 'commuter' in its name as well as in its summary, so the same boost raises its score to 3.68. A boost has to be a finite number, and the engine refuses any other value with CONFIG_INVALID.
Match a word through a typo
tolerance sets how many edits apart a search word and an indexed word can be when the engine matches the two. It defaults to 0, so a search for 'comuter bicyle' matches no document until you raise it. prefixLength, which defaults to 2, sets how many leading characters have to match exactly before tolerance applies.
import { createNarsil, type QueryParams } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: { name: 'string', summary: 'string:partial', maker: 'string', tags: 'string[]' },
})
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',
tags: ['commuter', 'aluminium'],
},
{
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',
tags: ['gravel', 'steel'],
},
{
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',
tags: ['folding', 'commuter'],
},
{
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',
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting, weighed at 7.4 kilograms.',
maker: 'road-bike-maker',
tags: ['road', 'carbon'],
},
{
id: 'city-step',
name: 'Step-through city bicycle',
summary: 'A step-through city bicycle with a chain guard, a basket, and a hub dynamo.',
maker: 'city-bike-maker',
tags: ['commuter', 'steel'],
},
])
const show = async (params: QueryParams): Promise<void> => {
const results = await narsil.query('bicycles', { ...params, document: false })
for (const hit of results.hits) {
console.log(hit.id, hit.score?.toFixed(2))
for (const [field, match] of Object.entries(hit.highlights ?? {})) {
console.log(` ${field}: ${match.snippet}`)
}
}
}
await show({
term: 'commuter bicycle',
term: 'comuter bicyle',
tolerance: 1,
fields: ['name', 'summary'],
boost: { name: 4 },
})
await narsil.shutdown()urban-commuter 3.68
city-step 0.34
folding-metro 0.34
cargo-hauler 0.07
road-racer 0.07
gravel-explorer 0.07Both misspellings are one edit from the indexed words, so with tolerance: 1 the engine returns the same ranking and scores as for the correct spelling. When the misspelling is inside the first two characters, lower prefixLength as well. 'Bycicle', for example, has a 'y' where 'bicycle' has an 'i' as its second letter, so it matches no document even at tolerance: 2 until you lower prefixLength to 1. tolerance accepts a whole number from 0 to 10, and prefixLength accepts one from 0 to 1,024. exact: true turns fuzzy matching off for the whole search.
Require every word, and mark it
With termMatch: 'all', the engine returns only the documents that contain every word of the search, while a number in place of 'all' sets how many of the words a document has to contain. With highlight, the engine returns each field that you list with the matched words wrapped in <mark> tags, which show prints under each hit.
import { createNarsil, type QueryParams } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: { name: 'string', summary: 'string:partial', maker: 'string', tags: 'string[]' },
})
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',
tags: ['commuter', 'aluminium'],
},
{
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',
tags: ['gravel', 'steel'],
},
{
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',
tags: ['folding', 'commuter'],
},
{
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',
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting, weighed at 7.4 kilograms.',
maker: 'road-bike-maker',
tags: ['road', 'carbon'],
},
{
id: 'city-step',
name: 'Step-through city bicycle',
summary: 'A step-through city bicycle with a chain guard, a basket, and a hub dynamo.',
maker: 'city-bike-maker',
tags: ['commuter', 'steel'],
},
])
const show = async (params: QueryParams): Promise<void> => {
const results = await narsil.query('bicycles', { ...params, document: false })
for (const hit of results.hits) {
console.log(hit.id, hit.score?.toFixed(2))
for (const [field, match] of Object.entries(hit.highlights ?? {})) {
console.log(` ${field}: ${match.snippet}`)
}
}
}
await show({
term: 'comuter bicyle',
tolerance: 1,
termMatch: 'all',
fields: ['name', 'summary'],
boost: { name: 4 },
highlight: { fields: ['name', 'summary'] },
})
await narsil.shutdown()urban-commuter 3.68
name: Urban <mark>commuter</mark>
summary: A lightweight aluminium <mark>commuter</mark> <mark>bicycle</mark> with hydraulic disc brakes and mudguards fitted as standard.The urban commuter is the one bicycle whose name or summary contains both words, so the engine returns it alone. The highlighter marks 'commuter' and 'bicycle', which are the words that 'comuter' and 'bicyle' match through tolerance. Beside each snippet, the highlight of every hit also contains positions, which gives the start and the end of each mark as character offsets into the original field, so that you can render the marks yourself. minScore drops every hit whose score is below a floor that you set; however, a BM25 score has no upper bound, so a floor that lets the right hits through for one search can drop every hit of another.
Complete the last word as the reader types
With prefix: true, the engine treats the last word of the term as unfinished, so that the word matches every indexed word that starts with it, while the earlier words have to match in full. The engine ranks a completed word below a word that matches in full, so a document that contains the exact word that the reader types comes first.
import { createNarsil, type QueryParams } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: { name: 'string', summary: 'string:partial', maker: 'string', tags: 'string[]' },
})
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',
tags: ['commuter', 'aluminium'],
},
{
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',
tags: ['gravel', 'steel'],
},
{
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',
tags: ['folding', 'commuter'],
},
{
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',
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting, weighed at 7.4 kilograms.',
maker: 'road-bike-maker',
tags: ['road', 'carbon'],
},
{
id: 'city-step',
name: 'Step-through city bicycle',
summary: 'A step-through city bicycle with a chain guard, a basket, and a hub dynamo.',
maker: 'city-bike-maker',
tags: ['commuter', 'steel'],
},
])
const show = async (params: QueryParams): Promise<void> => {
const results = await narsil.query('bicycles', { ...params, document: false })
for (const hit of results.hits) {
console.log(hit.id, hit.score?.toFixed(2))
for (const [field, match] of Object.entries(hit.highlights ?? {})) {
console.log(` ${field}: ${match.snippet}`)
}
}
}
await show({
term: 'comuter bicyle',
term: 'city ste',
prefix: true,
tolerance: 1,
termMatch: 'all',
fields: ['name', 'summary'],
boost: { name: 4 },
highlight: { fields: ['name', 'summary'] },
})
await narsil.shutdown()city-step 8.35
name: <mark>Step</mark>-through <mark>city</mark> bicycle
summary: A <mark>step</mark>-through <mark>city</mark> bicycle with a chain guard, a basket, and a hub dynamo.The engine completes 'ste' to 'step' and to 'steel', but termMatch: 'all' requires 'city' as well, so the step-through bicycle is the one hit. The highlighter marks the completed word along with the whole one, so a search box can show the reader why the bicycle matches. The engine applies tolerance only to the finished words, such as 'city'. The engine completes a word against the spellings in your documents, which it records while the surfaceForms setting of the index is on, so it completes 'securi' to 'security' although the stemmer stores 'secur'.
Search for words side by side and in order
Put words in double quotes to match them side by side and in that order. A document has to contain the whole phrase inside one field, so the phrase "city bicycle" doesn't match the folding bicycle, whose name contains 'folding bicycle', or any summary that contains 'bicycle' without 'city' before it. In this step, every other option returns to its default, apart from highlight.
import { createNarsil, type QueryParams } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: { name: 'string', summary: 'string:partial', maker: 'string', tags: 'string[]' },
})
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',
tags: ['commuter', 'aluminium'],
},
{
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',
tags: ['gravel', 'steel'],
},
{
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',
tags: ['folding', 'commuter'],
},
{
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',
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting, weighed at 7.4 kilograms.',
maker: 'road-bike-maker',
tags: ['road', 'carbon'],
},
{
id: 'city-step',
name: 'Step-through city bicycle',
summary: 'A step-through city bicycle with a chain guard, a basket, and a hub dynamo.',
maker: 'city-bike-maker',
tags: ['commuter', 'steel'],
},
])
const show = async (params: QueryParams): Promise<void> => {
const results = await narsil.query('bicycles', { ...params, document: false })
for (const hit of results.hits) {
console.log(hit.id, hit.score?.toFixed(2))
for (const [field, match] of Object.entries(hit.highlights ?? {})) {
console.log(` ${field}: ${match.snippet}`)
}
}
}
await show({
term: 'city ste',
prefix: true,
tolerance: 1,
termMatch: 'all',
fields: ['name', 'summary'],
boost: { name: 4 },
term: '"city bicycle"',
highlight: { fields: ['name', 'summary'] },
})
await narsil.shutdown()city-step 2.15
name: Step-through <mark>city</mark> <mark>bicycle</mark>
summary: A step-through <mark>city</mark> <mark>bicycle</mark> with a chain guard, a basket, and a hub dynamo.The step-through bicycle contains 'city bicycle' in its name and its summary, so the engine returns it alone. A search can mix phrases with loose words, as in "folding bicycle" train. Every hit has to contain each phrase, while the loose words only add to the score unless termMatch requires them. The straight double quote and the curly quotes each open or close a phrase. When a quote has no closing quote, the engine treats the rest of the term as the phrase.
The engine analyses a phrase with the language, tokeniser, and stop words of the index, so "folding bicycles" also matches 'folding bicycle'. The engine records the position of each stop word that it drops, so "state of the art" matches any text that has two stop words between 'state' and 'art'. tolerance, prefix, partialWords, and synonyms apply only to the words outside the quotes. A phrase can contain up to 32 words, and a search can contain up to 32 phrases. The engine refuses more with SEARCH_INVALID_PHRASE. It refuses a phrase with the same code on an index created with trackPositions: false, because that index stores no word positions to compare.
Find a word inside a longer word
With partialWords: true, the engine also matches each search word of three or more characters inside the longer words of every field whose type includes partial. The schema declares summary as string:partial, so a search for 'guard' matches 'mudguards' as well as 'chain guard'.
import { createNarsil, type QueryParams } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: { name: 'string', summary: 'string:partial', maker: 'string', tags: 'string[]' },
})
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',
tags: ['commuter', 'aluminium'],
},
{
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',
tags: ['gravel', 'steel'],
},
{
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',
tags: ['folding', 'commuter'],
},
{
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',
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting, weighed at 7.4 kilograms.',
maker: 'road-bike-maker',
tags: ['road', 'carbon'],
},
{
id: 'city-step',
name: 'Step-through city bicycle',
summary: 'A step-through city bicycle with a chain guard, a basket, and a hub dynamo.',
maker: 'city-bike-maker',
tags: ['commuter', 'steel'],
},
])
const show = async (params: QueryParams): Promise<void> => {
const results = await narsil.query('bicycles', { ...params, document: false })
for (const hit of results.hits) {
console.log(hit.id, hit.score?.toFixed(2))
for (const [field, match] of Object.entries(hit.highlights ?? {})) {
console.log(` ${field}: ${match.snippet}`)
}
}
}
await show({
term: '"city bicycle"',
highlight: { fields: ['name', 'summary'] },
term: 'guard',
partialWords: true,
highlight: { fields: ['summary'] },
})
await narsil.shutdown()city-step 1.63
summary: A step-through city bicycle with a chain <mark>guard</mark>, a basket, and a hub dynamo.
urban-commuter 0.83
summary: A lightweight aluminium commuter bicycle with hydraulic disc brakes and <mark>mudguards</mark> fitted as standard.The urban commuter scores 0.83 against the step-through bicycle's 1.63, because the engine scores a match inside a longer word in proportion to the part of that word that the search word makes up, and 'guard' makes up five of the nine characters in 'mudguards'. The engine adds up to 50 such longer words to a search and applies no tolerance to them. partialWords has no effect under exact: true. The engine finds the longer words among the spellings that it records while surfaceForms is on, which is why it refuses a partial field on an index whose surfaceForms setting is off. A browser bundle includes the partial-word code only when the app imports partialWordSearch from @delali/narsil/partial-words and passes it to registerPartialWordSearch before it creates or loads such an index. On Node.js and in the other three languages, the engine loads that code by itself.
Match the words that mean the same thing
A synonym set lets a search for one word also match the words that the set lists for it. A two-way rule lists from 2 to 100 words, each of which matches every other. A one-way rule expands one word into up to 99 synonyms, while a search for one of those synonyms matches only that synonym. updateSynonyms replaces the synonym set of an index from the next search onwards, with no rebuild, because a synonym changes no stored word. The synonyms option on createIndex sets the first synonym set. getSynonyms returns the current set with each word in the form that you give it.
import { createNarsil, type QueryParams } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: { name: 'string', summary: 'string:partial', maker: 'string', tags: 'string[]' },
})
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',
tags: ['commuter', 'aluminium'],
},
{
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',
tags: ['gravel', 'steel'],
},
{
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',
tags: ['folding', 'commuter'],
},
{
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',
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting, weighed at 7.4 kilograms.',
maker: 'road-bike-maker',
tags: ['road', 'carbon'],
},
{
id: 'city-step',
name: 'Step-through city bicycle',
summary: 'A step-through city bicycle with a chain guard, a basket, and a hub dynamo.',
maker: 'city-bike-maker',
tags: ['commuter', 'steel'],
},
])
const show = async (params: QueryParams): Promise<void> => {
const results = await narsil.query('bicycles', { ...params, document: false })
for (const hit of results.hits) {
console.log(hit.id, hit.score?.toFixed(2))
for (const [field, match] of Object.entries(hit.highlights ?? {})) {
console.log(` ${field}: ${match.snippet}`)
}
}
}
await narsil.updateSynonyms('bicycles', [
{ words: ['mudguard', 'fender'] },
{ word: 'groceries', synonyms: ['shopping'] },
])
await show({
term: 'guard',
partialWords: true,
term: 'fender groceries',
highlight: { fields: ['summary'] },
})
await narsil.shutdown()cargo-hauler 1.55
summary: An electric cargo bicycle rated to carry two children and a week of <mark>shopping</mark>.
urban-commuter 1.49
summary: A lightweight aluminium commuter bicycle with hydraulic disc brakes and <mark>mudguards</mark> fitted as standard.Neither 'fender' nor 'groceries' appears in any bicycle, yet the engine finds the urban commuter through 'mudguard' and the cargo hauler through 'shopping'. The highlighter marks the word that each bicycle contains. The engine analyses each word of a rule with the analyser of the index, so the rule for 'mudguard' also matches 'mudguards'. The engine refuses a stop word or a phrase in a rule with CONFIG_INVALID, because each word has to analyse to exactly one token. The engine expands each search word by one level and adds up to 50 synonyms to a search. It applies no tolerance, prefix completion, or partial matching to a synonym. It scores a word and its synonyms as one term, so a bicycle that contains 'fender' twice scores the same as one that contains 'mudguard' twice in a field of the same length. A browser bundle includes the synonym code only when the app imports synonyms from @delali/narsil/synonyms and passes it to registerSynonyms before it creates or loads an index with a synonym set. On Node.js and in the other three languages, the engine loads that code by itself.
Tune how repeated words and long fields score
BM25 takes two settings. k1 sets how much a repeated word adds to a score, from 0, where a repeat adds nothing, to 1,000. b sets how much a long field lowers a score, from 0, where length has no effect, to 1. The defaults are 1.2 and 0.75. You can set a pair for every field or for one field, on the index or on one search. The engine takes each value from the first of these places that sets it: the value that the search sets for that field, the value that the search sets for every field, the value that the index sets for that field, the value that the index sets for every field, and then the default. updateBM25 replaces the setting of the index with no rebuild, because the engine computes every score during the search from the word counts and field lengths that it stores.
import { createNarsil, type QueryParams } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: { name: 'string', summary: 'string:partial', maker: 'string', tags: 'string[]' },
})
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',
tags: ['commuter', 'aluminium'],
},
{
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',
tags: ['gravel', 'steel'],
},
{
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',
tags: ['folding', 'commuter'],
},
{
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',
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting, weighed at 7.4 kilograms.',
maker: 'road-bike-maker',
tags: ['road', 'carbon'],
},
{
id: 'city-step',
name: 'Step-through city bicycle',
summary: 'A step-through city bicycle with a chain guard, a basket, and a hub dynamo.',
maker: 'city-bike-maker',
tags: ['commuter', 'steel'],
},
])
const show = async (params: QueryParams): Promise<void> => {
const results = await narsil.query('bicycles', { ...params, document: false })
for (const hit of results.hits) {
console.log(hit.id, hit.score?.toFixed(2))
for (const [field, match] of Object.entries(hit.highlights ?? {})) {
console.log(` ${field}: ${match.snippet}`)
}
}
}
await narsil.updateSynonyms('bicycles', [
{ words: ['mudguard', 'fender'] },
{ word: 'groceries', synonyms: ['shopping'] },
])
await show({
term: 'fender groceries',
highlight: { fields: ['summary'] },
})
console.log('defaults')
await show({ term: 'mudguards basket' })
console.log('this search: b 0 on summary')
await show({ term: 'mudguards basket', bm25: { fields: { summary: { b: 0 } } } })
await narsil.updateBM25('bicycles', { fields: { summary: { b: 1 } } })
console.log('index: b 1 on summary')
await show({ term: 'mudguards basket' })
await narsil.shutdown()defaults
city-step 1.63
urban-commuter 1.49
this search: b 0 on summary
city-step 1.54
urban-commuter 1.54
index: b 1 on summary
city-step 1.66
urban-commuter 1.47'Mudguards' appears once in the summary of the urban commuter, while 'basket' appears once in the summary of the step-through bicycle. Since no other field or bicycle contains either word, only the length of each summary separates the two scores. Under the defaults, the step-through bicycle scores higher, because its summary has fewer words once the engine leaves out stop words such as 'a' and 'with', which never count towards the length of a field. With b at 0 on summary, the length of summary has no effect on this one search, so the two bicycles tie. After updateBM25 sets b to 1 on summary, the engine applies the full length penalty to summary on every later search of the index, so the gap between the two bicycles widens.
updateBM25 replaces the whole setting, so a value that you leave out of the call returns to its default, and {} clears the setting. The engine saves the setting with the index and writes it into every snapshot, so the setting applies again after a restart. The engine refuses a k1 outside 0 to 1,000, a b outside 0 to 1, and an unknown key with CONFIG_INVALID. It refuses a key in fields that isn't a string or string[] field, with CONFIG_INVALID on an index and with SEARCH_INVALID_FIELD on a search. The engine stores the bm25 of a search in its cursor, so it refuses that cursor under another bm25 with SEARCH_INVALID_CURSOR.
Size a search, then suggest words
preflight counts the documents that a search matches without building or ranking any hit, so you can learn how many hits a search has before you ask for them. suggest completes a prefix to the words in the index, with the words that the most documents contain first. Its limit defaults to 10 and accepts up to 100.
import { createNarsil, type QueryParams } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: { name: 'string', summary: 'string:partial', maker: 'string', tags: 'string[]' },
})
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',
tags: ['commuter', 'aluminium'],
},
{
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',
tags: ['gravel', 'steel'],
},
{
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',
tags: ['folding', 'commuter'],
},
{
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',
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting, weighed at 7.4 kilograms.',
maker: 'road-bike-maker',
tags: ['road', 'carbon'],
},
{
id: 'city-step',
name: 'Step-through city bicycle',
summary: 'A step-through city bicycle with a chain guard, a basket, and a hub dynamo.',
maker: 'city-bike-maker',
tags: ['commuter', 'steel'],
},
])
const show = async (params: QueryParams): Promise<void> => {
const results = await narsil.query('bicycles', { ...params, document: false })
for (const hit of results.hits) {
console.log(hit.id, hit.score?.toFixed(2))
for (const [field, match] of Object.entries(hit.highlights ?? {})) {
console.log(` ${field}: ${match.snippet}`)
}
}
}
console.log('defaults')
await show({ term: 'mudguards basket' })
console.log('this search: b 0 on summary')
await show({ term: 'mudguards basket', bm25: { fields: { summary: { b: 0 } } } })
await narsil.updateBM25('bicycles', { fields: { summary: { b: 1 } } })
console.log('index: b 1 on summary')
await show({ term: 'mudguards basket' })
const size = await narsil.preflight('bicycles', { term: 'commuter bicycle', termMatch: 'all' })
console.log('matches', size.count, 'exact', size.countExact)
await show({ term: 'commuter bicycle', termMatch: 'all', limit: size.count })
const words = await narsil.suggest('bicycles', { prefix: 'com', limit: 5 })
for (const word of words.terms) {
console.log('suggest', word.term, word.documentFrequency)
}
await narsil.shutdown()matches 3 exact true
urban-commuter 2.17
city-step 0.84
folding-metro 0.84
suggest commuter 3Three bicycles contain both 'commuter' and 'bicycle' across their text fields, and exact is true because the engine counts every match. The search that follows asks for exactly that many hits. While surfaceForms is on, the engine returns each suggestion with the spelling in your documents. For an index created with surfaceForms: false, the engine suggests the stems that it stores.
Score the same way across partitions
An index that you split into partitions stores separate word statistics in each partition, so the scoring option on a search sets which statistics the engine scores with:
- Under
local, which is the default, the engine scores each partition from the statistics of that partition. - Under
dfs, the engine gathers the document frequencies from every partition before it scores. - Under
broadcast, the engine sends the search to every partition and merges the results.
defaultScoring on the index sets the mode for a search that sets none. The second file, which is scoring.ts, scoring.py, main.go, or src/main.rs, splits the same six bicycles across four partitions and sends one search in each mode.
import { createNarsil } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: { name: 'string', summary: 'string:partial', maker: 'string', tags: 'string[]' },
partitions: { maxPartitions: 4 },
})
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',
tags: ['commuter', 'aluminium'],
},
{
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',
tags: ['gravel', 'steel'],
},
{
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',
tags: ['folding', 'commuter'],
},
{
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',
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting, weighed at 7.4 kilograms.',
maker: 'road-bike-maker',
tags: ['road', 'carbon'],
},
{
id: 'city-step',
name: 'Step-through city bicycle',
summary: 'A step-through city bicycle with a chain guard, a basket, and a hub dynamo.',
maker: 'city-bike-maker',
tags: ['commuter', 'steel'],
},
])
for (const scoring of ['local', 'dfs', 'broadcast'] as const) {
const results = await narsil.query('bicycles', { term: 'commuter bicycle', scoring, document: false })
for (const hit of results.hits) {
console.log(scoring, hit.id, hit.score?.toFixed(2))
}
}
await narsil.shutdown()local city-step 1.24
local urban-commuter 1.15
local folding-metro 1.06
local gravel-explorer 0.17
local cargo-hauler 0.13
local road-racer 0.13
dfs urban-commuter 2.17
dfs city-step 0.84
dfs folding-metro 0.84
dfs cargo-hauler 0.07
dfs road-racer 0.07
dfs gravel-explorer 0.07
broadcast urban-commuter 2.17
broadcast city-step 0.84
broadcast folding-metro 0.84
broadcast cargo-hauler 0.07
broadcast road-racer 0.07
broadcast gravel-explorer 0.07With local, the engine scores the word 'commuter' in each partition against the handful of documents in that partition, so the step-through bicycle scores 1.24 and ranks above the urban commuter at 1.15. Under dfs and broadcast, the engine reproduces the single-partition ranking and its scores exactly, because it then weighs every word against the whole index. The engine does the least work under local, since it skips the round that gathers statistics, so that mode suits an index in which each word appears evenly across the partitions. Under dfs and broadcast, the engine also counts synonyms in the shared statistics, so it scores synonyms alike in every partition.
Where to go next
- Read Filters and facets to narrow these results by field value and to count them by category.
- Read Sorting, grouping, and pagination to order the hits by a field, to collapse them into groups, and to page past the first ten.
- Read Language support for the analysers of other languages and the stop words that each one drops.