对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

使用MongoDB和 LangChain 执行父文档检索

您可以将 MongoDB Vector Search 与 LangChain 集成以执行父文档检索。在本教程中,您将完成以下步骤:

  1. 设置环境。

  2. 准备数据。

  3. 实例化父文档检索器。

  4. 创建MongoDB Vector Search索引。

  5. 在 RAG 管道中使用检索器。

父文档检索是一种检索技术,涉及将大型文档分割成较小的子文档。在此技术中,您先查询较小的数据块,然后将完整的父文档返回到 LLM。这可以通过允许对较小的数据块进行更精细的搜索,同时为 LLM 提供父文档的完整上下文,从而改善 RAG 代理和应用程序的响应。

使用 MongoDB 进行父文档检索,可将父文档和子文档存储在单个 MongoDB 集合中,这支持通过仅计算和索引子文档的嵌入来实现高效检索。

如要完成本教程,您必须具备以下条件:

  • 以下MongoDB 集群类型之一:

    • 运行 MongoDB 6.0.11 版本的 Atlas 集群,7.0.2或以上版本。确保您的 IP 地址 包含在 Atlas 项目的 访问列表 中。

    • 使用 Python 和 Docker 创建的本地 Atlas 部署。安装 atlas-local-lib-py (pip install atlas-local-lib-py),以编程方式创建和管理本地部署。要了解更多信息,请参阅 atlas-local-lib-py 存储库。

    • A MongoDB Community cluster with Search and Vector Search installed.

  • A Voyage AI API key. To create an API key, see Manage Voyage AI Model API Keys.

  • OpenAI API密钥。您必须拥有一个具有可用于API请求的积分的 OpenAI 帐户。要学习;了解有关注册 OpenAI 帐户的更多信息,请参阅 OpenAI API网站。

  • 运行交互式Python笔记本(例如 Colab)的环境。

为此教程设置环境。 通过保存扩展名为 .ipynb 的文件来创建交互式Python笔记本。 此 Notebook 允许您单独运行Python代码片段,并且您将使用它来运行本教程中的代码。

要设立笔记本环境,请执行以下操作:

1

运行以下命令:

pip install --quiet --upgrade langchain langchain-community langchain-core langchain-mongodb langchain-voyageai langchain-openai pymongo pypdf
2

运行以下代码,将占位符替换为以下值:

  • 您的 Voyage AI和 OpenAI API密钥。

  • MongoDB集群的连接字符串。

import os
os.environ["VOYAGE_API_KEY"] = "<voyage-api-key>"
os.environ["OPENAI_API_KEY"] = "<openai-api-key>"
MONGODB_URI = "<connection-string>"

注意

将 <connection-string> 替换为您的 Atlas 集群或本地部署的连接字符串。

连接字符串应使用以下格式:

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

重要: 确保连接字符串包含数据库用户的凭证。要学习有关查找连接字符串的更多信息,请参阅通过客户端库连接到集群。

Paste and run the following code in your notebook to load and chunk a sample PDF that contains a recent MongoDB earnings report.

该代码使用文本拆分器将 PDF 数据分割成较小的父文档。它指定每个文档的数据块大小(字符数)和数据块重叠(连续数据块之间的重叠字符数)。

from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import PyPDFLoader
# Load the PDF
loader = PyPDFLoader("https://investors.mongodb.com/node/12881/pdf")
data = loader.load()
# Chunk into parent documents
parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=20)
docs = parent_splitter.split_documents(data)
# Print a document
docs[0]

在本部分中,您将实例化父文档检索器,并使用它将数据引入MongoDB中。

MongoDBAtlasParentDocumentRetriever 将父文档分块为较小的子文档,嵌入子文档,然后将父文档和子文档摄取到MongoDB中的同一集合中。在幕后,该检索器创建了以下内容:

  • MongoDBAtlasVectorSearch 的一个实例,这是一种矢量存储,用于处理对子文档的矢量搜索查询。

  • MongoDBDocStore的实例,用于处理父文档存储和检索的文档存储。

1

配置 MongoDBAtlasParentDocumentRetriever 的最快方法是使用 from_connection_string 方法。此代码指定以下参数:

  • connection_string您的 Atlas 连接字符串,用于连接到您的集群。

  • child_splitter:用于将父文档分割为较小子文档的文本拆分器。

  • embedding_model用于嵌入子文档的嵌入模型。

  • database_name 和 collection_name:要导入文档的数据库和集合名称。

  • 以下可选参数用于配置 MongoDBAtlasVectorSearch 向量存储:

    • text_key:文档中包含要嵌入文本的字段。

    • relevance_score:用于向量搜索查询的相关性评分。

    • search_kwargs:在初始搜索中要检索多少个子文档。

