跳到主要内容
本笔记本介绍了如何在 LangChain 中使用 MongoDB Atlas 向量搜索,使用 `langchain-mongodb` 包。
MongoDB Atlas 是一个完全托管的云数据库,可在 AWS、Azure 和 GCP 上使用。它支持原生向量搜索、全文搜索 (BM25) 以及对 MongoDB 文档数据进行混合搜索。
MongoDB Atlas 向量搜索 允许您将嵌入存储在 MongoDB 文档中,创建向量搜索索引,并使用近似最近邻算法(`分层可导航小世界`)执行 KNN 搜索。它使用 $vectorSearch MQL 阶段

设置

*运行 MongoDB 6.0.11、7.0.2 或更高版本(包括 RC)的 Atlas 集群。
要使用 MongoDB Atlas,您必须首先部署一个集群。我们提供一个在您选择的云上可用的永久免费集群层。要开始使用,请访问 Atlas:快速入门 您需要安装 `langchain-mongodb` 和 `pymongo` 才能使用此集成。
pip install -qU langchain-mongodb pymongo

凭据

对于此笔记本,您需要找到您的 MongoDB 集群 URI。 有关查找集群 URI 的信息,请阅读 此指南
import getpass

MONGODB_ATLAS_CLUSTER_URI = getpass.getpass("MongoDB Atlas Cluster URI:")
如果您想获得一流的模型调用自动化跟踪,您还可以通过取消注释下方来设置您的 LangSmith API 密钥
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"

初始化

# | output: false
# | echo: false
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings()
from langchain_mongodb import MongoDBAtlasVectorSearch
from pymongo import MongoClient

# initialize MongoDB python client
client = MongoClient(MONGODB_ATLAS_CLUSTER_URI)

DB_NAME = "langchain_test_db"
COLLECTION_NAME = "langchain_test_vectorstores"
ATLAS_VECTOR_SEARCH_INDEX_NAME = "langchain-test-index-vectorstores"

MONGODB_COLLECTION = client[DB_NAME][COLLECTION_NAME]

vector_store = MongoDBAtlasVectorSearch(
    collection=MONGODB_COLLECTION,
    embedding=embeddings,
    index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME,
    relevance_score_fn="cosine",
)

# Create vector search index on the collection
# Since we are using the default OpenAI embedding model (ada-v2) we need to specify the dimensions as 1536
vector_store.create_vector_search_index(dimensions=1536)
[可选] 除了上面 `vector_store.create_vector_search_index` 命令之外,您还可以使用以下索引定义通过 Atlas UI 创建向量搜索索引
{
  "fields":[
    {
      "type": "vector",
      "path": "embedding",
      "numDimensions": 1536,
      "similarity": "cosine"
    }
  ]
}

管理向量存储

创建向量存储后,我们可以通过添加和删除不同的项目来与其交互。

向向量存储添加项目

我们可以使用 add_documents 函数将项目添加到向量存储中。
from uuid import uuid4

from langchain_core.documents import Document

document_1 = Document(
    page_content="I had chocolate chip pancakes and scrambled eggs for breakfast this morning.",
    metadata={"source": "tweet"},
)

document_2 = Document(
    page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees.",
    metadata={"source": "news"},
)

document_3 = Document(
    page_content="Building an exciting new project with LangChain - come check it out!",
    metadata={"source": "tweet"},
)

document_4 = Document(
    page_content="Robbers broke into the city bank and stole $1 million in cash.",
    metadata={"source": "news"},
)

document_5 = Document(
    page_content="Wow! That was an amazing movie. I can't wait to see it again.",
    metadata={"source": "tweet"},
)

document_6 = Document(
    page_content="Is the new iPhone worth the price? Read this review to find out.",
    metadata={"source": "website"},
)

document_7 = Document(
    page_content="The top 10 soccer players in the world right now.",
    metadata={"source": "website"},
)

document_8 = Document(
    page_content="LangGraph is the best framework for building stateful, agentic applications!",
    metadata={"source": "tweet"},
)

document_9 = Document(
    page_content="The stock market is down 500 points today due to fears of a recession.",
    metadata={"source": "news"},
)

document_10 = Document(
    page_content="I have a bad feeling I am going to get deleted :(",
    metadata={"source": "tweet"},
)

documents = [
    document_1,
    document_2,
    document_3,
    document_4,
    document_5,
    document_6,
    document_7,
    document_8,
    document_9,
    document_10,
]
uuids = [str(uuid4()) for _ in range(len(documents))]

