SimpleVecDB provides async wrappers for use in async/await contexts. These are thin wrappers around the synchronous API using ThreadPoolExecutor.

Quick Start

import asyncio
from simplevecdb import AsyncVectorDB

async def main():
    db = AsyncVectorDB("vectors.db")
    collection = db.collection("docs")

    # Add documents asynchronously
    ids = await collection.add_texts(
        ["Hello world", "Async is great"],
        embeddings=[[0.1] * 384, [0.2] * 384]
    )

    # Search asynchronously
    results = await collection.similarity_search([0.1] * 384, k=5)
    return results

results = asyncio.run(main())

Configuration

The async wrappers use a ThreadPoolExecutor for concurrent operations. You can configure the number of workers:

# Default: 4 workers
db = AsyncVectorDB("vectors.db")

# Custom worker count
db = AsyncVectorDB("vectors.db", max_workers=8)

Available Methods

AsyncVectorCollection provides async versions of all search and modification methods:

Sync Method Async Method
add_texts() await collection.add_texts()
similarity_search() await collection.similarity_search()
similarity_search_batch() await collection.similarity_search_batch()
keyword_search() await collection.keyword_search()
hybrid_search() await collection.hybrid_search()
max_marginal_relevance_search() await collection.max_marginal_relevance_search()
delete_by_ids() await collection.delete_by_ids()
remove_texts() await collection.remove_texts()

Synchronous properties remain unchanged:

  • collection.name - Collection name

Concurrent Operations

Run multiple searches in parallel with asyncio.gather or use batch search for better performance:

async def concurrent_search():
    db = AsyncVectorDB("vectors.db")
    collection = db.collection("docs")

    queries = [[0.1] * 384, [0.2] * 384, [0.3] * 384]

    # Option 1: Batch search (recommended, ~10x faster)
    results = await collection.similarity_search_batch(queries, k=5)

    # Option 2: Concurrent individual searches
    results = await asyncio.gather(*[
        collection.similarity_search(q, k=5)
        for q in queries
    ])
    return results

When to Use

Use Async API when:

  • Building async web servers (FastAPI, aiohttp)
  • Running concurrent searches
  • Integrating with async frameworks

Use Sync API when:

  • Simple scripts and notebooks
  • Single-threaded applications
  • Maximum simplicity is needed

API Reference

simplevecdb.async_core.AsyncVectorDB

Async wrapper for VectorDB.

Creates a thread pool executor for running synchronous SQLite operations without blocking the async event loop.

Example

async def main(): ... db = AsyncVectorDB("my_vectors.db") ... collection = db.collection("documents") ... await collection.add_texts(["hello"], embeddings=[[0.1]384]) ... results = await collection.similarity_search([0.1]384) ... await db.close()

Parameters:

Name Type Description Default
path str

Path to SQLite database file. Use ":memory:" for in-memory DB.

':memory:'
distance_strategy DistanceStrategy

Distance metric (COSINE, L2, or L1).

COSINE
quantization Quantization

Vector quantization (FLOAT, INT8, or BIT).

FLOAT
max_workers int

Number of threads in executor pool. Default 4.

4
**kwargs Any

Additional arguments passed to VectorDB.

