An index stores your documents under a schema. The engine checks each document against that schema when you write the document, so the engine refuses a write that contains a value of the wrong type. On this page, you'll build one program that declares the schema of a bicycle catalogue, stores the bicycles, fetches them by id, pages through them, changes two of them, gives the live index a new stop word, and copies its documents into a second index through an export. Every call on this page is in the TypeScript package, the Python package, the Go module, and the Rust crate. The file is catalogue.ts in TypeScript, catalogue.py in Python, main.go in Go, and src/main.rs in Rust. 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.
Declare the schema
The schema maps each field to a type or, for a nested object, to another schema, which the engine accepts up to four levels deep. required lists the fields that every document has to contain. With strict: true, the engine also rejects a document that contains a field that the schema doesn't declare.
import { createNarsil } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: {
name: 'string',
summary: 'string:partial',
frameNumber: 'verbatim',
maker: { name: 'string', country: 'enum' },
category: 'enum',
price: 'number',
inStock: 'boolean',
tags: 'string[]:pattern',
},
required: ['name', 'price'],
strict: true,
})
await narsil.shutdown()The engine splits the value of a string field into words, so a search finds the document by any one of them. The engine indexes the value of a verbatim field as one whole term, so use verbatim for a value such as a frame number, a file path, or an order code. The engine leaves verbatim fields out of keyword search, while a filter can test the whole value of one or part of it. You can add three options after a colon to a string or string[] field:
- With
pattern, the engine maintains an index of the whole values of the field. The engine answerseq,ne,in,nin,startsWith,endsWith,contains, andcaseFoldfrom that index, so the engine refuses those tests withSEARCH_INVALID_FILTERon a text field without the option. That is whytagsisstring[]:patternhere. - With
partial, a search withpartialWords: truecan find a word inside a longer word, such as proof inside waterproof, as in the example on full-text search. The engine refusespartialwithCONFIG_INVALIDon an index whosesurfaceFormssetting is off. - With
sortable, the engine stores the values that it sorts the field by.sortableis the only option that the engine accepts on averbatimfield.
The engine fixes the schema once the index exists, so give each text field its options when you create the index. The engine stores the options in the order sortable, pattern, partial. The engine refuses an unknown type, or an option that the engine doesn't accept on that type, such as number:sortable, with SCHEMA_INVALID_TYPE. A verbatim value, or the value of a field whose type includes pattern, can contain up to 8,192 code points. Set patternValueLimit on the index to a whole number from 1 to 65,536 to change that limit. The engine refuses a longer value with DOC_VALIDATION_FAILED.
createIndex refuses a fifth level of nesting with SCHEMA_DEPTH_EXCEEDED. The other index options change how the engine analyses and scores text:
languagesets the and defaults toenglish.stopWordsandtokenizerreplace the and the tokeniser of that analyser.bm25sets thek1andbvalues of the ranking, which default to 1.2 and 0.75.surfaceForms, which defaults to true, makes the engine record each spelling that the stemmer changes so that suggestions and prefix completions return words with the spelling that your documents contain.
The engine refuses an index configuration larger than 16 MiB in MessagePack with CONFIG_INVALID. A long stop word list counts towards that size, so it can push a configuration past the limit.
Store documents under their ids
insert stores one document and returns its id. The engine takes that id from the id field of the document, or from a third docId argument when the document has no id. When you give neither, the engine generates a UUID v7. When the docId differs from the id of the document, the engine refuses the insert with DOC_VALIDATION_FAILED, because the stored document has to contain the same id as the key that the engine stores it under. When the index contains a document under the id, the engine refuses the insert with DOC_ALREADY_EXISTS. insertBatch stores many documents in one call and returns each failure beside the successes.
import { createNarsil } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: {
name: 'string',
summary: 'string:partial',
frameNumber: 'verbatim',
maker: { name: 'string', country: 'enum' },
category: 'enum',
price: 'number',
inStock: 'boolean',
tags: 'string[]:pattern',
},
required: ['name', 'price'],
strict: true,
})
await narsil.insert('bicycles', {
id: 'urban-commuter',
name: 'Urban commuter',
summary: 'A lightweight aluminium commuter bicycle with hydraulic disc brakes.',
frameNumber: 'CTY/24-0749',
maker: { name: 'city-bike-maker', country: 'pt' },
category: 'city',
price: 749,
inStock: true,
tags: ['commuter', 'aluminium'],
})
const loaded = await narsil.insertBatch('bicycles', [
{
id: 'gravel-explorer',
name: 'Gravel explorer',
summary: 'A steel gravel bicycle built for long unpaved rides.',
frameNumber: 'GRV/24-1299',
maker: { name: 'gravel-bike-maker', country: 'jp' },
category: 'gravel',
price: 1299,
inStock: true,
tags: ['gravel', 'steel'],
},
{
id: 'folding-metro',
name: 'Metro folding bicycle',
summary: 'A folding bicycle that fits under a train seat.',
frameNumber: 'FLD/24-0899',
maker: { name: 'folding-bike-maker', country: 'ng' },
category: 'folding',
price: 899,
inStock: false,
tags: ['folding', 'commuter'],
},
{
id: 'cargo-hauler',
name: 'Cargo hauler',
summary: 'An electric cargo bicycle rated to carry two children.',
frameNumber: 'CRG/24-3499',
maker: { name: 'cargo-bike-maker', country: 'se' },
category: 'cargo',
price: 3499,
inStock: true,
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting.',
frameNumber: 'RD/24-4250',
maker: { name: 'road-bike-maker', country: 'lb' },
category: 'road',
price: '4250',
inStock: true,
tags: ['road', 'carbon'],
},
])
console.log(
JSON.stringify(
{
succeeded: loaded.succeeded,
failed: loaded.failed.map(({ docId, error }) => ({ docId, code: error.code, message: error.message })),
},
null,
2
)
)
await narsil.shutdown(){
"succeeded": [
"gravel-explorer",
"folding-metro",
"cargo-hauler"
],
"failed": [
{
"docId": "road-racer",
"code": "DOC_VALIDATION_FAILED",
"message": "Field \"price\" expected a finite number"
}
]
}The road racer has price as the string '4250', so the engine rejects that one document and stores the other three. The error has the same code in all four languages, with a message that contains the name of the field. The TypeScript engine applies a batch 1,000 documents at a time and yields to the event loop between those chunks, so it can answer a query between two chunks of a large batch. updateBatch takes a list of { docId, document } pairs, while removeBatch takes a list of ids. Both calls return the same { succeeded, failed } shape as insertBatch.
Read documents back by id
get returns the stored document, or nothing for an id that isn't in the index. getMultiple returns an entry for each id that is in the index, while has returns a boolean and countDocuments returns the number of documents in the index. In this step, the program prints those four results in place of the batch report.
import { createNarsil } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: {
name: 'string',
summary: 'string:partial',
frameNumber: 'verbatim',
maker: { name: 'string', country: 'enum' },
category: 'enum',
price: 'number',
inStock: 'boolean',
tags: 'string[]:pattern',
},
required: ['name', 'price'],
strict: true,
})
await narsil.insert('bicycles', {
id: 'urban-commuter',
name: 'Urban commuter',
summary: 'A lightweight aluminium commuter bicycle with hydraulic disc brakes.',
frameNumber: 'CTY/24-0749',
maker: { name: 'city-bike-maker', country: 'pt' },
category: 'city',
price: 749,
inStock: true,
tags: ['commuter', 'aluminium'],
})
const loaded = await narsil.insertBatch('bicycles', [
await narsil.insertBatch('bicycles', [
{
id: 'gravel-explorer',
name: 'Gravel explorer',
summary: 'A steel gravel bicycle built for long unpaved rides.',
frameNumber: 'GRV/24-1299',
maker: { name: 'gravel-bike-maker', country: 'jp' },
category: 'gravel',
price: 1299,
inStock: true,
tags: ['gravel', 'steel'],
},
{
id: 'folding-metro',
name: 'Metro folding bicycle',
summary: 'A folding bicycle that fits under a train seat.',
frameNumber: 'FLD/24-0899',
maker: { name: 'folding-bike-maker', country: 'ng' },
category: 'folding',
price: 899,
inStock: false,
tags: ['folding', 'commuter'],
},
{
id: 'cargo-hauler',
name: 'Cargo hauler',
summary: 'An electric cargo bicycle rated to carry two children.',
frameNumber: 'CRG/24-3499',
maker: { name: 'cargo-bike-maker', country: 'se' },
category: 'cargo',
price: 3499,
inStock: true,
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting.',
frameNumber: 'RD/24-4250',
maker: { name: 'road-bike-maker', country: 'lb' },
category: 'road',
price: '4250',
inStock: true,
tags: ['road', 'carbon'],
},
])
console.log(
JSON.stringify(
{
succeeded: loaded.succeeded,
failed: loaded.failed.map(({ docId, error }) => ({ docId, code: error.code, message: error.message })),
commuter: await narsil.get('bicycles', 'urban-commuter'),
found: [...(await narsil.getMultiple('bicycles', ['gravel-explorer', 'road-racer'])).keys()],
hasCargo: await narsil.has('bicycles', 'cargo-hauler'),
total: await narsil.countDocuments('bicycles'),
},
null,
2
)
)
await narsil.shutdown(){
"commuter": {
"id": "urban-commuter",
"name": "Urban commuter",
"summary": "A lightweight aluminium commuter bicycle with hydraulic disc brakes.",
"frameNumber": "CTY/24-0749",
"maker": {
"name": "city-bike-maker",
"country": "pt"
},
"category": "city",
"price": 749,
"inStock": true,
"tags": [
"commuter",
"aluminium"
]
},
"found": [
"gravel-explorer"
],
"hasCargo": true,
"total": 4
}The index contains no road racer, so getMultiple returns one entry for the two ids in the call, while countDocuments returns 4 for the four bicycles in the index. For a missing id, get returns undefined in TypeScript, None in Python, false as the second value in Go, and None in Rust. Because a Go map has no order, DocumentFromMap sorts the keys, so the Go program prints them in byte order. Build a document with engine.NewDocument() and Set when the stored order matters to you, because the engine then stores the keys in the order that you set them.
The bicycles in this catalogue have no vector field, so each of these reads returns every field that the engine stores. On an index with a vector field, the engine in every language leaves that field out of the documents that get, getMultiple, and listDocuments return, and out of every search hit, because a vector of 384 numbers adds about 8 KB to each document in a JSON response. When you need the vectors back, pass { document: { vectors: true } } as the third argument of get or getMultiple, or set vectors: true in the document projection of a query or a listing. The engine also returns a vector field when the include list of the projection contains it. To return the vectors from every read of an index, create the index with returnVectors: true. On such an index, set vectors: false in the projection of a read when you want the engine to leave the vectors out of that read. In Python, get and get_multiple take the projection itself as their third argument, as in {"vectors": True}, while you write the document projection of a query or a listing, and the returnVectors setting of an index, with the same keys as in TypeScript. In Go, Get and GetMultiple take engine.ReturnVectors(true) as their last argument, while QueryParams and ListParams take it in their Document field. To return the vectors from every read of an index in Go, set ReturnVectors: true in engine.IndexConfig. In Rust, get_with and get_multiple_with take the projection, which is a DocumentProjection::Fields with vectors: Some(true), while IndexConfig takes return_vectors: Some(true).
Page through every document
A query with no term matches no document, even with a filter, so use listDocuments to list every document in an index. listDocuments returns the stored documents a page at a time in id order, with no ranking. A filters expression narrows the listing to the documents that match it. Pass the cursor from each page back to fetch the next page; the last page has no cursor. document.include limits each entry to the fields that you list, although every entry includes its id as well.
import { createNarsil } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: {
name: 'string',
summary: 'string:partial',
frameNumber: 'verbatim',
maker: { name: 'string', country: 'enum' },
category: 'enum',
price: 'number',
inStock: 'boolean',
tags: 'string[]:pattern',
},
required: ['name', 'price'],
strict: true,
})
await narsil.insert('bicycles', {
id: 'urban-commuter',
name: 'Urban commuter',
summary: 'A lightweight aluminium commuter bicycle with hydraulic disc brakes.',
frameNumber: 'CTY/24-0749',
maker: { name: 'city-bike-maker', country: 'pt' },
category: 'city',
price: 749,
inStock: true,
tags: ['commuter', 'aluminium'],
})
await narsil.insertBatch('bicycles', [
{
id: 'gravel-explorer',
name: 'Gravel explorer',
summary: 'A steel gravel bicycle built for long unpaved rides.',
frameNumber: 'GRV/24-1299',
maker: { name: 'gravel-bike-maker', country: 'jp' },
category: 'gravel',
price: 1299,
inStock: true,
tags: ['gravel', 'steel'],
},
{
id: 'folding-metro',
name: 'Metro folding bicycle',
summary: 'A folding bicycle that fits under a train seat.',
frameNumber: 'FLD/24-0899',
maker: { name: 'folding-bike-maker', country: 'ng' },
category: 'folding',
price: 899,
inStock: false,
tags: ['folding', 'commuter'],
},
{
id: 'cargo-hauler',
name: 'Cargo hauler',
summary: 'An electric cargo bicycle rated to carry two children.',
frameNumber: 'CRG/24-3499',
maker: { name: 'cargo-bike-maker', country: 'se' },
category: 'cargo',
price: 3499,
inStock: true,
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting.',
frameNumber: 'RD/24-4250',
maker: { name: 'road-bike-maker', country: 'lb' },
category: 'road',
price: '4250',
inStock: true,
tags: ['road', 'carbon'],
},
])
console.log(
JSON.stringify(
{
commuter: await narsil.get('bicycles', 'urban-commuter'),
found: [...(await narsil.getMultiple('bicycles', ['gravel-explorer', 'road-racer'])).keys()],
hasCargo: await narsil.has('bicycles', 'cargo-hauler'),
total: await narsil.countDocuments('bicycles'),
},
null,
2
)
)
let cursor: string | undefined
do {
const page = await narsil.listDocuments('bicycles', { limit: 2, cursor, document: { include: ['name', 'price'] } })
console.log(JSON.stringify(page, (key, value) => (key === 'elapsed' ? undefined : value), 2))
cursor = page.cursor ?? undefined
} while (cursor !== undefined)
await narsil.shutdown(){
"documents": [
{
"id": "cargo-hauler",
"document": {
"name": "Cargo hauler",
"price": 3499
}
},
{
"id": "folding-metro",
"document": {
"name": "Metro folding bicycle",
"price": 899
}
}
],
"cursor": "eyJ2Ijo0LCJhIjoiZm9sZGluZy1tZXRybyIsInEiOiI2OTY5MTkwNSJ9",
"total": 4
}
{
"documents": [
{
"id": "gravel-explorer",
"document": {
"name": "Gravel explorer",
"price": 1299
}
},
{
"id": "urban-commuter",
"document": {
"name": "Urban commuter",
"price": 749
}
}
],
"cursor": null,
"total": 4
}All four packages return the same cursor, because the cursor encodes the last id of the page and a hash of the filter of the listing. The engine sorts ids by their Unicode code points, so cargo-hauler comes first and urban-commuter comes last. By the same rule, the engine lists the ids 9, 10, 2, and 100 in the order 10, 100, 2, and 9. Pad numeric ids to a fixed width, such as 0009 and 0010, when you want a listing in numeric order. total gives the number of documents in the listing, which is 4 here. When the listing has a filter, total gives the number of documents that match the filter. limit defaults to 10. You can set limit to a value from 1 to 10,000, since the engine treats a value below 1 as 1 and refuses a value above 10,000 with SEARCH_RESULT_WINDOW_EXCEEDED.
When you write to an index while you page through it, the engine applies three rules to the listing:
- The engine returns exactly once each document that is in the index from the first page of the listing to the last.
- The engine leaves out a document that you remove ahead of the cursor.
- The engine returns a document that you insert only when its id sorts after the cursor.
The engine refuses a cursor that it cannot decode with SEARCH_INVALID_CURSOR.
Change a document, then inspect the index
update replaces the whole document under an id, so include in the new version every field that the document needs after the update, id among them. In TypeScript, Python, and Rust, read a document with vectors: true before you change the document and pass it to update. A copy that you read without vectors: true contains no vectors, so the engine stores the new version without them. remove deletes a document by id. Both calls fail with DOC_NOT_FOUND for an id that isn't in the index. The program then calls listIndexes and getStats, which return the state of the index and its statistics.
import { createNarsil } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: {
name: 'string',
summary: 'string:partial',
frameNumber: 'verbatim',
maker: { name: 'string', country: 'enum' },
category: 'enum',
price: 'number',
inStock: 'boolean',
tags: 'string[]:pattern',
},
required: ['name', 'price'],
strict: true,
})
await narsil.insert('bicycles', {
id: 'urban-commuter',
name: 'Urban commuter',
summary: 'A lightweight aluminium commuter bicycle with hydraulic disc brakes.',
frameNumber: 'CTY/24-0749',
maker: { name: 'city-bike-maker', country: 'pt' },
category: 'city',
price: 749,
inStock: true,
tags: ['commuter', 'aluminium'],
})
await narsil.insertBatch('bicycles', [
{
id: 'gravel-explorer',
name: 'Gravel explorer',
summary: 'A steel gravel bicycle built for long unpaved rides.',
frameNumber: 'GRV/24-1299',
maker: { name: 'gravel-bike-maker', country: 'jp' },
category: 'gravel',
price: 1299,
inStock: true,
tags: ['gravel', 'steel'],
},
{
id: 'folding-metro',
name: 'Metro folding bicycle',
summary: 'A folding bicycle that fits under a train seat.',
frameNumber: 'FLD/24-0899',
maker: { name: 'folding-bike-maker', country: 'ng' },
category: 'folding',
price: 899,
inStock: false,
tags: ['folding', 'commuter'],
},
{
id: 'cargo-hauler',
name: 'Cargo hauler',
summary: 'An electric cargo bicycle rated to carry two children.',
frameNumber: 'CRG/24-3499',
maker: { name: 'cargo-bike-maker', country: 'se' },
category: 'cargo',
price: 3499,
inStock: true,
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting.',
frameNumber: 'RD/24-4250',
maker: { name: 'road-bike-maker', country: 'lb' },
category: 'road',
price: '4250',
inStock: true,
tags: ['road', 'carbon'],
},
])
let cursor: string | undefined
do {
const page = await narsil.listDocuments('bicycles', { limit: 2, cursor, document: { include: ['name', 'price'] } })
console.log(JSON.stringify(page, (key, value) => (key === 'elapsed' ? undefined : value), 2))
cursor = page.cursor ?? undefined
} while (cursor !== undefined)
await narsil.update('bicycles', 'folding-metro', {
id: 'folding-metro',
name: 'Metro folding bicycle',
summary: 'A folding bicycle that fits under a train seat and unfolds in fifteen seconds.',
frameNumber: 'FLD/24-0899',
maker: { name: 'folding-bike-maker', country: 'ng' },
category: 'folding',
price: 949,
inStock: true,
tags: ['folding', 'commuter'],
})
await narsil.remove('bicycles', 'cargo-hauler')
console.log(JSON.stringify({ indexes: narsil.listIndexes(), stats: narsil.getStats('bicycles') }, null, 2))
await narsil.shutdown(){
"indexes": [
{
"name": "bicycles",
"documentCount": 3,
"partitionCount": 1,
"language": "english",
"state": "open",
"reopenCount": 0
}
],
"stats": {
"documentCount": 3,
"partitionCount": 1,
"estimatedMemoryBytes": 959653,
"language": "english",
"schema": {
"name": "string",
"summary": "string:partial",
"frameNumber": "verbatim",
"maker": {
"name": "string",
"country": "enum"
},
"category": "enum",
"price": "number",
"inStock": "boolean",
"tags": "string[]:pattern"
},
"heldSearchStates": 0
}
}After the update and the removal, the index contains three bicycles. state is open while the index is in memory and closed once the engine releases it. reopenCount gives the number of times that the engine loads the index again after a release, from the moment that the engine starts. The rules for when the engine releases an index and loads it again are on persistence and durability. estimatedMemoryBytes gives the estimate that each package makes of the memory that the index occupies, so the figure differs between languages. clear empties an index but leaves its schema in place, while dropIndex deletes the index along with its schema.
Shut the engine down before the process exits, because the engine stops its workers and flushes its durability state during the shutdown. The Python with block and the Go defer both call shutdown for you. After the shutdown, the engine refuses every further call with INSTANCE_SHUT_DOWN.
Give a live index new stop words
The engine derives the terms of an index from its language, its tokeniser, and its stop words, so a change to any of them requires the engine to analyse every document again. changeAnalysis builds the new terms beside the old ones while the engine goes on answering searches and accepting writes on the index. Once the new terms are complete, changeAnalysis switches every search to them in one step. The engine leaves unchanged each setting that you leave out of the call, while null on tokenizer or stopWords returns that setting to the default of the language.
The call takes a tokeniser by its registered name, and a stop word set by its registered name or as a list of words. The engine stores only that name or list with the index, so after a restart it looks up the code by the same name. In this step, a set called catalogue-noise contains the English stop words plus bicycle, since every summary in the catalogue contains that word.
import { createNarsil } from '@delali/narsil'
import { createNarsil, registerStopWords } from '@delali/narsil'
registerStopWords('catalogue-noise', (defaults) => new Set([...defaults, 'bicycle']))
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: {
name: 'string',
summary: 'string:partial',
frameNumber: 'verbatim',
maker: { name: 'string', country: 'enum' },
category: 'enum',
price: 'number',
inStock: 'boolean',
tags: 'string[]:pattern',
},
required: ['name', 'price'],
strict: true,
})
await narsil.insert('bicycles', {
id: 'urban-commuter',
name: 'Urban commuter',
summary: 'A lightweight aluminium commuter bicycle with hydraulic disc brakes.',
frameNumber: 'CTY/24-0749',
maker: { name: 'city-bike-maker', country: 'pt' },
category: 'city',
price: 749,
inStock: true,
tags: ['commuter', 'aluminium'],
})
await narsil.insertBatch('bicycles', [
{
id: 'gravel-explorer',
name: 'Gravel explorer',
summary: 'A steel gravel bicycle built for long unpaved rides.',
frameNumber: 'GRV/24-1299',
maker: { name: 'gravel-bike-maker', country: 'jp' },
category: 'gravel',
price: 1299,
inStock: true,
tags: ['gravel', 'steel'],
},
{
id: 'folding-metro',
name: 'Metro folding bicycle',
summary: 'A folding bicycle that fits under a train seat.',
frameNumber: 'FLD/24-0899',
maker: { name: 'folding-bike-maker', country: 'ng' },
category: 'folding',
price: 899,
inStock: false,
tags: ['folding', 'commuter'],
},
{
id: 'cargo-hauler',
name: 'Cargo hauler',
summary: 'An electric cargo bicycle rated to carry two children.',
frameNumber: 'CRG/24-3499',
maker: { name: 'cargo-bike-maker', country: 'se' },
category: 'cargo',
price: 3499,
inStock: true,
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting.',
frameNumber: 'RD/24-4250',
maker: { name: 'road-bike-maker', country: 'lb' },
category: 'road',
price: '4250',
inStock: true,
tags: ['road', 'carbon'],
},
])
await narsil.update('bicycles', 'folding-metro', {
id: 'folding-metro',
name: 'Metro folding bicycle',
summary: 'A folding bicycle that fits under a train seat and unfolds in fifteen seconds.',
frameNumber: 'FLD/24-0899',
maker: { name: 'folding-bike-maker', country: 'ng' },
category: 'folding',
price: 949,
inStock: true,
tags: ['folding', 'commuter'],
})
await narsil.remove('bicycles', 'cargo-hauler')
console.log(JSON.stringify({ indexes: narsil.listIndexes(), stats: narsil.getStats('bicycles') }, null, 2))
const matches = async (term: string): Promise<number> => (await narsil.query('bicycles', { term, limit: 0 })).count
const before = { bicycle: await matches('bicycle'), commuter: await matches('commuter') }
await narsil.changeAnalysis('bicycles', { stopWords: 'catalogue-noise' })
const after = { bicycle: await matches('bicycle'), commuter: await matches('commuter') }
console.log(JSON.stringify({ before, after }, null, 2))
await narsil.shutdown(){
"before": {
"bicycle": 3,
"commuter": 2
},
"after": {
"bicycle": 0,
"commuter": 2
}
}Before the change, bicycle matches all three summaries, so every summary gains about the same score from it. After the change, the index contains no term for bicycle, while a search for commuter returns the same two bicycles as before. In TypeScript, registerStopWords registers the name for every engine in the process, while the Python and Rust packages register the name on one engine. The Go module takes the set in Config.StopWordSets. Register the name in every process that loads the index, because the engine looks the name up again whenever it loads the index.
A call that repeats the current settings of the index completes with no rebuild. If you call changeAnalysis again while the engine is building an earlier change, the later call replaces the earlier one, so the earlier caller receives ANALYSIS_CHANGE_REPLACED. The call fails with LANGUAGE_NOT_SUPPORTED for an unknown language, with CONFIG_INVALID for an unregistered name, and with ANALYSIS_REBUILD_MEMORY_EXCEEDED when a second copy of the terms doesn't fit in memory. After each of those failures, the engine leaves the old settings of the index in place. The engine leaves vectors untouched during the rebuild, so a vector search returns the same results throughout. The languages, tokenisers, and stop word sets that you can switch to are on Language support.
Copy an index through a document export
exportDocuments writes an index as JSON Lines. The first line is a header that contains the index configuration, while each later line contains one document, with the value of each vector field as a list of numbers. The engine writes and reads the same format in every release, so you can move an index across an upgrade through an export. importDocumentExport loads an export into an index. When no index has that name yet, importDocumentExport creates the index from the header. The import replaces each document whose id the index contains, so you can repeat an interrupted import until the index matches the export.
import { createNarsil, registerStopWords } from '@delali/narsil'
registerStopWords('catalogue-noise', (defaults) => new Set([...defaults, 'bicycle']))
const narsil = await createNarsil()
await narsil.createIndex('bicycles', {
schema: {
name: 'string',
summary: 'string:partial',
frameNumber: 'verbatim',
maker: { name: 'string', country: 'enum' },
category: 'enum',
price: 'number',
inStock: 'boolean',
tags: 'string[]:pattern',
},
required: ['name', 'price'],
strict: true,
})
await narsil.insert('bicycles', {
id: 'urban-commuter',
name: 'Urban commuter',
summary: 'A lightweight aluminium commuter bicycle with hydraulic disc brakes.',
frameNumber: 'CTY/24-0749',
maker: { name: 'city-bike-maker', country: 'pt' },
category: 'city',
price: 749,
inStock: true,
tags: ['commuter', 'aluminium'],
})
await narsil.insertBatch('bicycles', [
{
id: 'gravel-explorer',
name: 'Gravel explorer',
summary: 'A steel gravel bicycle built for long unpaved rides.',
frameNumber: 'GRV/24-1299',
maker: { name: 'gravel-bike-maker', country: 'jp' },
category: 'gravel',
price: 1299,
inStock: true,
tags: ['gravel', 'steel'],
},
{
id: 'folding-metro',
name: 'Metro folding bicycle',
summary: 'A folding bicycle that fits under a train seat.',
frameNumber: 'FLD/24-0899',
maker: { name: 'folding-bike-maker', country: 'ng' },
category: 'folding',
price: 899,
inStock: false,
tags: ['folding', 'commuter'],
},
{
id: 'cargo-hauler',
name: 'Cargo hauler',
summary: 'An electric cargo bicycle rated to carry two children.',
frameNumber: 'CRG/24-3499',
maker: { name: 'cargo-bike-maker', country: 'se' },
category: 'cargo',
price: 3499,
inStock: true,
tags: ['cargo', 'electric'],
},
{
id: 'road-racer',
name: 'Road racer',
summary: 'A carbon road bicycle with electronic shifting.',
frameNumber: 'RD/24-4250',
maker: { name: 'road-bike-maker', country: 'lb' },
category: 'road',
price: '4250',
inStock: true,
tags: ['road', 'carbon'],
},
])
await narsil.update('bicycles', 'folding-metro', {
id: 'folding-metro',
name: 'Metro folding bicycle',
summary: 'A folding bicycle that fits under a train seat and unfolds in fifteen seconds.',
frameNumber: 'FLD/24-0899',
maker: { name: 'folding-bike-maker', country: 'ng' },
category: 'folding',
price: 949,
inStock: true,
tags: ['folding', 'commuter'],
})
await narsil.remove('bicycles', 'cargo-hauler')
const matches = async (term: string): Promise<number> => (await narsil.query('bicycles', { term, limit: 0 })).count
const before = { bicycle: await matches('bicycle'), commuter: await matches('commuter') }
await narsil.changeAnalysis('bicycles', { stopWords: 'catalogue-noise' })
const after = { bicycle: await matches('bicycle'), commuter: await matches('commuter') }
console.log(JSON.stringify({ before, after }, null, 2))
const exported = await new Response(await narsil.exportDocuments('bicycles')).text()
const lines = exported.trimEnd().split('\n')
const imported = await narsil.importDocumentExport('bicycles-archive', new TextEncoder().encode(exported))
console.log(
JSON.stringify(
{
header: JSON.parse(lines[0]),
documentLines: lines.length - 1,
imported,
archived: await narsil.countDocuments('bicycles-archive'),
},
null,
2
)
)
await narsil.shutdown(){
"header": {
"format": "narsil-export",
"version": 1,
"index": {
"schema": {
"name": "string",
"summary": "string:partial",
"frameNumber": "verbatim",
"maker.name": "string",
"maker.country": "enum",
"category": "enum",
"price": "number",
"inStock": "boolean",
"tags": "string[]:pattern"
},
"language": "english",
"analysisRevision": "4026533016c7f4b1",
"arrayPositionGap": 100,
"stopWords": "catalogue-noise",
"analysisGeneration": 1,
"surfaceForms": true,
"strict": true,
"required": [
"name",
"price"
]
}
},
"documentLines": 3,
"imported": {
"imported": 3,
"refusedCount": 0,
"refused": []
},
"archived": 3
}The header contains the schema, the language, the registered stop word name, and the fingerprint of the analysis, so the engine answers searches on the archive index in the same way as on the original. The TypeScript and Go packages write a nested field such as maker.name as one dotted path, while the Python and Rust packages write it as a nested object. The TypeScript package accepts both forms, whereas the Go module refuses the nested form and the Python and Rust packages refuse the dotted form, each with SCHEMA_INVALID_TYPE. For an index with nested fields, the TypeScript package can therefore import an export from any of the four languages, the Go module can import one from TypeScript or Go, and the Python and Rust packages can import one from Python or Rust. In Python and Rust, the import method is called import_documents. In the Python package, export_documents returns the bytes, or writes them to a path or a binary file that you pass as its second argument.
JSON has no type for a date, raw bytes, NaN, or an infinite number, so exportDocuments writes each such value as a one-key object such as {"$date":[1700000000,123000000]}, which the import turns back into the original value. When the import can't parse a line, or the engine rejects the document on it, the import records the line number and the error code and moves on to the next line. An export contains only the name of a stop word set or a tokeniser, so register that name in the process that imports the export. The engine refuses a document larger than 16 MiB on an import as it does on an insert. When the import creates the index, the engine applies the limits of a new index to the header, so the engine refuses a configuration larger than 16 MiB with CONFIG_INVALID.
Where to go next
- Read Full-text search for the ranking, phrase search, the matches inside a longer word that
partialallows, synonyms, and the suggestions whose spellingsurfaceFormssets. - Read Filters and facets for the filter expressions that work in both a query and a listing, including the pattern tests on
verbatimandpatternfields. - Read Sorting, grouping, and pagination for the sort order, the grouped results, and the cursor that pages through ranked results.