Skip to main content

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.

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

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.

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:

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:

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.

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.

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:

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
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:

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

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:

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:

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.

{"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

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.

Metadata

Release files for muninn-vectordb 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for muninn-vectordb 1.1.0
File Size Uploaded Provenance Actions
muninn_vectordb-1.1.0.tar.gz 586.2 kB Without provenance Details for muninn_vectordb-1.1.0.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for muninn-vectordb 1.1.0
File Interpreter ABI Platform Actions
muninn_vectordb-1.1.0-cp39-abi3-win_amd64.whl CPython 3.9 abi3 Windows x86-64 Details for muninn_vectordb-1.1.0-cp39-abi3-win_amd64.whl
muninn_vectordb-1.1.0-cp39-abi3-manylinux_2_28_x86_64.whl CPython 3.9 abi3 Linux glibc 2.28+ x86-64 Details for muninn_vectordb-1.1.0-cp39-abi3-manylinux_2_28_x86_64.whl
muninn_vectordb-1.1.0-cp39-abi3-manylinux_2_28_aarch64.whl CPython 3.9 abi3 Linux glibc 2.28+ ARM64 Details for muninn_vectordb-1.1.0-cp39-abi3-manylinux_2_28_aarch64.whl

Total release size: 4.2 MB

Release files / muninn_vectordb-1.1.0.tar.gz

Download URL muninn_vectordb-1.1.0.tar.gz
Size 586.2 kB
Tags Source
SHA-256 checksum
How to use checksums
2be95ad63190d5f59ffa46585169354832d071d7660a59861088b39ef06a438f
BLAKE2b-256 checksum
How to use checksums
10a6efe85c1e14605f2bea578dce47bc8cecc91c1987e03575bfecbc4192acde
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / muninn_vectordb-1.1.0-cp39-abi3-win_amd64.whl

Download URL muninn_vectordb-1.1.0-cp39-abi3-win_amd64.whl
Size 1.2 MB
Tags CPython 3.9 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
54766cee9b4ad16dec78709cb0e7bc3b45e4abbbbe3df6589bfd87c63eff5365
BLAKE2b-256 checksum
How to use checksums
224f9369a824104313981c642d5b38065fd65341c5b50a8e6f595fff92b1ec0f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / muninn_vectordb-1.1.0-cp39-abi3-manylinux_2_28_x86_64.whl

Download URL muninn_vectordb-1.1.0-cp39-abi3-manylinux_2_28_x86_64.whl
Size 1.3 MB
Tags CPython 3.9 Linux glibc 2.28+ x86-64 abi3
SHA-256 checksum
How to use checksums
9a52ae157bbecc1b2d8e3c248121ed39dac68aa59d86a60be85494d66226077f
BLAKE2b-256 checksum
How to use checksums
cf034cd441eb2eed10958a1ed6a18bae6ebef5da9065ae63aa1370ef94f36199
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / muninn_vectordb-1.1.0-cp39-abi3-manylinux_2_28_aarch64.whl

Download URL muninn_vectordb-1.1.0-cp39-abi3-manylinux_2_28_aarch64.whl
Size 1.2 MB
Tags CPython 3.9 Linux glibc 2.28+ ARM64 abi3
SHA-256 checksum
How to use checksums
994fbd57d5be2ccf5426bb790b277bb4f38cfb09f4bc0a3577c49917a6a96489
BLAKE2b-256 checksum
How to use checksums
aa9ab0d6b5f0380072fc9650e5e846027ebaf4fdbab06c910868191988754546
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for muninn-vectordb 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page