{}
Source code in src/simplevecdb/async_core.py
class AsyncVectorDB:
    """
    Async wrapper for VectorDB.

    Creates a thread pool executor for running synchronous SQLite operations
    without blocking the async event loop.

    Example:
        >>> async def main():
        ...     db = AsyncVectorDB("my_vectors.db")
        ...     collection = db.collection("documents")
        ...     await collection.add_texts(["hello"], embeddings=[[0.1]*384])
        ...     results = await collection.similarity_search([0.1]*384)
        ...     await db.close()

    Args:
        path: Path to SQLite database file. Use ":memory:" for in-memory DB.
        distance_strategy: Distance metric (COSINE, L2, or L1).
        quantization: Vector quantization (FLOAT, INT8, or BIT).
        max_workers: Number of threads in executor pool. Default 4.
        **kwargs: Additional arguments passed to VectorDB.
    """

    def __init__(
        self,
        path: str = ":memory:",
        distance_strategy: DistanceStrategy = DistanceStrategy.COSINE,
        quantization: Quantization = Quantization.FLOAT,
        max_workers: int = 4,
        *,
        executor: ThreadPoolExecutor | None = None,
        **kwargs: Any,
    ):
        self._db = VectorDB(path=path, distance_strategy=distance_strategy, quantization=quantization, **kwargs)
        self._owns_executor = executor is None
        self._executor = executor if executor is not None else ThreadPoolExecutor(max_workers=max_workers)
        self._collections: dict[tuple, AsyncVectorCollection] = {}
        self._collections_lock = Lock()  # Thread-safe collection caching

    def collection(
        self,
        name: str = "default",
        distance_strategy: DistanceStrategy | None = None,
        quantization: Quantization | None = None,
        store_embeddings: bool = False,
    ) -> AsyncVectorCollection:
        """
        Get or create a named vector collection.

        Args:
            name: Collection name (alphanumeric + underscore only).
            distance_strategy: Override database-level distance metric.
            quantization: Override database-level quantization.
            store_embeddings: If True, store embeddings as BLOBs in SQLite
                alongside the usearch index. Required for ``rebuild_index()``.
                Mirrors ``VectorDB.collection``; without this argument async
                callers had no way to enable embedding storage.

        Returns:
            AsyncVectorCollection instance.
        """
        cache_key = (name, distance_strategy, quantization, store_embeddings)
        with self._collections_lock:
            if cache_key not in self._collections:
                sync_collection = self._db.collection(
                    name,
                    distance_strategy=distance_strategy,
                    quantization=quantization,
                    store_embeddings=store_embeddings,
                )
                self._collections[cache_key] = AsyncVectorCollection(
                    sync_collection, self._executor
                )
            return self._collections[cache_key]

    def list_collections(self) -> list[str]:
        """Return names of all persisted collections in the database."""
        return self._db.list_collections()

    async def delete_collection(self, name: str) -> None:
        """Delete a collection and all its data."""
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(
            self._executor, lambda: self._db.delete_collection(name)
        )
        # Evict from async-level cache too — match any tuple whose first
        # element is this name (the cache key now includes store_embeddings).
        with self._collections_lock:
            keys_to_remove = [k for k in self._collections if k[0] == name]
            for k in keys_to_remove:
                del self._collections[k]

    async def search_collections(
        self,
        query: Sequence[float],
        collections: list[str] | None = None,
        k: int = 10,
        filter: dict[str, Any] | None = None,
        *,
        normalize_scores: bool = True,
        parallel: bool = True,
    ) -> list[tuple[Document, float, str]]:
        """
        Search across multiple collections with merged, ranked results.

        See VectorDB.search_collections for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._db.search_collections(
                query,
                collections,
                k,
                filter,
                normalize_scores=normalize_scores,
                parallel=parallel,
            ),
        )

    async def vacuum(self, checkpoint_wal: bool = True) -> None:
        """
        Reclaim disk space by rebuilding the database file.

        Async wrapper for VectorDB.vacuum(). See sync version for details.

        Args:
            checkpoint_wal: If True (default), also truncate the WAL file.
        """
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(
            self._executor, lambda: self._db.vacuum(checkpoint_wal)
        )

    def __repr__(self) -> str:
        return f"AsyncVectorDB(path={self._db.path!r})"

    async def close(self) -> None:
        """Close the database connection and shutdown executor.

        Drains in-flight tasks (`wait=True`) before closing the SQLite
        connection. Otherwise pool threads can still hold cursors against
        ``self._db.conn`` when ``self._db.close()`` runs the connection's
        close, producing use-after-close races and silent data loss.
        Pending (not-yet-started) work is cancelled.
        """
        try:
            if self._owns_executor:
                # cancel_futures=True cancels work that hasn't started yet;
                # wait=True drains anything already executing so the SQLite
                # connection is not closed under live threads.
                self._executor.shutdown(wait=True, cancel_futures=True)
        except Exception:
            _logger.warning("Executor shutdown failed", exc_info=True)
        finally:
            self._db.close()

    async def __aenter__(self) -> "AsyncVectorDB":
        """Async context manager entry."""
        return self

    async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
        """Async context manager exit."""
        await self.close()

collection(name='default', distance_strategy=None, quantization=None, store_embeddings=False)

Get or create a named vector collection.

Parameters:

Name Type Description Default
name str

Collection name (alphanumeric + underscore only).

'default'
distance_strategy DistanceStrategy | None

Override database-level distance metric.

None
quantization Quantization | None

Override database-level quantization.

None
store_embeddings bool

If True, store embeddings as BLOBs in SQLite alongside the usearch index. Required for rebuild_index(). Mirrors VectorDB.collection; without this argument async callers had no way to enable embedding storage.

False

Returns:

Type Description
AsyncVectorCollection

AsyncVectorCollection instance.

Source code in src/simplevecdb/async_core.py
def collection(
    self,
    name: str = "default",
    distance_strategy: DistanceStrategy | None = None,
    quantization: Quantization | None = None,
    store_embeddings: bool = False,
) -> AsyncVectorCollection:
    """
    Get or create a named vector collection.

    Args:
        name: Collection name (alphanumeric + underscore only).
        distance_strategy: Override database-level distance metric.
        quantization: Override database-level quantization.
        store_embeddings: If True, store embeddings as BLOBs in SQLite
            alongside the usearch index. Required for ``rebuild_index()``.
            Mirrors ``VectorDB.collection``; without this argument async
            callers had no way to enable embedding storage.

    Returns:
        AsyncVectorCollection instance.
    """
    cache_key = (name, distance_strategy, quantization, store_embeddings)
    with self._collections_lock:
        if cache_key not in self._collections:
            sync_collection = self._db.collection(
                name,
                distance_strategy=distance_strategy,
                quantization=quantization,
                store_embeddings=store_embeddings,
            )
            self._collections[cache_key] = AsyncVectorCollection(
                sync_collection, self._executor
            )
        return self._collections[cache_key]

list_collections()

Return names of all persisted collections in the database.

Source code in src/simplevecdb/async_core.py
def list_collections(self) -> list[str]:
    """Return names of all persisted collections in the database."""
    return self._db.list_collections()

delete_collection(name) async

Delete a collection and all its data.

Source code in src/simplevecdb/async_core.py
async def delete_collection(self, name: str) -> None:
    """Delete a collection and all its data."""
    loop = asyncio.get_running_loop()
    await loop.run_in_executor(
        self._executor, lambda: self._db.delete_collection(name)
    )
    # Evict from async-level cache too — match any tuple whose first
    # element is this name (the cache key now includes store_embeddings).
    with self._collections_lock:
        keys_to_remove = [k for k in self._collections if k[0] == name]
        for k in keys_to_remove:
            del self._collections[k]

search_collections(query, collections=None, k=10, filter=None, *, normalize_scores=True, parallel=True) async

Search across multiple collections with merged, ranked results.

See VectorDB.search_collections for full documentation.

Source code in src/simplevecdb/async_core.py
async def search_collections(
    self,
    query: Sequence[float],
    collections: list[str] | None = None,
    k: int = 10,
    filter: dict[str, Any] | None = None,
    *,
    normalize_scores: bool = True,
    parallel: bool = True,
) -> list[tuple[Document, float, str]]:
    """
    Search across multiple collections with merged, ranked results.

    See VectorDB.search_collections for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._db.search_collections(
            query,
            collections,
            k,
            filter,
            normalize_scores=normalize_scores,
            parallel=parallel,
        ),
    )

