【RAG】【vector_stores047】Lantern向量存储索引示例
案例目标
本案例演示如何使用PostgreSQL数据库和Lantern扩展与LlamaIndex框架结合,实现高效的向量搜索和混合搜索功能。主要目标包括:
- 展示如何创建基于Lantern的向量索引
- 演示如何使用HNSW索引参数优化搜索性能
- 展示如何实现混合搜索(向量搜索+全文搜索)
- 演示如何从现有向量存储创建索引
- 展示如何配置文本搜索语言参数
技术栈与核心依赖
核心技术
- LlamaIndex: 用于构建文档索引和查询的框架
- PostgreSQL: 关系型数据库,作为向量存储的基础
- Lantern: PostgreSQL的向量扩展,提供向量搜索功能
- OpenAI: 用于生成文本嵌入向量
核心依赖
pip install llama-index-vector-stores-lantern
pip install llama-index-embeddings-openai
pip install psycopg2-binary
pip install asyncpg
环境配置
在开始之前,需要进行以下环境配置:
1. 安装必要的依赖包
%pip install llama-index-vector-stores-lantern %pip install llama-index-embeddings-openai !pip install psycopg2-binary llama-index asyncpg2. 配置OpenAI API密钥
import os os.environ["OPENAI_API_KEY"] = "<your_key>" openai.api_key = "<your_key>"3. 配置嵌入模型
from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core import Settings # 设置全局嵌入模型 Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small")4. 创建PostgreSQL数据库
import psycopg2 connection_string = "postgresql://postgres:postgres@localhost:5432" db_name = "postgres" conn = psycopg2.connect(connection_string) conn.autocommit = True with conn.cursor() as c: c.execute(f"DROP DATABASE IF EXISTS {db_name}") c.execute(f"CREATE DATABASE {db_name}")案例实现
1. 导入必要的库
from llama_index.core import SimpleDirectoryReader, StorageContext from llama_index.core import VectorStoreIndex from llama_index.vector_stores.lantern import LanternVectorStore import textwrap import openai from sqlalchemy import make_url2. 加载文档数据
# 创建目录并下载数据 !mkdir -p 'data/paul_graham/' !wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt' # 加载文档 documents = SimpleDirectoryReader("./data/paul_graham").load_data() print("Document ID:", documents[0].doc_id)3. 创建Lantern向量存储和索引
url = make_url(connection_string) vector_store = LanternVectorStore.from_params( database=db_name, host=url.host, password=url.password, port=url.port, user=url.username, table_name="paul_graham_essay", embed_dim=1536, # openai embedding dimension ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex.from_documents( documents, storage_context=storage_context, show_progress=True ) query_engine = index.as_query_engine()4. 执行查询
# 查询作者做了什么 response = query_engine.query("What did the author do?") print(textwrap.fill(str(response), 100)) # 查询1980年代中期发生了什么 response = query_engine.query("What happened in the mid 1980s?") print(textwrap.fill(str(response), 100))5. 从现有向量存储创建索引
vector_store = LanternVectorStore.from_params( database=db_name, host=url.host, password=url.password, port=url.port, user=url.username, table_name="paul_graham_essay", embed_dim=1536, # openai embedding dimension m=16, # HNSW M parameter ef_construction=128, # HNSW ef construction parameter ef=64, # HNSW ef search parameter ) index = VectorStoreIndex.from_vector_store(vector_store=vector_store) query_engine = index.as_query_engine() response = query_engine.query("What did the author do?") print(textwrap.fill(str(response), 100))6. 实现混合搜索
# 创建支持混合搜索的向量存储 hybrid_vector_store = LanternVectorStore.from_params( database=db_name, host=url.host, password=url.password, port=url.port, user=url.username, table_name="paul_graham_essay_hybrid_search", embed_dim=1536, # openai embedding dimension hybrid_search=True, text_search_config="english", ) storage_context = StorageContext.from_defaults( vector_store=hybrid_vector_store ) hybrid_index = VectorStoreIndex.from_documents( documents, storage_context=storage_context ) # 创建混合查询引擎 hybrid_query_engine = hybrid_index.as_query_engine( vector_store_query_mode="hybrid", sparse_top_k=2 ) hybrid_response = hybrid_query_engine.query( "Who does Paul Graham think of with the word schtick" ) print(hybrid_response)案例效果
通过本案例的实现,可以达到以下效果:
查询效果示例
查询:"What did the author do?"
结果:返回关于Paul Graham职业生涯和创业经历的详细信息
查询:"What happened in the mid 1980s?"
结果:返回关于1980年代中期AI发展的相关信息
混合搜索查询:"Who does Paul Graham think of with the word schtick"
结果:通过向量搜索和全文搜索的组合,返回更精确的结果
技术效果
- 高效的向量搜索和检索
- 支持HNSW索引优化搜索性能
- 支持混合搜索(向量+全文)
- 可以从现有向量存储创建索引
- 支持多种文本搜索语言配置
案例实现思路
本案例的实现思路如下:
- 环境准备:安装必要的依赖库,包括LlamaIndex、Lantern向量存储和PostgreSQL连接器
- 数据库准备:创建PostgreSQL数据库,配置连接参数
- 数据准备:下载并加载Paul Graham的散文作为示例文档
- 向量存储初始化:创建LanternVectorStore实例,配置嵌入维度
- 索引创建:使用加载的文档创建向量索引
- 查询执行:执行查询并获取结果,展示基本向量搜索功能
- 索引复用:展示如何从现有向量存储创建索引,并配置HNSW参数
- 混合搜索实现:创建支持混合搜索的向量存储,结合向量搜索和全文搜索
关键技术点
- HNSW索引:使用分层可导航小世界图索引提高搜索性能
- 混合搜索:结合向量搜索和全文搜索,提高搜索准确性
- 向量存储复用:从现有向量存储创建索引,避免重复构建
- 文本搜索配置:支持多语言文本搜索配置
扩展建议
基于本案例,可以考虑以下扩展方向:
功能扩展
- 实现更复杂的元数据过滤功能
- 添加自定义重排序策略
- 实现多语言混合搜索
- 添加向量相似度阈值过滤
- 实现增量更新索引功能
应用场景扩展
- 构建企业知识库检索系统
- 实现文档相似性分析工具
- 开发智能问答系统
- 构建学术论文检索平台
- 实现多模态搜索系统
性能优化建议
- 调整HNSW索引参数(m, ef_construction, ef)以平衡索引构建速度和查询性能
- 优化向量维度和嵌入模型以提高检索精度
- 考虑使用PostgreSQL分区表处理大规模数据
- 调整混合搜索中的sparse_top_k参数以优化全文搜索结果
总结
本案例展示了如何使用LlamaIndex和Lantern向量存储构建高效的向量搜索系统。通过PostgreSQL和Lantern扩展,我们可以利用关系型数据库的强大功能和向量搜索的高效性,实现高性能的向量检索。
案例中介绍了两种主要的搜索方式:纯向量搜索和混合搜索。纯向量搜索适用于语义相似性查询,而混合搜索结合了向量搜索和全文搜索的优势,能够提供更准确和全面的搜索结果。
通过调整HNSW索引参数,我们可以根据具体应用场景优化搜索性能。Lantern作为PostgreSQL的向量扩展,不仅提供了高效的向量搜索能力,还保持了与PostgreSQL生态系统的兼容性,使得开发者可以利用PostgreSQL的丰富功能,如事务、并发控制和扩展性。
总的来说,LlamaIndex和Lantern的结合为构建高性能的向量搜索应用提供了一个强大而灵活的解决方案,适用于各种需要高效向量搜索的应用场景。
