Metadata-Version: 2.4
Name: muninn-vectordb
Version: 1.1.0
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Rust
Classifier: Topic :: Database
Classifier: Topic :: Database :: Database Engines/Servers
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Text Processing :: Indexing
Classifier: Typing :: Typed
Requires-Dist: numpy>=1.19
Requires-Dist: pytest>=7 ; extra == 'test'
Provides-Extra: test
License-File: LICENSE
Summary: Embedded vector database and full-text search engine: fast vector, keyword and hybrid search with filters, durable writes.
Keywords: vector-database,search-engine,hnsw,bm25,embedded,hybrid-search
Home-Page: https://github.com/KRuskowski/muninn
License-Expression: MIT
Requires-Python: >=3.9
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/KRuskowski/muninn/blob/main/CHANGELOG.md
Project-URL: Documentation, https://github.com/KRuskowski/muninn/blob/main/python/README.md
Project-URL: Homepage, https://github.com/KRuskowski/muninn
Project-URL: Repository, https://github.com/KRuskowski/muninn

# muninn-db

muninn is an embedded vector database and full-text search engine: it runs inside your Python program, stores its data in a directory, and searches by vector similarity, by keywords (BM25), or both at once (hybrid search), with filters on your own fields. Writes are durable: every acknowledged write survives a crash.

```sh
pip install muninn-vectordb
```

From the 1.0.0 release on, wheels are published for Linux (x86-64 and ARM64) and Windows (x86-64), for Python 3.9 and later. numpy (1.19 or later) is the only dependency.

## Quick start

```python
import numpy as np
import muninn_db

with muninn_db.Database.open("data") as db:
  docs = db.create_collection("docs", {
    "vector": {"dim": 3, "metric": "cosine"},
    "text_fields": ["title"],
    "filterable": {"lang": "keyword", "year": "integer"},
  })
  docs.upsert([
    {"id": 1, "vector": [0.1, 0.2, 0.3],
     "text": {"title": "an embedded database"},
     "payload": {"lang": "en", "year": 2024}},
    {"id": "b2", "vector": [0.3, 0.1, 0.0],
     "text": {"title": "eine eingebettete Datenbank"},
     "payload": {"lang": "de", "year": 2021}},
  ])

  # Vector search.
  hits = docs.search([0.1, 0.2, 0.25], k=5)
  # Keyword search.
  hits = docs.search(text="database")
  # Hybrid search with a filter, returning the payloads.
  hits = docs.search(
    np.array([0.1, 0.2, 0.25], dtype=np.float32), text="database",
    filter={"and": [{"eq": {"lang": "en"}}, {"range": {"year": {"gte": 2020}}}]},
    with_payload=True)
  for h in hits:
    print(h.id, h.score, h.vector_score, h.text_score, h.payload)
```

## Opening a database

`Database.open(path, options=None, *, read_only=False, **options)` opens the directory, creating it if needed, and recovers every acknowledged write. One process at a time may open a directory for writing; a second attempt raises `DatabaseLockedError`, and so does opening it while another process has it open read-only (the message says which).

**Reading from several processes.** `Database.open(path, read_only=True)` opens an existing database for reading only, beside any number of other read-only openers (but not beside a writer). It changes nothing on disk, so it works on a backup, a snapshot, a read-only folder or inside a sandbox; every write (`upsert`, `delete`, `write`, `flush`, `compact`, creating or dropping collections) raises `ReadOnlyError`. It sees every write acknowledged before it opened. `db.read_only` says how a database was opened.

**Waiting for the other side.** With `lock_timeout=10` (seconds), opening waits up to that long for another process to close the database instead of failing at once. Waiting is fair: a writer that waits goes ahead of readers that arrive after it. A child process started while a database is open (`subprocess`, `multiprocessing`) briefly holds a copy of its lock, until the child starts its program, so reopen right after a close with a short `lock_timeout`.

```python
db = muninn_db.Database.open("data", durability="batch", sync_interval_ms=10)
...
db.close()  # or use `with`
```

| option | meaning | default |
|---|---|---|
| `durability` | `"each"`: on disk before a write returns. `"batch"`: on disk within `sync_interval_ms` (a power cut can lose that much). `"none"`: left to the operating system (survives the program crashing, not the machine). | `"each"` |
| `sync_interval_ms` | longest delay with `"batch"` | 10 |
| `memtable_max_docs` | documents kept in memory per collection before they are written to disk | 50 000 |
| `auto_compact` | merge on-disk parts in the background | `True` |
| `lock_timeout` | seconds to wait for another process to close the database | 0 |

`muninn_db.Options` lists every setting with its documentation; pass it as the second argument or use the same names as keywords.

`close()` waits for running operations, then stops background work and unlocks the directory; afterwards every call on the database and its collections raises `DatabaseClosedError`. Nothing is lost by not calling `flush()` first.

## Collections and schemas

A schema is fixed when the collection is created. Write it as a dict (the same form as the HTTP API) or with the schema classes:

