agentscope.ragMongoDBStore
class MongoDBStore(VectorStoreBase)
agentscope/rag/_vdb/_mongodb.py:31–529MongoDB 存储,负责持久化与读取数据。位于 agentscope.rag 包,继承自 VectorStoreBase。核心成员包括 get_client、create_collection、delete_collection、has_collection、insert、delete。
Each knowledge base maps to one MongoDB collection inside a single
database. Every document stores the owning document_id plus
the serialized :class:~agentscope.rag.Chunk, which is
reconstructed on retrieval.
示例Example
# MongoDB Atlas
store = MongoDBStore(
uri="mongodb+srv://user:pass@cluster.mongodb.net",
database="agentscope_rag",
filter_fields=[
"document_id",
"chunk.metadata.tenant_id",
],
)
async with store:
await store.create_collection("kb-1", dimensions=768)
构造器摘要Constructor Summary
| 构造器Constructor | 说明Description |
|---|---|
def __init__(uri: str, database: str, distance: Literal['cosine', 'euclidean', 'dotProduct'] = 'cosine', index_name: st… | 初始化 `MongoDBStore` 实例。 Initialize the MongoDB vector store. |
方法摘要Method Summary
构造器详情Constructor Detail
MongoDBStore
def __init__(uri: str, database: str, distance: Literal['cosine', 'euclidean', 'dotProduct'] = 'cosine', index_name: str = 'vector_index', filter_fields: list[str] | None = None, client_kwargs: dict[str, Any] | None = None) -> None
初始化 MongoDBStore 实例。
Initialize the MongoDB vector store.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
uri | str | URI(类型 `str`)。The MongoDB connection URI, e.g. `"mongodb+srv://..."` for Atlas or `"mongodb://localhost:27017"` for a self-hosted replica set. |
database | str | 数据库(类型 `str`)。The database name. Each knowledge base maps to one collection inside this database. |
distance默认default 'cosine' | Literal['cosine', 'euclidean', 'dotProduct'] | distance(类型 `Literal['cosine', 'euclidean', 'dotProduct']`)。The similarity metric used when creating vector search indexes. |
index_name默认default 'vector_index' | str | 索引名称(类型 `str`)。The name of the vector search index created on each collection. All collections share this index name. |
filter_fields默认default None | list[str] | None | 过滤 fields(类型 `list[str] | None`)。Field paths declared as filter fields in the vector search index. Required for `metadata_filter` in :meth:`search`. Defaults to `["document_id"]`. |
client_kwargs默认default None | dict[str, Any] | None | 客户端关键字参数(类型 `dict[str, Any] | None`)。Extra keyword arguments forwarded to :class:`~pymongo.AsyncMongoClient`. |
agentscope/rag/_vdb/_mongodb.py:65–106方法详情Method Detail
get_client
def get_client() -> 'AsyncMongoClient'
获取客户端。
Lazily create and cache the async MongoDB client.
agentscope/rag/_vdb/_mongodb.py:108–122__aexit__
async def __aexit__(exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: Any) -> None
退出异步上下文并清理资源。
Exit the async context — close the underlying client.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
exc_type | type[BaseException] | None | exc 类型(类型 `type[BaseException] | None`)。The exc type. |
exc_val | BaseException | None | exc val(类型 `BaseException | None`)。The exc val. |
exc_tb | Any | exc tb(类型 `Any`)。The exc tb. |
agentscope/rag/_vdb/_mongodb.py:124–133create_collection
async def create_collection(name: str, dimensions: int) -> None
创建新的MongoDB 集合使用向量搜索索引。
No-op if the collection already exists.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
name | str | 名称(类型 `str`)。The collection name. Typically, the knowledge base ID. |
dimensions | int | 向量维度(类型 `int`)。The fixed vector dimensionality for this collection. |
agentscope/rag/_vdb/_mongodb.py:147–185delete_collection
async def delete_collection(name: str) -> None
删除集合。
Delete a collection and all its data.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
name | str | 集合名称到删除。The collection name to delete. |
agentscope/rag/_vdb/_mongodb.py:187–194has_collection
async def has_collection(name: str) -> bool
判断是否具有集合。
Check whether a collection exists.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
name | str | 集合名称到检查。The collection name to check. |
agentscope/rag/_vdb/_mongodb.py:196–206insert
async def insert(collection: str, records: list[VectorRecord]) -> None
执行插入相关操作。
Each document stores :attr:VectorRecord.document_id under the document_id key and the serialized :class:Chunk under the chunk key, so that :meth:delete can remove all records of one document.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
collection | str | 目标集合名称。The target collection name. |
records | list[VectorRecord] | records(类型 `list[VectorRecord]`)。The records to insert (each carrying a :class:`Chunk` and its embedding vector). |
agentscope/rag/_vdb/_mongodb.py:252–290delete
async def delete(collection: str, document_id: str, metadata_filter: dict[str, Any] | None = None) -> None
删除数据。
Matches the document_id field written by :meth:insert from :attr:VectorRecord.document_id.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
collection | str | 目标集合名称。The target collection name. |
document_id | str | 文档标识(类型 `str`)。The source document ID whose records should be removed. |
metadata_filter默认default None | dict[str, Any] | None | 元数据过滤器(类型 `dict[str, Any] | None`)。Restrict deletion to records matching every metadata pair in addition to the document ID. `None` disables filtering. |
agentscope/rag/_vdb/_mongodb.py:292–315search
async def search(collection: str, query_vector: list[float], top_k: int = 5, metadata_filter: dict[str, Any] | None = None) -> list[VectorSearchResult]
执行搜索相关操作。
The search considers at least 100 candidates and targets 20 times top_k, capped at MongoDB's 10,000-candidate limit.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
collection | str | 集合到搜索。The collection to search. |
query_vector | list[float] | 查询向量化向量。The query embedding vector. |
top_k默认default 5 | int | 返回条数(类型 `int`)。Maximum number of results to return. Cannot exceed 10,000. |
metadata_filter默认default None | dict[str, Any] | None | 元数据过滤器(类型 `dict[str, Any] | None`)。If provided, restrict the search to records whose `chunk.metadata` matches every `key == value` pair in this dict (translated into a MongoDB filter against `chunk.metadata. `). Each key must correspond to a path declared in `filter_fields`. |
- 可能抛出 `Exception`。`ValueError`:
- 可能抛出 `Exception`。If `top_k` exceeds MongoDB's 10,000-candidate ANN limit.
agentscope/rag/_vdb/_mongodb.py:321–391list_documents
async def list_documents(collection: str, metadata_filter: dict[str, Any] | None = None) -> list[DocumentSummary]
列出文档。
Aggregates records by document_id.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
collection | str | 目标集合名称。The target collection name. |
metadata_filter默认default None | dict[str, Any] | None | 元数据过滤器(类型 `dict[str, Any] | None`)。If provided, restrict aggregation to records whose `chunk.metadata` matches every `key == value` pair. |
agentscope/rag/_vdb/_mongodb.py:426–479list_chunks
async def list_chunks(collection: str, document_id: str, *, offset: int = 0, limit: int = 30, metadata_filter: dict[str, Any] | None = None) -> list[Chunk]
列出 list_chunks。
Uses a native find + sort + skip + limit query on the chunk.chunk_index field — MongoDB is the only backend that supports server-side ordering directly.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
collection | str | 目标集合名称。The target collection name. |
document_id | str | 文档标识(类型 `str`)。The source document whose chunks should be listed. |
offsetkw默认default 0 | int | 偏移量(类型 `int`)。Number of leading chunks to skip. |
limitkw默认default 30 | int | 数量上限(类型 `int`)。Maximum number of chunks to return. |
metadata_filterkw默认default None | dict[str, Any] | None | 元数据过滤器(类型 `dict[str, Any] | None`)。Extra `chunk.metadata` equality constraints. |
agentscope/rag/_vdb/_mongodb.py:485–529