Pinecone是一个功能丰富的向量数据库,今天我们将通过演示如何在Pinecone向量存储中使用自查询检索器(SelfQueryRetriever),来加深对它的理解。首先,我们需要创建一个Pinecone索引,并用一些数据来初始化它。
技术背景介绍
在信息检索与人工智能结合的领域,Pinecone作为一款云原生向量数据库,提供了高度可扩展的解决方案。它能存储、搜索和分析高维向量,这对于需要处理大量非结构化数据的应用非常有用。
核心原理解析
自查询检索器(SelfQueryRetriever)是一种智能检索机制,可以在用户查询中利用文档的元数据进行更为复杂和精准的搜索操作。配合Pinecone的向量存储,这种检索器可以根据文档内容描述和元数据对查询进行自动调整和优化。
代码实现演示(重点)
首先,我们需要安装必要的Python包:
%pip install --upgrade --quiet lark
%pip install --upgrade --quiet pinecone-notebooks pinecone-client==3.2.2
然后,我们开始创建Pinecone索引和初始化存储内容:
from pinecone import Pinecone, ServerlessSpec
from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings
from langchain_pinecone import PineconeVectorStore
# 使用OpenAI的嵌入作为向量化工具
embeddings = OpenAIEmbeddings()
api_key = 'your-api-key' # 请确保在环境变量中正确设置
index_name = "langchain-self-retriever-demo"
pc = Pinecone(api_key=api_key)
# 创建新索引
if index_name not in pc.list_indexes().names():
pc.create_index(
name=index_name,
dimension=1536,
metric="cosine",
spec=ServerlessSpec(cloud="aws", region="us-east-1"),
)
docs = [
Document(page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": ["action", "science fiction"]}),
# 添加更多文档
]
vectorstore = PineconeVectorStore.from_documents(docs, embeddings, index_name=index_name)
接着,我们创建自查询检索器:
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]"),
# 添加更多属性信息
]
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
)
最后,我们可以测试我们的检索器:
# 测试检索器
result = retriever.invoke("What are some movies about dinosaurs")
print(result)
应用场景分析
这种技术在很多场景中都可以大显身手,例如:在线推荐系统、智能问答平台、文档搜索和个性化内容推送等场景中,通过智能匹配用户需求与内容,可以极大提升用户体验。
实践建议
- 数据准备:在使用Pinecone进行搜索前,确保数据经过适当的预处理和向量化。
- 查询优化:充分利用自查询检索器的元数据功能,以便优化查询性能。
- 安全性:确保API密钥的安全存储,避免泄露。
如果遇到问题欢迎在评论区交流。
—END—