from langchain_mongodb.retrievers import MongoDBAtlasParentDocumentRetriever
from langchain_voyageai import VoyageAIEmbeddings
# Define the embedding model to use
embedding_model = VoyageAIEmbeddings(model="voyage-3-large")
# Define the chunking method for the child documents
child_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=20)
# Specify the database and collection name
database_name = "langchain_db"
collection_name = "parent_document"
# Create the parent document retriever
parent_doc_retriever = MongoDBAtlasParentDocumentRetriever.from_connection_string(
connection_string = MONGODB_URI,
child_splitter = child_splitter,
embedding_model = embedding_model,
database_name = database_name,
collection_name = collection_name,
text_key = "page_content",
relevance_score_fn = "dotProduct",
search_kwargs = { "k": 10 },
)
2

然后,运行以下代码,使用检索器的 add_documents 方法将文档导入到 Atlas 中。它将父文档作为输入,并根据您配置检索器的方式接收父文档和子文档。

parent_doc_retriever.add_documents(docs)
3

运行示例代码后,您可以导航到集群中的 langchain_db.parent_document 集合,在 Atlas 用户界面中查看文档。

父文档和子文档都有一个包含分割文本的 page_content 字段。子文档还包含一个额外的 embedding 字段,其中包含分割文本的向量嵌入,以及一个与父文档的 _id 对应的 doc_id 字段。

您可以在 Atlas 用户界面中运行以下查询,将 <id> 占位符替换为有效的文档 ID:

  • 要查看共享相同父文档 ID 的子文档:

    { doc_id: "<id>" }
  • 要查看这些子文档的父文档:

    { _id: "<id>" }

要对 langchain_db.parent_document集合启用向量搜索查询,必须创建MongoDB Vector Search索引。您可以使用 LangChain 辅助工具方法或 PyMongo 驱动程序方法。根据您的首选方法,在您的笔记本中运行以下代码:

# Get the vector store instance from the retriever
vector_store = parent_doc_retriever.vectorstore
# Use helper method to create the vector search index
vector_store.create_vector_search_index(
dimensions = 1024 # The number of dimensions to index
)

The index should take about one minute to build. While it builds, the index is in an initial sync state. When it finishes building, you can start querying the data in your collection.

MongoDB构建索引后,您可以对数据运行向量搜索查询,并使用 RAG管道中的检索器。在笔记本中粘贴并运行以下代码,以实现执行父文档检索的示例RAG管道:

1

要查看与给定查询最相关的文档,请粘贴并运行以下代码,在集合上执行示例向量搜索查询。检索器搜索与 string AI technology 语义相似的相关子文档,然后返回这些子文档对应的父文档。

parent_doc_retriever.invoke("AI technology")

要了解有关使用 LangChain 的向量搜索查询示例的更多信息,请参阅运行向量搜索查询。

2

要创建并运行带有父文档检索器的 RAG 管道,请粘贴并运行以下代码。此代码执行以下操作:

  • 定义 LangChain 提示模板,指示 LLM 使用检索到的父文档作为查询的上下文。LangChain 将这些文档传递给 {context} 输入变量,并将您的查询传递给 {query} 变量。

  • 构造一条指定以下内容的链:

    • 您配置的父文档检索器用于检索相关的父文档。

    • 您定义的提示模板。

    • OpenAI 的法学硕士,用于生成上下文感知响应。 默认下,这是 gpt-3.5-turbo 模型。

  • 使用示例查询提示链并返回响应。 生成的响应可能会有所不同。

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI
# Define a prompt template
template = """
Use the following pieces of context to answer the question at the end.
{context}
Question: {query}?
"""
prompt = PromptTemplate.from_template(template)
model = ChatOpenAI()
# Construct a chain to answer questions on your data
chain = (
{"context": parent_doc_retriever, "query": RunnablePassthrough()}
| prompt
| model
| StrOutputParser()
)
# Prompt the chain
query = "In a list, what are MongoDB's latest AI announcements?"
answer = chain.invoke(query)
print(answer)
1. MongoDB obtained the AWS Modernization Competency designation.
2. MongoDB launched a MongoDB University course focused on building AI applications with MongoDB and AWS.
3. MongoDB announced new technology integrations for AI, data analytics, and automating database deployments across various environments.
4. MongoDB launched the MongoDB AI Applications Program (MAAP) to help companies harness the power of data and future AI technologies.
5. Capgemini, Confluent, IBM, Unstructured, and QuantumBlack joined the MAAP ecosystem to offer customers additional integration and solution options.

观看有关使用 LangChain 和MongoDB检索父文档的视频。

时长:27 分钟