vacuum(checkpoint_wal=True) async

Reclaim disk space by rebuilding the database file.

Async wrapper for VectorDB.vacuum(). See sync version for details.

Parameters:

Name Type Description Default
checkpoint_wal bool

If True (default), also truncate the WAL file.

True
Source code in src/simplevecdb/async_core.py
async def vacuum(self, checkpoint_wal: bool = True) -> None:
    """
    Reclaim disk space by rebuilding the database file.

    Async wrapper for VectorDB.vacuum(). See sync version for details.

    Args:
        checkpoint_wal: If True (default), also truncate the WAL file.
    """
    loop = asyncio.get_running_loop()
    await loop.run_in_executor(
        self._executor, lambda: self._db.vacuum(checkpoint_wal)
    )

close() async

Close the database connection and shutdown executor.

Drains in-flight tasks (wait=True) before closing the SQLite connection. Otherwise pool threads can still hold cursors against self._db.conn when self._db.close() runs the connection's close, producing use-after-close races and silent data loss. Pending (not-yet-started) work is cancelled.

Source code in src/simplevecdb/async_core.py
async def close(self) -> None:
    """Close the database connection and shutdown executor.

    Drains in-flight tasks (`wait=True`) before closing the SQLite
    connection. Otherwise pool threads can still hold cursors against
    ``self._db.conn`` when ``self._db.close()`` runs the connection's
    close, producing use-after-close races and silent data loss.
    Pending (not-yet-started) work is cancelled.
    """
    try:
        if self._owns_executor:
            # cancel_futures=True cancels work that hasn't started yet;
            # wait=True drains anything already executing so the SQLite
            # connection is not closed under live threads.
            self._executor.shutdown(wait=True, cancel_futures=True)
    except Exception:
        _logger.warning("Executor shutdown failed", exc_info=True)
    finally:
        self._db.close()

__aenter__() async

Async context manager entry.

Source code in src/simplevecdb/async_core.py
async def __aenter__(self) -> "AsyncVectorDB":
    """Async context manager entry."""
    return self

__aexit__(exc_type, exc_val, exc_tb) async

Async context manager exit.

Source code in src/simplevecdb/async_core.py
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
    """Async context manager exit."""
    await self.close()

simplevecdb.async_core.AsyncVectorCollection

Async wrapper for VectorCollection.

All methods are async versions of the synchronous VectorCollection methods, executed in a thread pool to avoid blocking the event loop.

