> Complete content index: https://narsil.sondelali.com/llms.txt

# Rust

> Add the Narsil crate to a Rust program, map the names in these docs onto its types, keep an index on disk, read its errors, write a tokeniser in Rust, and share one engine between threads.

URL: https://narsil.sondelali.com/docs/rust
Section: Languages
Version: 0.4 (@delali/narsil@0.4.3, latest)

With the `delali-narsil` crate, a Rust program searches Narsil indexes inside its process, on Narsil's C core, which Cargo compiles when it builds the crate. The crate saves every file in the same format as the other packages, so TypeScript, Python, and Go programs can open an index that a Rust program saves, and a Rust program can open theirs. Narsil has no Rust client for its HTTP server, so a Rust program calls a Narsil server by sending requests to the routes that the [HTTP server](/docs/http-server) page lists.

## Add the crate

The examples in these docs use version 0.2.0 of the crate.

```bash title="cargo"
cargo add delali-narsil@0.2.0
```

The crate requires Rust 1.88 or later and a C11 compiler. Its library is called `narsil`, so a Rust program imports it with `use narsil::...`. On Windows with the MSVC toolchain, the build script compiles the core with `clang-cl`, which comes with LLVM, because the core uses C11 atomics and compiler builtins that `cl.exe` lacks. Install LLVM on such a machine, or set `CC` to a clang that targets your platform.

## Map the names in these docs onto Rust

The method names are in Rust's snake case, every fallible method returns `narsil::Result`, and every method takes `&self`. Where these docs pass a JavaScript object, the crate takes a typed struct for settings and queries, and a `narsil::Map` of `narsil::Value` entries for a document. `parse_json` turns JSON text into a `Value`, so you can write a schema or a filter as JSON text.

| TypeScript | Rust |
| --- | --- |
| `createNarsil(config)` | `Narsil::open(NarsilConfig { ..NarsilConfig::default() })?` |
| `schema: { name: 'string', price: 'number' }` | `schema: parse_json(r#"{ "name": "string", "price": "number" }"#)?` |
| a document object | a `Map`, filled with `insert("name", Value::String(...))` |
| `insert(index, document, docId)` | `insert(index, map, Some(doc_id))`, or `None` to take the id from the document |
| `query(index, { term: 'cargo', limit: 5 })` | `query(index, &QueryParams { term: Some("cargo".into()), limit: Some(5), ..QueryParams::default() })` |
| `get` returning `undefined` | `get` returning `Ok(None)` |
| `hit.score`, which can be `undefined` | `hit.score`, an `Option<f64>` |
| `open`, `close` | `open_index`, `close_index` |
| `snapshot(index)` returning a stream | `snapshot(index, &mut writer)` |
| `exportDocuments`, `importDocumentExport` | `export_documents`, `import_documents` |

`write_json` turns a `Value` back into JSON text, which the program in the next section uses to print a stored document.

## Keep an index on disk

When you set `durability` to a directory, the engine writes each change to a write-ahead log before the call returns, and it writes checkpoints in the background. A later engine on the same directory opens every index in that directory. In the program below, one engine saves an index, and a second engine on the same directory loads it again.

```rust title="src/main.rs"
use std::path::Path;

use narsil::{
    DurabilityConfig, IndexConfig, Map, Narsil, NarsilConfig, Value, parse_json, write_json,
};

fn open(directory: &Path) -> narsil::Result<Narsil> {
    Narsil::open(NarsilConfig {
        durability: Some(DurabilityConfig {
            directory: Some(directory.to_path_buf()),
            ..DurabilityConfig::default()
        }),
        ..NarsilConfig::default()
    })
}

fn main() -> narsil::Result<()> {
    let directory = std::env::temp_dir().join(format!("bicycles-{}", std::process::id()));

    let narsil = open(&directory)?;
    narsil.create_index(
        "bicycles",
        IndexConfig {
            schema: parse_json(r#"{ "name": "string", "price": "number" }"#)?,
            ..IndexConfig::default()
        },
    )?;
    let mut cargo = Map::new();
    cargo.insert("id", Value::String("cargo-hauler".into()));
    cargo.insert("name", Value::String("Larsson Cargo hauler".into()));
    cargo.insert("price", Value::Number(3499.0));
    narsil.insert("bicycles", cargo, None)?;
    narsil.shutdown()?;

    let narsil = open(&directory)?;
    for index in narsil.list_indexes() {
        println!("{} {}", index.name, index.document_count);
    }
    if let Some(stored) = narsil.get("bicycles", "cargo-hauler")? {
        println!("{}", write_json(&Value::Object(stored)));
    }
    narsil.shutdown()?;

    std::fs::remove_dir_all(&directory).ok();
    Ok(())
}
```

```text result open
bicycles 1
{"id":"cargo-hauler","name":"Larsson Cargo hauler","price":3499}
```

`shutdown` flushes every log to disk and releases the directory. If the flush fails, `shutdown` returns `PERSISTENCE_SAVE_FAILED`. In a real deployment, pass a fixed directory; this program uses a directory under the system's temporary directory and removes it at the end, so that every start of the program begins with an empty directory. With `NarsilConfig::default()`, the engine keeps every index only in memory. The other settings are on [Persistence and durability](/docs/persistence-and-durability).

## Read the error code

