在本文中,我将演示如何使用LlamaIndex与Supabase向量存储进行向量搜索。首先,我们需要配置OpenAI的API密钥并安装必要的软件包。请确保按照以下步骤操作。
安装必要的软件包
%pip install llama-index-vector-stores-supabase
!pip install llama-index
配置OpenAI API密钥
首先设置OpenAI API密钥以便为加载到索引中的文档创建嵌入。
import os
os.environ["OPENAI_API_KEY"] = "[your_openai_api_key]" # 请替换为你的OpenAI API密钥
下载数据
我们将下载一个示例文件来进行演示。
!mkdir -p 'data/paul_graham/'
!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'
加载文档
接下来,我们使用 SimpleDirectoryReader
加载存储在指定目录中的文档。
from llama_index.core import SimpleDirectoryReader
documents = SimpleDirectoryReader("./data/paul_graham/").load_data()
print(
"Document ID:",
documents[0].doc_id,
"Document Hash:",
documents[0].doc_hash,
)
# 输出示例
# Document ID: fb056993-ee9e-4463-80b4-32cf9509d1d8 Document Hash: 77ae91ab542f3abb308c4d7c77c9bc4c9ad0ccd63144802b7cbe7e1bb3a4094e
创建由Supabase向量存储支持的索引
这一步骤适用于所有支持pgvector的Postgres提供商。如果集合不存在,我们将尝试创建一个新集合。
from llama_index.core import VectorStoreIndex, StorageContext
from llama_index.vector_stores.supabase import SupabaseVectorStore
vector_store = SupabaseVectorStore(
postgres_connection_string=(
"postgresql://<user>:<password>@<host>:<port>/<db_name>"
),
collection_name="base_demo",
)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
documents, storage_context=storage_context
)
查询索引
现在我们可以使用索引进行查询。
query_engine = index.as_query_engine()
response = query_engine.query("Who is the author?")
print(response) # 输出作者信息
response = query_engine.query("What did the author do growing up?")
print(response) # 输出作者的成长经历
使用元数据过滤器
我们还可以使用元数据过滤器来进行查询。
from llama_index.core.schema import TextNode
from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters
nodes = [
TextNode(
**{
"text": "The Shawshank Redemption",
"metadata": {
"author": "Stephen King",
"theme": "Friendship",
},
}
),
TextNode(
**{
"text": "The Godfather",
"metadata": {
"director": "Francis Ford Coppola",
"theme": "Mafia",
},
}
),
TextNode(
**{
"text": "Inception",
"metadata": {
"director": "Christopher Nolan",
},
}
),
]
vector_store = SupabaseVectorStore(
postgres_connection_string=(
"postgresql://<user>:<password>@<host>:<port>/<db_name>"
),
collection_name="metadata_filters_demo",
)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex(nodes, storage_context=storage_context)
# 定义元数据过滤器
filters = MetadataFilters(
filters=[ExactMatchFilter(key="theme", value="Mafia")]
)
# 使用过滤器进行检索
retriever = index.as_retriever(filters=filters)
retriever.retrieve("What is inception about?")
# 输出示例
# [NodeWithScore(node=Node(text='The Godfather', ...), score=0.20671339734643313)]
可能遇到的错误及解决方案
-
API Key未设置或错误:
- 请确保已正确设置OpenAI的API密钥,并且其格式正确(必须为字符串值)。如有问题,请重新生成并设置新密钥。
-
数据库连接失败:
- 检查数据库连接字符串是否正确,包括用户名、密码、主机、端口和数据库名。
-
数据加载失败:
- 确认提供的文件路径和文件名是否正确,以及文件是否存在。
参考资料
如果你觉得这篇文章对你有帮助,请点赞,关注我的博客,谢谢!