Source code in src/simplevecdb/async_core.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
class AsyncVectorCollection:
    """
    Async wrapper for VectorCollection.

    All methods are async versions of the synchronous VectorCollection methods,
    executed in a thread pool to avoid blocking the event loop.
    """

    def __init__(
        self,
        sync_collection: VectorCollection,
        executor: ThreadPoolExecutor,
    ):
        self._collection = sync_collection
        self._executor = executor

    @property
    def name(self) -> str:
        """Collection name."""
        return self._collection.name

    def __repr__(self) -> str:
        return f"AsyncVectorCollection(name={self._collection.name!r})"

    async def add_texts(
        self,
        texts: Sequence[str],
        metadatas: Sequence[dict] | None = None,
        embeddings: Sequence[Sequence[float]] | None = None,
        ids: Sequence[int | None] | None = None,
        *,
        parent_ids: Sequence[int | None] | None = None,
        threads: int = 0,
    ) -> list[int]:
        """Add texts with optional embeddings and metadata.

        See VectorCollection.add_texts for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.add_texts(
                texts, metadatas, embeddings, ids,
                parent_ids=parent_ids, threads=threads,
            ),
        )

    async def similarity_search(
        self,
        query: str | Sequence[float],
        k: int = 5,
        filter: dict[str, Any] | None = None,
        *,
        exact: bool | None = None,
        threads: int = 0,
    ) -> list[tuple[Document, float]]:
        """
        Search for most similar vectors.

        See VectorCollection.similarity_search for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.similarity_search(
                query, k, filter, exact=exact, threads=threads
            ),
        )

    async def similarity_search_batch(
        self,
        queries: Sequence[Sequence[float]],
        k: int = 5,
        filter: dict[str, Any] | None = None,
        *,
        exact: bool | None = None,
        threads: int = 0,
    ) -> list[list[tuple[Document, float]]]:
        """
        Batch search for multiple query vectors.

        See VectorCollection.similarity_search_batch for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.similarity_search_batch(
                queries, k, filter, exact=exact, threads=threads
            ),
        )

    async def keyword_search(
        self,
        query: str,
        k: int = 5,
        filter: dict[str, Any] | None = None,
    ) -> list[tuple[Document, float]]:
        """
        Search using BM25 keyword ranking.

        See VectorCollection.keyword_search for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.keyword_search(query, k, filter),
        )

    async def hybrid_search(
        self,
        query: str,
        k: int = 5,
        filter: dict[str, Any] | None = None,
        *,
        query_vector: Sequence[float] | None = None,
        vector_k: int | None = None,
        keyword_k: int | None = None,
        rrf_k: int = 60,
    ) -> list[tuple[Document, float]]:
        """
        Combine keyword and vector search using Reciprocal Rank Fusion.

        See VectorCollection.hybrid_search for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.hybrid_search(
                query,
                k,
                filter,
                query_vector=query_vector,
                vector_k=vector_k,
                keyword_k=keyword_k,
                rrf_k=rrf_k,
            ),
        )

    async def max_marginal_relevance_search(
        self,
        query: str | Sequence[float],
        k: int = 5,
        fetch_k: int = 20,
        lambda_mult: float = 0.5,
        filter: dict[str, Any] | None = None,
    ) -> list[Document]:
        """
        Search with diversity using Max Marginal Relevance.

        See VectorCollection.max_marginal_relevance_search for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.max_marginal_relevance_search(
                query, k, fetch_k, lambda_mult, filter
            ),
        )

    async def delete_by_ids(self, ids: Sequence[int]) -> None:
        """
        Delete documents by their IDs.

        See VectorCollection.delete_by_ids for full documentation.
        """
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(
            self._executor,
            lambda: self._collection.delete_by_ids(ids),
        )

    async def get_documents(
        self,
        filter_dict: dict[str, Any] | None = None,
        *,
        limit: int | None = None,
        offset: int | None = None,
    ) -> list[tuple[int, str, dict[str, Any]]]:
        """Get documents with text content and metadata.

        See VectorCollection.get_documents for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.get_documents(
                filter_dict=filter_dict, limit=limit, offset=offset
            ),
        )

    async def get_embeddings_by_ids(self, ids: Sequence[int]) -> dict[int, Any]:
        """Fetch stored embeddings by document IDs.

        See VectorCollection.get_embeddings_by_ids for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.get_embeddings_by_ids(list(ids)),
        )

    async def update_metadata(
        self, updates: list[tuple[int, dict[str, Any]]]
    ) -> int:
        """Update metadata for multiple documents (shallow merge).

        See VectorCollection.update_metadata for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.update_metadata(updates),
        )

    async def count(self) -> int:
        """Count documents in collection."""
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            self._collection.count,
        )

    async def save(self) -> None:
        """Save collection to disk."""
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(
            self._executor,
            self._collection.save,
        )

    @property
    def dim(self) -> int | None:
        """Vector dimension (None if no vectors added yet)."""
        return self._collection.dim

    async def remove_texts(
        self,
        texts: Sequence[str] | None = None,
        filter: dict[str, Any] | None = None,
    ) -> int:
        """
        Remove documents by text content or metadata filter.

        See VectorCollection.remove_texts for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.remove_texts(texts, filter),
        )

    # ─────────────────────────────────────────────────────────────────────────
    # Index & Hierarchy (Async)
    # ─────────────────────────────────────────────────────────────────────────

    async def rebuild_index(
        self,
        *,
        connectivity: int | None = None,
        expansion_add: int | None = None,
        expansion_search: int | None = None,
    ) -> int:
        """Rebuild the HNSW index. See VectorCollection.rebuild_index."""
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.rebuild_index(
                connectivity=connectivity,
                expansion_add=expansion_add,
                expansion_search=expansion_search,
            ),
        )

    async def get_children(self, doc_id: int) -> list:
        """Get direct children of a document."""
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.get_children(doc_id),
        )

    async def get_parent(self, doc_id: int):
        """Get parent document, or None."""
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.get_parent(doc_id),
        )

    async def get_descendants(
        self, doc_id: int, max_depth: int | None = None
    ) -> list:
        """Get all descendants recursively."""
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.get_descendants(doc_id, max_depth),
        )

    async def get_ancestors(
        self, doc_id: int, max_depth: int | None = None
    ) -> list:
        """Get all ancestors to root."""
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.get_ancestors(doc_id, max_depth),
        )

    async def set_parent(self, doc_id: int, parent_id: int | None) -> bool:
        """Set or remove parent relationship."""
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.set_parent(doc_id, parent_id),
        )

    # ─────────────────────────────────────────────────────────────────────────
    # Clustering Methods (Async)
    # ─────────────────────────────────────────────────────────────────────────

    async def cluster(
        self,
        n_clusters: int | None = None,
        algorithm: str = "minibatch_kmeans",
        *,
        filter: dict[str, Any] | None = None,
        sample_size: int | None = None,
        min_cluster_size: int = 5,
        random_state: int | None = None,
    ) -> Any:
        """
        Cluster documents by their embeddings (async).

        See VectorCollection.cluster for full documentation.
        """
        # Runtime-validate algorithm so we can drop the prior ``# type: ignore``
        # and produce a clear ValueError instead of a confusing internal
        # failure deep in the sync code.
        valid_algorithms = ("kmeans", "minibatch_kmeans", "hdbscan")
        if algorithm not in valid_algorithms:
            raise ValueError(
                f"algorithm must be one of {valid_algorithms!r}; got {algorithm!r}"
            )

        from typing import cast, Literal

        narrowed = cast(Literal["kmeans", "minibatch_kmeans", "hdbscan"], algorithm)

        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.cluster(
                n_clusters,
                narrowed,
                filter=filter,
                sample_size=sample_size,
                min_cluster_size=min_cluster_size,
                random_state=random_state,
            ),
        )

    async def auto_tag(
        self,
        cluster_result: Any,
        *,
        method: str = "keywords",
        n_keywords: int = 5,
        custom_callback: Any = None,
    ) -> dict[int, str]:
        """
        Generate descriptive tags for clusters (async).

        See VectorCollection.auto_tag for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.auto_tag(
                cluster_result,
                method=method,
                n_keywords=n_keywords,
                custom_callback=custom_callback,
            ),
        )

    async def assign_cluster_metadata(
        self,
        cluster_result: Any,
        tags: dict[int, str] | None = None,
        *,
        metadata_key: str = "cluster",
        tag_key: str = "cluster_tag",
    ) -> int:
        """
        Persist cluster assignments to metadata (async).

        See VectorCollection.assign_cluster_metadata for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.assign_cluster_metadata(
                cluster_result,
                tags,
                metadata_key=metadata_key,
                tag_key=tag_key,
            ),
        )

    async def get_cluster_members(
        self,
        cluster_id: int,
        *,
        metadata_key: str = "cluster",
    ) -> list[Document]:
        """
        Get all documents in a cluster (async).

        See VectorCollection.get_cluster_members for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.get_cluster_members(
                cluster_id, metadata_key=metadata_key
            ),
        )

    async def save_cluster(
        self,
        name: str,
        cluster_result: Any,
        *,
        metadata: dict[str, Any] | None = None,
    ) -> None:
        """
        Save cluster state for later assignment (async).

        See VectorCollection.save_cluster for full documentation.
        """
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(
            self._executor,
            lambda: self._collection.save_cluster(
                name, cluster_result, metadata=metadata
            ),
        )

    async def load_cluster(
        self,
        name: str,
    ) -> tuple[Any, dict[str, Any]] | None:
        """
        Load saved cluster state (async).

        See VectorCollection.load_cluster for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.load_cluster(name),
        )

    async def list_clusters(self) -> list[dict[str, Any]]:
        """
        List all saved cluster configurations (async).

        See VectorCollection.list_clusters for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            self._collection.list_clusters,
        )

    async def delete_cluster(self, name: str) -> bool:
        """
        Delete a saved cluster configuration (async).

        See VectorCollection.delete_cluster for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.delete_cluster(name),
        )

    async def assign_to_cluster(
        self,
        name: str,
        doc_ids: list[int],
        *,
        metadata_key: str = "cluster",
    ) -> int:
        """
        Assign documents to a saved cluster (async).

        See VectorCollection.assign_to_cluster for full documentation.
        """
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(
            self._executor,
            lambda: self._collection.assign_to_cluster(
                name, doc_ids, metadata_key=metadata_key
            ),
        )