vector_store.add_documents(documents=documents, ids=uuids)
['03ad81e8-32a0-46f0-b7d8-f5b977a6b52a',
 '8396a68d-f4a3-4176-a581-a1a8c303eea4',
 'e7d95150-67f6-499f-b611-84367c50fa60',
 '8c31b84e-2636-48b6-8b99-9fccb47f7051',
 'aa02e8a2-a811-446a-9785-8cea0faba7a9',
 '19bd72ff-9766-4c3b-b1fd-195c732c562b',
 '642d6f2f-3e34-4efa-a1ed-c4ba4ef0da8d',
 '7614bb54-4eb5-4b3b-990c-00e35cb31f99',
 '69e18c67-bf1b-43e5-8a6e-64fb3f240e52',
 '30d599a7-4a1a-47a9-bbf8-6ed393e2e33c']

从向量存储中删除项目

vector_store.delete(ids=[uuids[-1]])
True

查询向量存储

一旦您的向量存储被创建并添加了相关文档,您很可能希望在链或代理运行期间查询它。

直接查询

执行简单的相似性搜索可以按如下方式完成
results = vector_store.similarity_search(
    "LangChain provides abstractions to make working with LLMs easy", k=2
)
for res in results:
    print(f"* {res.page_content} [{res.metadata}]")
* Building an exciting new project with LangChain - come check it out! [{'_id': 'e7d95150-67f6-499f-b611-84367c50fa60', 'source': 'tweet'}]
* LangGraph is the best framework for building stateful, agentic applications! [{'_id': '7614bb54-4eb5-4b3b-990c-00e35cb31f99', 'source': 'tweet'}]

带分数的相似性搜索

您还可以带分数搜索
results = vector_store.similarity_search_with_score("Will it be hot tomorrow?", k=1)
for res, score in results:
    print(f"* [SIM={score:3f}] {res.page_content} [{res.metadata}]")
* [SIM=0.784560] The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees. [{'_id': '8396a68d-f4a3-4176-a581-a1a8c303eea4', 'source': 'news'}]
Atlas 向量搜索支持使用 MQL 运算符进行过滤的预过滤。下面是一个在上面加载的相同数据上进行索引和查询的示例,它允许您对“page”字段进行元数据过滤。您可以更新现有索引,并使用定义的过滤器进行向量搜索的预过滤。 要启用预过滤,您需要更新索引定义以包含一个过滤器字段。在此示例中,我们将使用 `source` 字段作为过滤器字段。 这可以通过编程方式使用 `MongoDBAtlasVectorSearch.create_vector_search_index` 方法完成。
vectorstore.create_vector_search_index(
  dimensions=1536,
  filters=[{"type":"filter", "path":"source"}],
  update=True
)
或者,您也可以使用以下索引定义通过 Atlas UI 更新索引
{
  "fields":[
    {
      "type": "vector",
      "path": "embedding",
      "numDimensions": 1536,
      "similarity": "cosine"
    },
    {
      "type": "filter",
      "path": "source"
    }
  ]
}
然后您可以按如下方式运行带过滤器的查询
results = vector_store.similarity_search(query="foo", k=1, pre_filter={"source": {"$eq": "https://example.com"}})
for doc in results:
    print(f"* {doc.page_content} [{doc.metadata}]")

其他搜索方法

本笔记本中未涵盖其他各种搜索方法,例如 MMR 搜索或按向量搜索。有关 `MongoDBAtlasVectorStore` 可用搜索功能的完整列表,请查看 API 参考

通过转换为检索器进行查询

您还可以将向量存储转换为检索器,以便在您的链中更轻松地使用。 以下是如何将向量存储转换为检索器,然后使用简单的查询和过滤器调用检索器。
retriever = vector_store.as_retriever(
    search_type="similarity_score_threshold",
    search_kwargs={"k": 1, "score_threshold": 0.2},
)
retriever.invoke("Stealing from the bank is a crime")
[Document(metadata={'_id': '8c31b84e-2636-48b6-8b99-9fccb47f7051', 'source': 'news'}, page_content='Robbers broke into the city bank and stole $1 million in cash.')]

用于检索增强生成的使用

有关如何将此向量存储用于检索增强生成 (RAG) 的指南,请参阅以下部分

其他注意事项

  • 更多文档可在 MongoDB 的 LangChain 文档 网站上找到
  • 此功能已全面可用,并可用于生产部署。
  • Langchain 0.0.305 版本(发行说明)引入了对 $vectorSearch MQL 阶段的支持,该阶段与 MongoDB Atlas 6.0.11 和 7.0.2 一起提供。使用早期版本 MongoDB Atlas 的用户需要将其 LangChain 版本固定为 <=0.0.304

API 参考

有关所有 `MongoDBAtlasVectorSearch` 功能和配置的详细文档,请参阅 API 参考:python.langchain.com/api_reference/mongodb/index.html
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.