以编程方式使用文档

>MongoDB Atlas 是一个全托管云 > 数据库,可在 AWS、Azure 和 GCP 上使用。它现在支持原生 > MongoDB 文档数据的向量搜索。

安装和设置

请参阅 详细配置说明.

我们需要安装 langchain-mongodb python 包。

pip install langchain-mongodb
uv add langchain-mongodb

向量存储

请查看 使用示例.

from langchain_mongodb import MongoDBAtlasVectorSearch

检索器

全文搜索检索器

>Hybrid Search Retriever 使用 > Lucene 标准 (BM25) 分析器执行全文搜索。

from langchain_mongodb.retrievers import MongoDBAtlasFullTextSearchRetriever

混合搜索检索器

>Hybrid Search Retriever 结合向量搜索和全文搜索,通过 > 进行加权 Reciprocal Rank Fusion (RRF) 算法。

from langchain_mongodb.retrievers import MongoDBAtlasHybridSearchRetriever

模型缓存

MongoDBCache

一种用于在 MongoDB 中存储简单缓存的抽象。这不使用语义缓存,也不需要在生成前对集合创建索引。

要导入此缓存:

from langchain_mongodb.cache import MongoDBCache

要将此缓存与您的 LLM 一起使用:

from langchain_core.globals import set_llm_cache

# use any embedding provider...
from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings

mongodb_atlas_uri = ""
COLLECTION_NAME=""
DATABASE_NAME=""

set_llm_cache(MongoDBCache(
    connection_string=mongodb_atlas_uri,
    collection_name=COLLECTION_NAME,
    database_name=DATABASE_NAME,
))

### MongoDBAtlasSemanticCache 语义缓存允许用户根据用户输入与先前缓存结果之间的语义相似性来检索缓存的提示。它在内部将 MongoDB Atlas 同时作为缓存和向量存储使用。 MongoDBAtlasSemanticCache 继承自 MongoDBAtlasVectorSearch 需要定义一个 Atlas 向量搜索索引才能工作。请参阅 使用示例 了解如何设置索引。

要导入此缓存:

from langchain_mongodb.cache import MongoDBAtlasSemanticCache

要将此缓存与您的 LLM 一起使用:

from langchain_core.globals import set_llm_cache

# use any embedding provider...
from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings

mongodb_atlas_uri = ""
COLLECTION_NAME=""
DATABASE_NAME=""

set_llm_cache(MongoDBAtlasSemanticCache(
    embedding=FakeEmbeddings(),
    connection_string=mongodb_atlas_uri,
    collection_name=COLLECTION_NAME,
    database_name=DATABASE_NAME,
))