name property

Collection name.

dim property

Vector dimension (None if no vectors added yet).

add_texts(texts, metadatas=None, embeddings=None, ids=None, *, parent_ids=None, threads=0) async

Add texts with optional embeddings and metadata.

See VectorCollection.add_texts for full documentation.

Source code in src/simplevecdb/async_core.py
async def add_texts(
    self,
    texts: Sequence[str],
    metadatas: Sequence[dict] | None = None,
    embeddings: Sequence[Sequence[float]] | None = None,
    ids: Sequence[int | None] | None = None,
    *,
    parent_ids: Sequence[int | None] | None = None,
    threads: int = 0,
) -> list[int]:
    """Add texts with optional embeddings and metadata.

    See VectorCollection.add_texts for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.add_texts(
            texts, metadatas, embeddings, ids,
            parent_ids=parent_ids, threads=threads,
        ),
    )

Search for most similar vectors.

See VectorCollection.similarity_search for full documentation.

Source code in src/simplevecdb/async_core.py
async def similarity_search(
    self,
    query: str | Sequence[float],
    k: int = 5,
    filter: dict[str, Any] | None = None,
    *,
    exact: bool | None = None,
    threads: int = 0,
) -> list[tuple[Document, float]]:
    """
    Search for most similar vectors.

    See VectorCollection.similarity_search for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.similarity_search(
            query, k, filter, exact=exact, threads=threads
        ),
    )

