【RAG】【vector_stores002】Google AlloyDB for PostgreSQL 向量存储完整案例
本案例演示如何使用 LlamaIndex 与 Google AlloyDB for PostgreSQL 集成实现向量存储和检索功能用于构建基于文档的问答系统。1. 案例目标本案例的主要目标是设置 AlloyDB 向量存储配置 LlamaIndex 以使用 Google AlloyDB for PostgreSQL 作为向量数据库。文档索引与存储将文档内容加载并存储到 AlloyDB 向量数据库中。查询与检索基于存储的文档内容实现自然语言查询并获取相关答案。元数据过滤演示如何使用元数据过滤来精确控制搜索结果。向量索引优化展示如何添加向量索引以提高查询性能。2. 技术栈与核心依赖LlamaIndex用于构建基于 LLM 的应用程序的框架llama-index-alloydb-pgLlamaIndex 的 AlloyDB 向量存储插件llama-index-embeddings-vertexVertex AI 文本嵌入模型llama-index-llms-vertexVertex AI 大语言模型Google AlloyDB for PostgreSQLGoogle Cloud 提供的完全托管的关系型数据库服务核心依赖安装%pip install --upgrade --quiet llama-index-alloydb-pg llama-index-embeddings-vertex llama-index-llms-vertex llama-index3. 环境配置在使用本案例前需要完成以下环境配置Google Cloud 项目创建一个 Google Cloud 项目启用 AlloyDB API在 Google Cloud 控制台中启用 AlloyDB APIAlloyDB 集群和实例创建 AlloyDB 集群和实例AlloyDB 数据库创建 AlloyDB 数据库数据库用户为数据库添加用户身份验证配置 Google Cloud 身份验证4. 案例实现4.1 身份验证和项目设置# 身份验证 from google.colab import auth auth.authenticate_user() # 设置 Google Cloud 项目 PROJECT_ID my-project-id # 替换为您的项目ID !gcloud config set project {PROJECT_ID}4.2 设置 AlloyDB 数据库参数# AlloyDB 数据库连接参数 REGION us-central1 # 替换为您的区域 CLUSTER my-cluster # 替换为您的集群名称 INSTANCE my-primary # 替换为您的实例名称 DATABASE my-database # 替换为您的数据库名称 TABLE_NAME vector_store # 替换为您的表名 USER postgres # 替换为您的用户名 PASSWORD my-password # 替换为您的密码4.3 创建 AlloyDB 引擎from llama_index_alloydb_pg import AlloyDBEngine # 使用实例信息创建 AlloyDB 引擎 engine await AlloyDBEngine.afrom_instance( project_idPROJECT_ID, regionREGION, clusterCLUSTER, instanceINSTANCE, databaseDATABASE, userUSER, passwordPASSWORD, )4.4 初始化向量存储表# 初始化向量存储表 await engine.ainit_vector_store_table( table_nameTABLE_NAME, vector_size768, # VertexAI 模型的向量大小 )4.5 配置嵌入模型和 LLM# 启用 Vertex AI API !gcloud services enable aiplatform.googleapis.com # 配置嵌入模型和 LLM from llama_index.core import Settings from llama_index.embeddings.vertex import VertexTextEmbedding from llama_index.llms.vertex import Vertex import google.auth credentials, project_id google.auth.default() Settings.embed_model VertexTextEmbedding( model_nametextembedding-gecko003, projectPROJECT_ID, credentialscredentials, ) Settings.llm Vertex(modelgemini-1.5-flash-002, projectPROJECT_ID)4.6 创建向量存储from llama_index_alloydb_pg import AlloyDBVectorStore # 创建向量存储 vector_store await AlloyDBVectorStore.create( engineengine, table_nameTABLE_NAME, )4.7 准备数据并创建索引# 下载数据 !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 # 加载文档 from llama_index.core import SimpleDirectoryReader documents SimpleDirectoryReader(./data/paul_graham).load_data() # 创建索引 from llama_index.core import StorageContext, VectorStoreIndex storage_context StorageContext.from_defaults(vector_storevector_store) index VectorStoreIndex.from_documents( documents, storage_contextstorage_context, show_progressTrue )4.8 查询索引# 创建查询引擎并执行查询 query_engine index.as_query_engine() response query_engine.query(What did the author do?) print(response)4.9 创建自定义向量存储from llama_index_alloydb_pg import Column # 设置表名 TABLE_NAME vectorstore_custom # 创建带有自定义元数据列的表 await engine.ainit_vector_store_table( table_nameTABLE_NAME, vector_size768, # VertexAI 模型: textembedding-gecko003 metadata_columns[Column(len, INTEGER)], ) # 初始化自定义向量存储 custom_store await AlloyDBVectorStore.create( engineengine, table_nameTABLE_NAME, metadata_columns[len], )4.10 添加带元数据的文档from llama_index.core import Document # 创建带元数据的文档 fruits [apple, pear, orange, strawberry, banana, kiwi] documents [ Document(textfruit, metadata{len: len(fruit)}) for fruit in fruits ] storage_context StorageContext.from_defaults(vector_storecustom_store) custom_doc_index VectorStoreIndex.from_documents( documents, storage_contextstorage_context, show_progressTrue )4.11 使用元数据过滤搜索from llama_index.core.vector_stores.types import ( MetadataFilter, MetadataFilters, FilterOperator, ) # 创建过滤器 filters MetadataFilters( filters[ MetadataFilter(keylen, operatorFilterOperator.GT, value5), ], ) # 使用过滤器查询 query_engine custom_doc_index.as_query_engine(filtersfilters) res query_engine.query(List some fruits) print(str(res.source_nodes[0].text))4.12 添加向量索引from llama_index_alloydb_pg.indexes import IVFFlatIndex # 添加 IVFFlat 索引 index IVFFlatIndex() await vector_store.aapply_vector_index(index)4.13 添加 ScaNN 索引仅适用于 AlloyDB Omnifrom llama_index_alloydb_pg.indexes import ScaNNIndex # 设置向量大小 VECTOR_SIZE 768 # 替换为您的嵌入模型的向量大小 # 创建 ScaNN 索引 index ScaNNIndex(namemy_scann_index) await vector_store.aset_maintenance_work_mem(index.num_leaves, VECTOR_SIZE) await vector_store.aapply_vector_index(index)4.14 重新索引和删除索引# 重新索引 await vector_store.areindex() # 使用默认索引名称重新索引 # 删除索引 await vector_store.adrop_vector_index() # 使用默认名称删除索引5. 案例效果通过本案例您可以实现将文档内容向量化并存储到 Google AlloyDB for PostgreSQL 中使用自然语言查询文档内容如 What did the author do?获取基于文档内容的准确回答使用元数据过滤精确控制搜索结果通过添加向量索引提高查询性能6. 案例实现思路本案例的核心实现思路是环境准备配置 Google Cloud 项目和 AlloyDB 实例数据库连接使用AlloyDBEngine建立与 AlloyDB 的连接表初始化创建适合向量存储的数据库表结构模型配置配置 Vertex AI 的嵌入模型和语言模型向量存储使用AlloyDBVectorStore创建向量存储文档处理使用SimpleDirectoryReader加载文档索引创建使用VectorStoreIndex将文档内容向量化并存储查询执行通过query_engine执行自然语言查询高级功能实现元数据过滤和向量索引优化7. 扩展建议批量文档处理扩展系统以支持批量处理多个文档高级元数据过滤实现更复杂的元数据过滤条件如范围查询、多条件组合等混合搜索结合向量搜索和传统文本搜索提高检索精度性能优化针对大规模文档集优化索引和查询性能实时更新实现文档内容的实时更新和增量索引多语言支持扩展系统以支持多语言文档处理和查询自定义嵌入模型集成其他嵌入模型替代 Vertex AI分布式处理利用 AlloyDB 的分布式特性处理大规模数据8. 总结本案例展示了如何使用 LlamaIndex 与 Google AlloyDB for PostgreSQL 集成构建一个基于向量存储的文档问答系统。通过将文档内容向量化并存储在 AlloyDB 中我们可以实现高效的语义搜索和准确的问答功能。AlloyDB 作为 Google Cloud 提供的完全托管的关系型数据库服务提供了高性能、高可用性和可扩展性特别适合需要处理大量文档并提供智能问答的企业应用场景。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2486857.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!