```python
from muninn_db import Schema, VectorField, Hnsw

schema = Schema(
  vector=VectorField(384, metric="cosine", index=Hnsw(m=16, ef_construction=200),
                     quantization="none"),
  text_fields=["title", "body"],
  analyzer="english",
  filterable={"lang": "keyword", "year": "integer", "price": "float",
              "meta.public": "bool"},
)
docs = db.create_collection("docs", schema)
```

| setting | values | default |
|---|---|---|
| `vector.dim` | 1 to 65536 (required) | |
| `vector.metric` | `"cosine"`, `"dot"`, `"l2"` | `"cosine"` |
| `vector.index` | `Hnsw(m, ef_construction)` / `"hnsw"` (approximate, fast at any size), `Flat()` / `"flat"` (exact) | HNSW, m 16, ef_construction 200 |
| `vector.quantization` | `"none"`, `"sq8"` (one byte per dimension), `"binary"` (one bit); the best candidates are re-checked exactly | `"none"` |
| `text_fields` | names of the full-text fields | none |
| `analyzer` | `"default"` (lowercase only), `"english"` (accent folding, stop words, stemming), or `Analyzer(...)` | `"default"` |
| `filterable` | payload fields usable in filters: `{name: "keyword" \| "integer" \| "float" \| "bool"}`; dotted names reach nested objects | none |

A schema needs a vector field, at least one text field, or both. Other collection calls:

```python
db.collection("docs")                         # an existing collection
db.get_or_create_collection("docs", schema)   # either
db.list_collections()                         # ["docs", ...]
"docs" in db                                  # True
db.drop_collection("docs")                    # deletes it and its files
docs.schema                                   # a muninn_db.Schema
```

## Writing documents

A document has an id (a non-negative integer below 2**64, or a string; `7` and `"7"` are different documents), a vector when the collection has a vector field, text for any of the declared text fields, and an optional payload: any JSON-like value (dicts, lists, strings, numbers, booleans, None). Writing an existing id replaces the document.

```python
docs.upsert([{"id": 1, "vector": vec, "text": {"title": "..."}, "payload": {...}}])
```

For bulk loads, pass columns instead. A float32 numpy array is read directly from its memory; other arrays and lists are converted first.

```python
n = 100_000
docs.upsert(
  ids=np.arange(n),                                  # or a list of ints / strs
  vectors=np.random.rand(n, 384).astype(np.float32), # shape (n, dim)
  texts={"title": titles},                           # {field: [str, ...]}
  payloads=[{"lang": "en"}] * n,                     # one per id, or None
  batch_size=10_000,
)
```

Every `upsert` call is all-or-nothing: if any document is invalid nothing is stored, and after a crash either the whole call is there or none of it. With `batch_size`, each batch of that many documents is all-or-nothing instead (one batch may hold up to about 1 GB). When the call returns, the documents are searchable and as durable as the `durability` option promises.

Deleting some documents and writing others in one all-or-nothing step:

```python
docs.write(upserts=[{"id": 9, "text": {"title": "new"}}], deletes=[1, 2])
# returns how many of the deleted ids existed; the deletes come first, so
# an id in both lists ends up with its new document
```

```python
docs.delete([1, "b2"])   # returns how many of the ids existed
docs.get(1)              # {"id": 1, "vector": array([...], dtype=float32),
                         #  "text": {...}, "payload": {...}} or None
len(docs)                # documents that can be found
```

### Listing documents

`docs.scan(filter=None)` goes through every live document (or every one whose payload matches the filter) in the order they were written, as dicts like `get` returns:

```python
for doc in docs.scan({"eq": {"lang": "en"}}):
  print(doc["id"], doc["text"])
```

A scan reads one snapshot, taken when it starts: writes made while you iterate are not seen, and they are not held up either. Documents are fetched a few hundred at a time without the GIL, so memory stays small for any collection size. `scan.cursor` is a string marking where the scan got to; `docs.scan(cursor=...)` (in this process or a later one) continues there on the current state: documents written after that position come, including ones replaced since (again, with their new content), deleted ones do not. None is skipped, but after a merge or `compact()` of the part the cursor points into, documents may come again, up to the whole merged part (after `compact()` possibly everything): deduplicate by id, or read one scan to the end, if repeats matter. `scan.close()` releases the snapshot early; closing the database releases every scan.

## Searching

```python
hits = docs.search(vector=None, text=None, *, k=10, filter=None, ids=None,
                   fusion=None, fields=None, with_payload=False, ef=None,
                   rerank=None, candidates=None, boost=None)
```

A `vector` alone is a nearest-neighbour search, `text` alone a keyword search (a document matches if it contains any of the words), both a hybrid search.

| argument | meaning | default |
|---|---|---|
| `k` | number of results | 10 |
| `filter` | payload filter (below) | none |
| `ids` | only these document ids | all |
| `fusion` | hybrid only: `Rrf(k=60)` / `{"rrf": {"k": 60}}` (reciprocal-rank fusion) or `Weighted(vector=0.7, text=0.3)` / `{"weighted": {...}}` | `Rrf(60)` |
| `fields` | text fields to search; a document scores its best field | all |
| `boost` | multiplies text fields' scores before the best one is chosen, e.g. `{"title": 4.0}`; weights above 0, at most 1 000 000, only fields the search uses | 1 each |
| `with_payload` | include each hit's payload | `False` |
| `ef` | HNSW candidate-list size; larger is more accurate and slower | 64 |
| `rerank` | quantised candidates re-checked exactly | 4k (sq8), 16k (binary) |
| `candidates` | hybrid only: candidates per side before fusion | max(4k, 40) |