similarity_search_batch(queries, k=5, filter=None, *, exact=None, threads=0) async

Batch search for multiple query vectors.

See VectorCollection.similarity_search_batch for full documentation.

Source code in src/simplevecdb/async_core.py
async def similarity_search_batch(
    self,
    queries: Sequence[Sequence[float]],
    k: int = 5,
    filter: dict[str, Any] | None = None,
    *,
    exact: bool | None = None,
    threads: int = 0,
) -> list[list[tuple[Document, float]]]:
    """
    Batch search for multiple query vectors.

    See VectorCollection.similarity_search_batch for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.similarity_search_batch(
            queries, k, filter, exact=exact, threads=threads
        ),
    )

Search using BM25 keyword ranking.

See VectorCollection.keyword_search for full documentation.

Source code in src/simplevecdb/async_core.py
async def keyword_search(
    self,
    query: str,
    k: int = 5,
    filter: dict[str, Any] | None = None,
) -> list[tuple[Document, float]]:
    """
    Search using BM25 keyword ranking.

    See VectorCollection.keyword_search for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.keyword_search(query, k, filter),
    )

Combine keyword and vector search using Reciprocal Rank Fusion.

See VectorCollection.hybrid_search for full documentation.

Source code in src/simplevecdb/async_core.py
async def hybrid_search(
    self,
    query: str,
    k: int = 5,
    filter: dict[str, Any] | None = None,
    *,
    query_vector: Sequence[float] | None = None,
    vector_k: int | None = None,
    keyword_k: int | None = None,
    rrf_k: int = 60,
) -> list[tuple[Document, float]]:
    """
    Combine keyword and vector search using Reciprocal Rank Fusion.

    See VectorCollection.hybrid_search for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.hybrid_search(
            query,
            k,
            filter,
            query_vector=query_vector,
            vector_k=vector_k,
            keyword_k=keyword_k,
            rrf_k=rrf_k,
        ),
    )

Search with diversity using Max Marginal Relevance.

See VectorCollection.max_marginal_relevance_search for full documentation.

Source code in src/simplevecdb/async_core.py
async def max_marginal_relevance_search(
    self,
    query: str | Sequence[float],
    k: int = 5,
    fetch_k: int = 20,
    lambda_mult: float = 0.5,
    filter: dict[str, Any] | None = None,
) -> list[Document]:
    """
    Search with diversity using Max Marginal Relevance.

    See VectorCollection.max_marginal_relevance_search for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.max_marginal_relevance_search(
            query, k, fetch_k, lambda_mult, filter
        ),
    )

delete_by_ids(ids) async

Delete documents by their IDs.

See VectorCollection.delete_by_ids for full documentation.

Source code in src/simplevecdb/async_core.py
async def delete_by_ids(self, ids: Sequence[int]) -> None:
    """
    Delete documents by their IDs.

    See VectorCollection.delete_by_ids for full documentation.
    """
    loop = asyncio.get_running_loop()
    await loop.run_in_executor(
        self._executor,
        lambda: self._collection.delete_by_ids(ids),
    )

get_documents(filter_dict=None, *, limit=None, offset=None) async

Get documents with text content and metadata.

See VectorCollection.get_documents for full documentation.

