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

# Python

> Install Narsil in a Python program, map the names in these docs onto the Python package, keep an index on disk, read its errors, and write a tokeniser in Python.

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

With the `delali-narsil` package, a Python program searches Narsil indexes inside its process, through a blocking API or an asyncio API, with no separate server. The package wraps the Rust implementation of Narsil. It saves every file in the same format as the other packages, so TypeScript, Go, and Rust programs can open an index that a Python program saves, and a Python program can open theirs. If your Python program has to call a Narsil server that a TypeScript process serves, see [Python client](/docs/python-client) for the `narsil-client` package.

## Install the package

The examples in these docs use version 0.1.0 of the package.

```bash title="pip"
pip install delali-narsil==0.1.0
```

The package requires Python 3.11 or later. A Python program imports it as `narsil`. PyPI holds wheels for macOS on x64 and arm64, for Linux on x64 and arm64 with glibc or musl, and for Windows on x64 and arm64, so pip installs the package without a compiler on those platforms. Narsil builds every wheel against the stable interface of Python 3.11, so one wheel installs on every later Python release. On any other platform, you will have to build the package from the [Narsil repository](https://github.com/assetcorp/narsil), which requires Rust 1.88 or later and a C11 compiler.

## Map the names in these docs onto Python

The method names and keyword arguments are in Python's snake case, while every setting, query, and result is a plain `dict` with the same keys that these docs use. You can therefore copy a query such as `{"term": "folding", "termMatch": "all"}` from a TypeScript example without changing it. Most methods have the TypeScript name in snake case, while a few have another name:

| TypeScript | Python |
| --- | --- |
| `createNarsil(config)` | `Narsil(config)`, or `await AsyncNarsil.open(config)` for asyncio |
| `createIndex`, `insertBatch`, `listIndexes` | `create_index`, `insert_batch`, `list_indexes` |
| `insert(index, document, docId)` | `insert(index, document, doc_id=None)` |
| `get` returning `undefined` | `get` returning `None` |
| `open`, `close` | `open_index`, `close_index` |
| `exportDocuments`, `importDocumentExport` | `export_documents`, `import_documents` |
| `registerTokenizer`, `registerEmbeddingAdapter` | `register_tokenizer`, `register_embedding_adapter` |
| `shutdown()` | `shutdown()`, or the end of a `with` block |

`snapshot(index)` returns the archive as `bytes`, or writes it to a binary file object when you pass one as the second argument. `restore(index, source)` accepts `bytes` or a binary file object. `AsyncNarsil` has the same methods as coroutines. Because it makes each call on a worker thread, the event loop can serve other tasks while the engine works.

## 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.

```python title="store.py"
import tempfile

from narsil import Narsil

with tempfile.TemporaryDirectory() as directory:
    with Narsil({"durability": {"directory": directory}}) as narsil:
        narsil.create_index("bicycles", {"schema": {"name": "string", "price": "number"}})
        narsil.insert("bicycles", {"id": "cargo-hauler", "name": "Larsson Cargo hauler", "price": 3499})

    with Narsil({"durability": {"directory": directory}}) as narsil:
        print([index["name"] for index in narsil.list_indexes()])
        print(narsil.get("bicycles", "cargo-hauler"))
```

```text result open
['bicycles']
{'id': 'cargo-hauler', 'name': 'Larsson Cargo hauler', 'price': 3499}
```

The engine flushes its log as it shuts down, which happens at the end of a `with` block, on a call to `shutdown()`, or when the interpreter exits. In a real deployment, pass a fixed directory such as `./search-data`; this program uses a temporary directory so that it starts with an empty directory each time. The TypeScript, Go, and Rust packages can open the same directory. The durability settings are on [Persistence and durability](/docs/persistence-and-durability).

## Read the error code

When the engine fails, it raises `narsil.NarsilError`. Its `code` holds the same code that the TypeScript package raises for the same input, as a string such as `"DOC_ALREADY_EXISTS"`, and its `message` holds a description of the failure. The Python error has no `details` attribute. The package also checks the shape of every setting and query before the engine receives it, so the package raises `NarsilError` with `CONFIG_INVALID` for an unknown key or a negative `limit`. For an argument of the wrong Python type, such as an index name that is not a string, the package raises `TypeError`, as any Python function does. Examples that branch on a code, each with a Python tab, are on [Errors](/docs/errors).

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

The default tokeniser keeps a name such as `parseInvoiceDate` as one word, so a search for `invoice` doesn't find it. A tokeniser is an object whose `tokenize(text)` method returns `(token, position)` pairs, where each position is the index of the token, counting from 0. The tokeniser below splits each name at its capital letters. `register_tokenizer` makes it available to every index whose `tokenizer` setting holds the name that you register it under.

```python title="functions.py"
import re

from narsil import Narsil


class IdentifierTokenizer:
    def tokenize(self, text):
        words = re.findall(r"[A-Z]?[a-z]+|[A-Z]+|[0-9]+", text)
        return [(word.lower(), position) for position, word in enumerate(words)]


with Narsil() as narsil:
    narsil.register_tokenizer("identifiers", IdentifierTokenizer())
    narsil.create_index("functions", {"schema": {"name": "string"}, "tokenizer": "identifiers"})
    narsil.insert_batch(
        "functions",
        [
            {"id": "parse-invoice-date", "name": "parseInvoiceDate"},
            {"id": "format-currency", "name": "formatCurrencyAmount"},
            {"id": "send-invoice-reminder", "name": "sendInvoiceReminder"},
        ],
    )

    found = narsil.query("functions", {"term": "invoice"})
    print([hit["id"] for hit in found["hits"]])
```

```text result open
['parse-invoice-date', 'send-invoice-reminder']
```

With the tokeniser in place, `invoice` matches the two functions whose names hold that word. You can also pass tokenisers to the engine as it starts, as in `Narsil({"tokenizers": {"identifiers": IdentifierTokenizer()}})`.

The other extension points work in the same way. An embedding adapter is an object with a `dimensions` attribute and an `embed(text, purpose)` method, where `purpose` is `"document"` or `"query"`. An embedding adapter can also have an `embed_batch(texts, purpose)` method, so that the engine embeds a whole batch insert in one call. A rerank adapter has a `score(query, documents)` method, which returns one number for each document. A plugin has a `name` and 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`. Add a plugin to the engine with `add_plugin`. `narsil.EmbeddingAdapter`, `narsil.RerankAdapter`, and `narsil.Tokenizer` declare each shape for a type checker. When your code raises an exception inside the engine, the caller receives a `NarsilError` whose message holds the type and text of that exception. If your code raises a `NarsilError` itself, the caller receives it with its code and message unchanged.

## Share one engine between threads

Every method releases the interpreter lock while the engine works, so several Python threads can search one engine at the same time. The engine serves each search from the state of the index at the moment that the search starts, which means that a search never waits for a write. The engine can call a tokeniser, an adapter, or a plugin from any of its threads, so make each one safe to call from any thread. If a tokeniser, an embedding adapter, or a persistence adapter calls back into the engine that is calling it, that call raises `NarsilError` with `CONFIG_INVALID` at once, because the engine waits for the callback and can hold a lock on the index while it waits.

## How the Python package differs from the TypeScript package

- The HTTP server, the cluster, the HTTP client, and the React hooks are only in the TypeScript package, so a Python program that needs a server can call a TypeScript process through the [Python client](/docs/python-client).
- `NarsilError` has a code and a message, and it has no `details`.
- The package refuses an unknown key or a value of the wrong shape in any setting or query with `CONFIG_INVALID`.
- A `get` or a search that returns a date outside the range of Python's `datetime` raises `NarsilError` with `INTERNAL_ERROR`.

## Where to go next

- Read [Getting started](/docs/getting-started) to build a bicycle shop's search in Python, 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 [Python client](/docs/python-client) to call a Narsil server from Python.