When a fallible method fails, it returns a `narsil::NarsilError`, whose `code()` method returns an `ErrorCode` and whose `message()` method returns the description of the failure. Each `ErrorCode` variant has the same spelling as the code in every other Narsil package, such as `ErrorCode::DOC_ALREADY_EXISTS`. `as_str` and `from_name` convert between a variant and that spelling. `ErrorCode` is a non-exhaustive enum, so a `match` on it requires a wildcard arm. The Rust error has no details. Examples that branch on a code, each with a Rust tab, are on [Errors](/docs/errors).

## Write a tokeniser, an adapter, or a plugin in Rust

The default tokeniser keeps a name such as `parseInvoiceDate` as one word, so a search for `invoice` doesn't find it. A tokeniser is a type that implements the `Tokenizer` trait, whose `tokenize` method returns a `Vec<Token>` in which each token holds its text and its position, counting from 0. The tokeniser below starts a new word at each capital letter. `register_tokenizer` registers it under the name `identifiers`, and the `tokenizer` setting of the index holds the same name.

```rust title="src/main.rs"
use std::sync::Arc;

use narsil::{
    IndexConfig, Map, Narsil, NarsilConfig, QueryParams, Token, Tokenizer, TokenizerSetting, Value,
    parse_json,
};

struct IdentifierTokenizer;

impl Tokenizer for IdentifierTokenizer {
    fn tokenize(&self, text: &str) -> Vec<Token> {
        let mut words: Vec<String> = Vec::new();
        let mut word = String::new();
        for character in text.chars() {
            let starts_word = character.is_uppercase() || !character.is_alphanumeric();
            if starts_word && !word.is_empty() {
                words.push(std::mem::take(&mut word));
            }
            if character.is_alphanumeric() {
                word.extend(character.to_lowercase());
            }
        }
        if !word.is_empty() {
            words.push(word);
        }
        words
            .into_iter()
            .zip(0..)
            .map(|(token, position)| Token { token, position })
            .collect()
    }
}

fn function(id: &str, name: &str) -> Map {
    let mut document = Map::new();
    document.insert("id", Value::String(id.into()));
    document.insert("name", Value::String(name.into()));
    document
}

fn main() -> narsil::Result<()> {
    let narsil = Narsil::open(NarsilConfig::default())?;
    narsil.register_tokenizer("identifiers", Arc::new(IdentifierTokenizer))?;

    narsil.create_index(
        "functions",
        IndexConfig {
            schema: parse_json(r#"{ "name": "string" }"#)?,
            tokenizer: Some(TokenizerSetting::Named("identifiers".into())),
            ..IndexConfig::default()
        },
    )?;
    narsil.insert_batch(
        "functions",
        vec![
            function("parse-invoice-date", "parseInvoiceDate"),
            function("format-currency", "formatCurrencyAmount"),
            function("send-invoice-reminder", "sendInvoiceReminder"),
        ],
    )?;

    let found = narsil.query(
        "functions",
        &QueryParams {
            term: Some("invoice".into()),
            ..QueryParams::default()
        },
    )?;
    for hit in &found.hits {
        println!("{}", hit.id);
    }

    narsil.shutdown()
}
```

```text result open
parse-invoice-date
send-invoice-reminder
```

With the tokeniser in place, `invoice` matches the two functions whose names hold that word. With `TokenizerSetting::Instance`, you can pass a tokeniser to one index without a name. However, an engine with `durability` set refuses that setting, because a checkpoint can store the name of a tokeniser but none of its code. Register every tokeniser by name for a durable engine.

Each of the other extension points is a trait that requires `Send` and `Sync`. An `EmbeddingAdapter` implements `dimensions()` and `embed(input, purpose)`, and it can override `embed_batch` when its model accepts a batch of texts in one call. A `RerankAdapter` implements `score(query, documents)`, which returns one score for each document. `register_embedding_adapter` and `register_rerank_adapter` register each adapter under a name. A `Plugin` implements `name()` and overrides any of the hooks `before_insert`, `after_insert`, `before_update`, `after_update`, `before_remove`, `after_remove`, `before_search`, `after_search`, `on_index_create`, `on_index_drop`, and `on_partition_split`, and you add a plugin to the engine with `add_plugin`. When a `before` hook returns an error, the engine refuses the operation and returns that error to the caller unchanged. The engine holds none of its locks while it calls a hook, so a hook can call the engine.

## Share one engine between threads

Because `Narsil` is `Send` and `Sync` and every method takes `&self`, several threads can share one engine through an `Arc`, with no extra lock around it. Every thread searches the one copy of each index that the engine keeps. The crate checks the `workers` setting as the TypeScript package does, but the setting has no effect in Rust.

## How the Rust crate differs from the TypeScript package

- The cluster, the HTTP client, and the React hooks are only in the TypeScript package, so a Rust program calls a Narsil server through its HTTP routes.
- To serve an index from the Rust server, start the container image under a tag that ends in `-rust`, as in [Switch the node to the Rust server](/docs/container#switch-the-node-to-the-rust-server).
- `NarsilError` has a code and a message, and it has no details.
- The engine keeps one copy of each index, which every thread searches, while the TypeScript package copies a large index into each worker thread.
- A durable engine refuses a tokeniser that you pass to an index as an instance, so register every tokeniser by name for a durable engine.

## Where to go next

- Read [Getting started](/docs/getting-started) to build a bicycle shop's search in Rust, with the same scores as in the other languages.
- Read [Errors](/docs/errors) for the codes and for how a program in each language can branch on them.
- Read [Persistence and durability](/docs/persistence-and-durability) for the durability settings and snapshots.