Source code in src/simplevecdb/async_core.py
async def get_documents(
    self,
    filter_dict: dict[str, Any] | None = None,
    *,
    limit: int | None = None,
    offset: int | None = None,
) -> list[tuple[int, str, dict[str, Any]]]:
    """Get documents with text content and metadata.

    See VectorCollection.get_documents for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.get_documents(
            filter_dict=filter_dict, limit=limit, offset=offset
        ),
    )

get_embeddings_by_ids(ids) async

Fetch stored embeddings by document IDs.

See VectorCollection.get_embeddings_by_ids for full documentation.

Source code in src/simplevecdb/async_core.py
async def get_embeddings_by_ids(self, ids: Sequence[int]) -> dict[int, Any]:
    """Fetch stored embeddings by document IDs.

    See VectorCollection.get_embeddings_by_ids for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.get_embeddings_by_ids(list(ids)),
    )

update_metadata(updates) async

Update metadata for multiple documents (shallow merge).

See VectorCollection.update_metadata for full documentation.

Source code in src/simplevecdb/async_core.py
async def update_metadata(
    self, updates: list[tuple[int, dict[str, Any]]]
) -> int:
    """Update metadata for multiple documents (shallow merge).

    See VectorCollection.update_metadata for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.update_metadata(updates),
    )

count() async

Count documents in collection.

Source code in src/simplevecdb/async_core.py
async def count(self) -> int:
    """Count documents in collection."""
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        self._collection.count,
    )

save() async

Save collection to disk.

Source code in src/simplevecdb/async_core.py
async def save(self) -> None:
    """Save collection to disk."""
    loop = asyncio.get_running_loop()
    await loop.run_in_executor(
        self._executor,
        self._collection.save,
    )

remove_texts(texts=None, filter=None) async

Remove documents by text content or metadata filter.

See VectorCollection.remove_texts for full documentation.

Source code in src/simplevecdb/async_core.py
async def remove_texts(
    self,
    texts: Sequence[str] | None = None,
    filter: dict[str, Any] | None = None,
) -> int:
    """
    Remove documents by text content or metadata filter.

    See VectorCollection.remove_texts for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.remove_texts(texts, filter),
    )

rebuild_index(*, connectivity=None, expansion_add=None, expansion_search=None) async

Rebuild the HNSW index. See VectorCollection.rebuild_index.

Source code in src/simplevecdb/async_core.py
async def rebuild_index(
    self,
    *,
    connectivity: int | None = None,
    expansion_add: int | None = None,
    expansion_search: int | None = None,
) -> int:
    """Rebuild the HNSW index. See VectorCollection.rebuild_index."""
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.rebuild_index(
            connectivity=connectivity,
            expansion_add=expansion_add,
            expansion_search=expansion_search,
        ),
    )

get_children(doc_id) async

Get direct children of a document.

Source code in src/simplevecdb/async_core.py
async def get_children(self, doc_id: int) -> list:
    """Get direct children of a document."""
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.get_children(doc_id),
    )

get_parent(doc_id) async

Get parent document, or None.

Source code in src/simplevecdb/async_core.py
async def get_parent(self, doc_id: int):
    """Get parent document, or None."""
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.get_parent(doc_id),
    )

get_descendants(doc_id, max_depth=None) async

Get all descendants recursively.

Source code in src/simplevecdb/async_core.py
async def get_descendants(
    self, doc_id: int, max_depth: int | None = None
) -> list:
    """Get all descendants recursively."""
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.get_descendants(doc_id, max_depth),
    )

get_ancestors(doc_id, max_depth=None) async

Get all ancestors to root.

Source code in src/simplevecdb/async_core.py
async def get_ancestors(
    self, doc_id: int, max_depth: int | None = None
) -> list:
    """Get all ancestors to root."""
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.get_ancestors(doc_id, max_depth),
    )

set_parent(doc_id, parent_id) async

Set or remove parent relationship.

Source code in src/simplevecdb/async_core.py
async def set_parent(self, doc_id: int, parent_id: int | None) -> bool:
    """Set or remove parent relationship."""
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.set_parent(doc_id, parent_id),
    )

cluster(n_clusters=None, algorithm='minibatch_kmeans', *, filter=None, sample_size=None, min_cluster_size=5, random_state=None) async

Cluster documents by their embeddings (async).

See VectorCollection.cluster for full documentation.

