Reference
The database object (db)
What srvdb.create and srvdb.open return, and how to use it as a context manager.
srvdb.create and srvdb.open return an open database object, called db throughout these pages. You never construct it directly.
with srvdb.open(path) as db: # saves and closes on a clean exit db.add(ids, vectors, metadatas) db.search(query, k=10)Context manager
Section titled “Context manager”- A
withblock that ends normally callsdb.save()and thendb.close(). - A
withblock that ends with an exception calls onlydb.close(): writes since the lastsave()are not made durable, so a half-finished batch never reaches disk. The exception propagates. - After the block, every method except
close()raisesValueError.
Methods
Section titled “Methods”| Method | Summary |
|---|---|
db.add |
Add new vectors with their ids and metadata. |
db.upsert |
Add vectors, replacing any that already have the same id. |
db.delete |
Delete vectors by id. |
db.save |
Make every earlier write durable. db.persist() is an alias. |
db.close |
Release the database and its lock without saving. |
db.search |
Find the k nearest vectors to a query. |
db.enable_keyword_search |
Index a metadata field for keyword search. |
db.count |
Number of searchable vectors. |
The full list is in the Python API overview.
- Vectors are identified by string ids. Each vector carries one metadata JSON object; SrvDB stores the id in it under the key
"__id__". - Scores are cosine similarities, higher is closer.
- Durability: writes are visible to
searchas soon as the call returns and durable once a latersave()returns. See Durability and save(). - Thread safety: a database object is safe to share between threads. Every method releases the GIL; writes take an exclusive lock and wait for each other and for running searches instead of failing. See Threads and processes.
- For type hints, the class is importable as
from srvdb import Database.
Examples
Section titled “Examples”import srvdb
v = [1.0] + [0.0] * 127 # tiny 128-dimension vectorsw = [0.0, 1.0] + [0.0] * 126with srvdb.create("./vectors", dimension=128) as db: db.add(["a", "b"], [v, w], ['{"title": "A"}', "{}"])with srvdb.open("./vectors") as db: print(db.search(v, k=1))# [('a', 1.0)]import srvdb
with srvdb.create("./vectors", dimension=128) as db: db.add(["a"], [[1.0] + [0.0] * 127], ["{}"])try: with srvdb.open("./vectors") as db: db.add(["b"], [[0.0, 1.0] + [0.0] * 126], ["{}"]) raise RuntimeError("embedding service failed")except RuntimeError: passprint(srvdb.open("./vectors").count()) # "b" was not saved# 1Was this page helpful? Tell us in Discussions.