Reference
db.search
Find the k nearest vectors to a query.
db.search(query: Sequence[float] | None, k: int, *, text: str | None = None, where: dict | None = None, expand: tuple | None = None, certify: bool = False, deadline_ms: float | None = None) -> list[tuple[str, float]] | list[tuple[str, float, int]] | SearchOutcomeParameters
Section titled “Parameters”-
query : sequence of float or None Query vector with the database dimension and only finite values (a list or 1-D NumPy array), or
Nonefor a keyword-only search withtext. -
k : int Maximum number of results, at least 1.
-
text : str, optional, keyword-only Keyword query, ranked by BM25 over the field chosen with
db.enable_keyword_search. With aqueryvector the two rankings are fused (Reciprocal Rank Fusion). See Keyword and hybrid search. -
where : dict, optional, keyword-only Metadata filter, for example
{"genre": "jazz"}or{"year": {"$gte": 1950}}. Operators:$eq,$ne,$gt,$gte,$lt,$lte,$in,$nin,$and,$or,$not;"a.b"names a nested field. See Filtered search. DefaultNonesearches every vector. -
expand : tuple, optional, keyword-only
(link_type, hops)or(link_type, hops, max_results): after thekhits, follow outgoing links oflink_typefor 1 to 3 hops, adding at mostmax_resultslinked records (default 100, at most 1,000). Works with vector, keyword (text) and hybrid hits; cannot be combined withwhere(linked records would not be filtered) or withcertify/deadline_ms(linked records would not be certified). See Links between records. -
certify : bool, keyword-only, RaBitQ modes only Plain vector search only (not with
textorwhere). Use the RaBitQ error bounds: certify results whose interval clears the k-th lower bound and rescore only the uncertain candidates on the full vectors. See RaBitQ, step 5. DefaultFalse. -
deadline_ms : float, optional, keyword-only, RaBitQ modes only Stop after this many milliseconds and return the best results found. The clock is checked between 32-vector scan blocks and between 256-vector rescoring batches. Default
None, no deadline.
Returns
Section titled “Returns”list[tuple[str, float]]: up to k (id, score) pairs, best first. Scores are cosine similarities computed in float32, so an identical vector scores about 0.99999994 rather than exactly 1.0. With text and no query, scores are BM25 scores; with both, they are fused rank scores that only order the results. With where, only matching vectors are returned, and k of them whenever at least k match. Fewer than k pairs come back when fewer vectors (or matches) exist; an empty database returns [].
With expand, list[tuple[str, float, int]]: (id, score, hop) tuples, the hits with hop 0 and then the linked records ordered by hop. A linked record carries the score of the record it was reached from.
With certify=True or deadline_ms, a SearchOutcome. It iterates, indexes (integers and slices) and has a len() like the list above (out.results returns that plain list), and also has these attributes:
completeness(float): fraction of live vectors scanned, 1.0 unless the deadline passed.confidence(float or None): withcertify=True, 0.99, a nominal and approximate lower bound on the probability, over a hypothetical random rotation seed, that the results are exactly the top k of the scanned vectors. It is not a per-query guarantee, not a long-run rate for this database’s fixed seed, and not joint across queries.Nonewithoutcertify, and when the rerank cap (max(k × rerank, 1000)candidates) or the deadline cut the rescoring short;certifiedis then 0.certified,reranked,scanned(int): results certified without rescoring, candidates rescored, and vectors scanned.
Raises
Section titled “Raises”-
ValueError
kis 0, or a query does not match the database dimension or contains NaN or infinity, orwhereis not a valid filter (empty, an unknown operator, a wrong operand type, a value JSON cannot encode). Also raised for a negativek, when bothqueryandtextareNone, whentexthas no letters or digits, is over 64 KiB or has more than 1,024 distinct words, and whentextis given beforeenable_keyword_search(). Also raised forcertifyordeadline_mson a database that is not in a RaBitQ mode, without a query vector, or combined withtextorwhere, and for a negative or non-finitedeadline_ms. Also raised for anexpandthat is malformed, out of bounds, or combined withwhere,certifyordeadline_ms. -
RuntimeError An internal fault occurred, or the keyword index file is damaged (call
enable_keyword_search()to rebuild it).
- Sees every write whose call has returned, persisted or not.
- Results are exact in
"flat"mode and approximate in the other modes. In"pq"mode scores are approximate too. - A
wherefilter reads every metadata record once per call (O(n));search_batchshares that pass across queries. - Thread safety: releases the GIL and takes a shared lock, so calls from several threads run in parallel; they wait while a write is running. See Threads and processes.
Examples
Section titled “Examples”import srvdb
db = srvdb.create("./vectors", dimension=128)v = [1.0] + [0.0] * 127 # tiny 128-dimension vectorsw = [0.0, 1.0] + [0.0] * 126db.add(["a", "b"], [v, w], ["{}", "{}"])print(db.search(v, k=2))# [('a', 0.9999999403953552), ('b', 0.0)]
db.add(["c"], [w], ['{"kind": "note"}'])print(db.search(v, k=2, where={"kind": "note"}))# [('c', 0.0)]With a RaBitQ database:
import randomimport srvdb
rng = random.Random(3)vecs = [[rng.gauss(0, 1) for _ in range(128)] for _ in range(1000)]db = srvdb.create("./rq", dimension=128, index="rabitq")db.add([f"d{i}" for i in range(1000)], vecs, ["{}"] * 1000)out = db.search(vecs[5], k=1, certify=True, deadline_ms=10_000)print(out[0][0], out.completeness, out.confidence)# d5 1.0 0.99See also
Section titled “See also”- Filtered search: Filter syntax and performance.
db.search_batch: Run several searches in one call.- Keyword and hybrid search: BM25 and fusion.
db.get: Return the metadata stored for an id.db.set_ef_search: Set HNSW’s search candidate list size.
Was this page helpful? Tell us in Discussions.