Source code in src/simplevecdb/async_core.py
async def cluster(
    self,
    n_clusters: int | None = None,
    algorithm: str = "minibatch_kmeans",
    *,
    filter: dict[str, Any] | None = None,
    sample_size: int | None = None,
    min_cluster_size: int = 5,
    random_state: int | None = None,
) -> Any:
    """
    Cluster documents by their embeddings (async).

    See VectorCollection.cluster for full documentation.
    """
    # Runtime-validate algorithm so we can drop the prior ``# type: ignore``
    # and produce a clear ValueError instead of a confusing internal
    # failure deep in the sync code.
    valid_algorithms = ("kmeans", "minibatch_kmeans", "hdbscan")
    if algorithm not in valid_algorithms:
        raise ValueError(
            f"algorithm must be one of {valid_algorithms!r}; got {algorithm!r}"
        )

    from typing import cast, Literal

    narrowed = cast(Literal["kmeans", "minibatch_kmeans", "hdbscan"], algorithm)

    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.cluster(
            n_clusters,
            narrowed,
            filter=filter,
            sample_size=sample_size,
            min_cluster_size=min_cluster_size,
            random_state=random_state,
        ),
    )

auto_tag(cluster_result, *, method='keywords', n_keywords=5, custom_callback=None) async

Generate descriptive tags for clusters (async).

See VectorCollection.auto_tag for full documentation.

Source code in src/simplevecdb/async_core.py
async def auto_tag(
    self,
    cluster_result: Any,
    *,
    method: str = "keywords",
    n_keywords: int = 5,
    custom_callback: Any = None,
) -> dict[int, str]:
    """
    Generate descriptive tags for clusters (async).

    See VectorCollection.auto_tag for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.auto_tag(
            cluster_result,
            method=method,
            n_keywords=n_keywords,
            custom_callback=custom_callback,
        ),
    )

assign_cluster_metadata(cluster_result, tags=None, *, metadata_key='cluster', tag_key='cluster_tag') async

Persist cluster assignments to metadata (async).

See VectorCollection.assign_cluster_metadata for full documentation.

Source code in src/simplevecdb/async_core.py
async def assign_cluster_metadata(
    self,
    cluster_result: Any,
    tags: dict[int, str] | None = None,
    *,
    metadata_key: str = "cluster",
    tag_key: str = "cluster_tag",
) -> int:
    """
    Persist cluster assignments to metadata (async).

    See VectorCollection.assign_cluster_metadata for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.assign_cluster_metadata(
            cluster_result,
            tags,
            metadata_key=metadata_key,
            tag_key=tag_key,
        ),
    )

get_cluster_members(cluster_id, *, metadata_key='cluster') async

Get all documents in a cluster (async).

See VectorCollection.get_cluster_members for full documentation.

Source code in src/simplevecdb/async_core.py
async def get_cluster_members(
    self,
    cluster_id: int,
    *,
    metadata_key: str = "cluster",
) -> list[Document]:
    """
    Get all documents in a cluster (async).

    See VectorCollection.get_cluster_members for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.get_cluster_members(
            cluster_id, metadata_key=metadata_key
        ),
    )

save_cluster(name, cluster_result, *, metadata=None) async

Save cluster state for later assignment (async).

See VectorCollection.save_cluster for full documentation.

Source code in src/simplevecdb/async_core.py
async def save_cluster(
    self,
    name: str,
    cluster_result: Any,
    *,
    metadata: dict[str, Any] | None = None,
) -> None:
    """
    Save cluster state for later assignment (async).

    See VectorCollection.save_cluster for full documentation.
    """
    loop = asyncio.get_running_loop()
    await loop.run_in_executor(
        self._executor,
        lambda: self._collection.save_cluster(
            name, cluster_result, metadata=metadata
        ),
    )

load_cluster(name) async

Load saved cluster state (async).

See VectorCollection.load_cluster for full documentation.

Source code in src/simplevecdb/async_core.py
async def load_cluster(
    self,
    name: str,
) -> tuple[Any, dict[str, Any]] | None:
    """
    Load saved cluster state (async).

    See VectorCollection.load_cluster for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.load_cluster(name),
    )

list_clusters() async

List all saved cluster configurations (async).

See VectorCollection.list_clusters for full documentation.

Source code in src/simplevecdb/async_core.py
async def list_clusters(self) -> list[dict[str, Any]]:
    """
    List all saved cluster configurations (async).

    See VectorCollection.list_clusters for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        self._collection.list_clusters,
    )

delete_cluster(name) async

Delete a saved cluster configuration (async).

See VectorCollection.delete_cluster for full documentation.

Source code in src/simplevecdb/async_core.py
async def delete_cluster(self, name: str) -> bool:
    """
    Delete a saved cluster configuration (async).

    See VectorCollection.delete_cluster for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.delete_cluster(name),
    )

assign_to_cluster(name, doc_ids, *, metadata_key='cluster') async

Assign documents to a saved cluster (async).

See VectorCollection.assign_to_cluster for full documentation.

Source code in src/simplevecdb/async_core.py
async def assign_to_cluster(
    self,
    name: str,
    doc_ids: list[int],
    *,
    metadata_key: str = "cluster",
) -> int:
    """
    Assign documents to a saved cluster (async).

    See VectorCollection.assign_to_cluster for full documentation.
    """
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self._executor,
        lambda: self._collection.assign_to_cluster(
            name, doc_ids, metadata_key=metadata_key
        ),
    )