Each `Hit` has `id`, `score` (higher is better: the cosine similarity, dot product or minus the squared Euclidean distance for vector searches, BM25 for keyword searches, the fused score for hybrid ones), `vector_score` and `text_score` (each side's score, or None if that side did not find the document) and `payload` (with `with_payload=True`). `hit.to_dict()` gives a dict. Equal scores come back in the order the documents were written.

Many vector queries at once run in parallel on all CPU cores:

```python
results = docs.search_batch(queries, k=10)   # queries: shape (n, dim)
```

**Fusing separate searches.** When vectors and text live in different collections (or databases), search each and combine the hits the way a hybrid search does:

```python
k = 10
side = muninn_db.hybrid_candidates(k)          # max(4 k, 40)
vh = images.search(vec, k=side)
th = captions.search(text="red fox", k=side)
hits = muninn_db.Rrf().fuse(vh, th, k)         # or muninn_db.fuse(vh, th, k=k, fusion=...)
```

Hits are matched by id. With each side searched `hybrid_candidates(k)` deep, the result is what one hybrid search over both would return, except that documents with exactly equal scores come in the order they first appear (vector hits first). Hits may also be dicts with `id`, `score` and optionally `vector_score`, `text_score`, `payload`.

### Filters

Filters are dicts in the same language as the HTTP API. Fields must be declared `filterable` in the schema.

```text
{"eq":     {FIELD: VALUE}}
{"in":     {FIELD: [VALUE, ...]}}
{"range":  {FIELD: {"gt" | "gte" | "lt" | "lte": NUMBER, ...}}}
{"exists": FIELD}
{"and":    [filter, ...]}
{"or":     [filter, ...]}
{"not":    filter}
```

A field holding a list matches when any element matches. A payload value of the wrong kind (text where a number is declared) counts as missing. Filters are applied during the search, so `k` hits come back whenever `k` documents match.

## Maintenance

```python
docs.flush()     # write in-memory documents to disk, shorten the log
docs.compact()   # merge all on-disk parts, dropping deleted documents
docs.stats()     # {"live_docs": ..., "deleted_docs": ..., "segments": [...], ...}
db.stats()       # {name: stats} for every collection
```

Neither is needed for durability or for searches to see new documents; both happen automatically in the background.

## Threads and processes

A `Database` and its collections may be used from many threads at once. Searches and writes run without holding the GIL, so searches from several threads run in parallel, and concurrent writers share disk flushes. Ctrl-C (`KeyboardInterrupt`) arrives when the running call returns; a call is never cut off halfway.

Only one process at a time may open a database directory for writing (any number may open it with `read_only=True`, but not beside a writer; see "Opening a database"). A child process created with `fork` (the default start method of `multiprocessing` on Linux before Python 3.14) gets a copy of the parent's `Database` objects but not the background threads behind them, so it cannot use them: every call (also on a `Scan`) raises `ForkedProcessError`, and `close()` there only marks the copy closed, leaving the parent's database untouched. Open the database in the process that uses it, and start child processes with the `"spawn"` or `"forkserver"` method if they need to open it themselves (after the parent closed it).

A collection keeps its database open: as long as a `Collection` is in use, the directory stays locked even if the `Database` object is gone. `collection.database` returns the database, for example to close it.

## Errors

Every error is a `muninn_db.MuninnError`; most also derive from the built-in exception that fits:

| exception | also | when |
|---|---|---|
| `InvalidArgumentError` | `ValueError` | a wrong vector dimension, an invalid schema or filter, an undeclared text or filter field, a negative id |
| `ReadOnlyError` | `InvalidArgumentError` | a write to a database opened with `read_only=True` |
| `NotFoundError` | `LookupError` | an unknown collection |
| `AlreadyExistsError` | | creating a collection whose name is taken |
| `CorruptionError` | | damaged files |
| `UnsupportedError` | | data written by a newer version of muninn; nothing is changed on disk, open it with that version again |
| `UnavailableError` | | a collection that stopped accepting writes after a disk failure; reopening the database recovers it |
| `DatabaseClosedError` | `ValueError` | using a closed database |
| `ForkedProcessError` | `RuntimeError` | using a database in a child process created with `fork` (see above) |
| `StorageError` | `OSError` | disk errors |
| `DatabaseLockedError` | `StorageError` | the directory is open elsewhere (for writing, or read-only while you open it for writing); with `lock_timeout`, still after waiting that long |

Wrong Python types raise `TypeError` (a float where an integer is expected, bytes where ids or vectors are expected); numbers out of range (`k=0`, a negative option) raise `InvalidArgumentError`.

## License

MIT. Source, the HTTP server and the Rust library: <https://github.com/KRuskowski/muninn>.

