人工智能RAG大模型【免费下载链接】llama_indexLlamaIndex is the document processing platform for AI项目地址https://gitcode.com/GitHub_Trending/ll/llama_index点击查看免费下载本指南以 LlamaIndex 官方 API 参考文档 TimescaleVectorStore 为线索围绕其完整源码实现与官方示例 Notebook系统讲解如何用 TimescaleDB 作为 LlamaIndex 的向量存储后端。你将掌握TimescaleVectorStore的安装、参数配置、索引构建、ANN 索引管理以及最具特色的按时间分区的向量相似度检索在 Retriever 与 Query Engine 中的落地用法。TimescaleVectorStore 是什么TimescaleVectorStore是 LlamaIndex 官方向量存储集成之一其定位在官方集成清单中被列为TimeScale (TimescaleVectorStore)详见 vector_stores.md。它把 TimescaleDB——一个面向 AI 应用增强的 PostgreSQL——接入 LlamaIndex 的向量索引体系增强 pgvector通过受 DiskANN 启发的索引算法在海量向量上提供更快、更准的相似度检索自动按时间分区向量及其元数据按时间自动分表支持既按向量相似度、又按时间范围的高效检索熟悉的 SQL 接口向量与关系型元数据共存于同一数据库可直接用 PostgreSQL 生态工具查询。整个集成由独立包llama-index-vector-stores-timescalevector提供核心实现只有约 300 行位于 base.py底层依赖timescale-vectorPython 客户端与llama-index-core见 pyproject.toml。安装与快速开始安装依赖在项目中安装 TimescaleVectorStore 集成包即可示例 Notebook 中通常还会一并安装 OpenAI 嵌入模型包见 Timescalevector.ipynbpip install llama-index-vector-stores-timescalevector pip install llama-index-embeddings-openai # 生成向量嵌入时使用获取连接串并初始化TimescaleVectorStore 的核心构造参数是service_urlTimescale 云数据库连接串与table_name存储向量的表名。官方推荐通过from_params类方法创建实例这是源码中定义的工厂方法base.pyfrom llama_index.vector_stores.timescalevector import TimescaleVectorStore TIMESCALE_SERVICE_URL postgres://tsdbadmin:passwordid.tsdb.cloud.timescale.com:port/tsdb?sslmoderequire vector_store TimescaleVectorStore.from_params( service_urlTIMESCALE_SERVICE_URL, table_nameyour_table_name_here, num_dimensions1536, # 可选默认 1536 )也可以在环境变量中存放连接串.env中以TIMESCALE_SERVICE_URLpostgresql://开头再用python-dotenv读取避免密钥硬编码。参数说明from_params与构造函数__init__的参数完全一致base.py参数类型默认值说明service_urlstr必填PostgreSQL/Timescale 连接串table_namestr必填存储向量的表名构造时会被自动转为小写num_dimensionsintDEFAULT_EMBEDDING_DIM1536向量维度须与所用嵌入模型输出维度一致time_partition_intervalOptional[timedelta]None时间分区间隔传入后启用按时间分区能力且表 id 必须是 UUID v1初始化时会自动完成两件事base.py_create_clients()分别创建同步客户端client.Sync与异步客户端client.Async两者共享同一连接串、表名与维度。若设置了time_partition_intervalid 类型固定为UUID否则为TEXT_create_tables()通过同步客户端调用create_tables()自动建表无需手工执行 DDL。与 VectorStoreIndex 集成建索引、查询、复用从文档构建索引TimescaleVectorStore 可像其他向量存储一样作为VectorStoreIndex的后端。通过StorageContext把向量存储注入索引LlamaIndex 会负责切分文档、调用嵌入模型并写入 Timescale 表from llama_index.core import SimpleDirectoryReader, StorageContext, VectorStoreIndex from llama_index.vector_stores.timescalevector import TimescaleVectorStore # 加载文档 documents SimpleDirectoryReader(./data/paul_graham).load_data() # 创建向量存储 vector_store TimescaleVectorStore.from_params( service_urlTIMESCALE_SERVICE_URL, table_namepaul_graham_essay, ) # 构建索引 storage_context StorageContext.from_defaults(vector_storevector_store) index VectorStoreIndex.from_documents(documents, storage_contextstorage_context) # 查询 query_engine index.as_query_engine() response query_engine.query(Did the author work at YC?)复用已有的索引Timescale 表中的数据持久保存在云端因此重启进程后只需连接串与表名即可恢复索引无需重新入库Timescalevector.ipynb 中的 Querying existing index 一节vector_store TimescaleVectorStore.from_params( service_urlTIMESCALE_SERVICE_URL, table_namepaul_graham_essay, ) index VectorStoreIndex.from_vector_store(vector_storevector_store) query_engine index.as_query_engine() response query_engine.query(What did the author do before YC?)源码级实现剖析数据写入node 转行add/async_add负责把 LlamaIndex 的BaseNode转换成 Timescale 客户端可识别的行并upsert入库base.py元数据经node_to_metadata_dict序列化remove_textTrue表示文本单独存列、不重复嵌入元数据flat_metadata决定元数据是否扁平化存储默认复用node.node_id作为主键启用时间分区后主键必须是 UUID v1。源码会先尝试解析现有 id若非 UUID 或不是 v1 版本则用uuid.uuid1()自动生成从而让行的时间属性由插入时刻决定每一行包含[id, metadata, text, embedding]四个字段。查询与元数据过滤query/aquery将VectorStoreQuery转换为底层搜索base.py查询向量取query.query_embedding返回条数取query.similarity_top_k。VectorStoreQuery是 LlamaIndex 核心定义的通用查询结构含query_embedding、similarity_top_k、filters等字段见 types.py。MetadataFilters会被_filter_to_dict拍平成{key: value}字典传给底层搜索空过滤器返回None不做额外条件。结果通过_db_rows_to_query_result还原为VectorStoreQueryResultnodes / similarities / ids优先用metadata_dict_to_node重建节点若旧数据格式不兼容则回退到TextNode兼容逻辑保证向后兼容。删除delete(ref_doc_id)以{doc_id: ref_doc_id}作为元数据过滤条件调用delete_by_metadata即按文档 ID 批量清理其下所有节点向量base.py。同步/异步双通道存储类同时维护client.Sync与client.Async两套底层客户端同步方法add/query/delete与异步方法async_add/aquery一一对应方便在异步应用中使用close()会同时关闭两个客户端base.py。加速检索三种 ANN 索引的管理当数据量增长后可以对 embedding 列创建 ANN 索引加速相似度检索。注意这里的索引是数据库层的 ANN 索引与 LlamaIndex 的索引概念不同。TimescaleVectorStore 通过枚举IndexType支持三种索引base.py枚举值底层索引特点TIMESCALE_VECTOR默认DiskANN 启发的图索引TimescaleVectorIndex默认推荐海量向量下检索更快更准PGVECTOR_HNSWpgvector 的 HNSW分层可导航小世界图召回精度高官方同样推荐PGVECTOR_IVFFLATpgvector 的 IVFFLAT倒排文件索引适合大数据量批量导入后使用创建与删除create_index(index_typeDEFAULT_INDEX_TYPE, **kwargs)默认创建 timescale_vectorDiskANN索引drop_index()删除当前索引base.py# 默认创建 DiskANN 索引 vector_store.create_index() # 删除后用自定义参数重建 DiskANN 索引 vector_store.drop_index() vector_store.create_index(tsv, max_alpha1.0, num_neighbors50) # 切换为 HNSW 索引m、ef_construction 有智能默认值 vector_store.drop_index() vector_store.create_index(hnsw, m16, ef_construction64) # 切换为 IVFFLAT 索引num_lists、num_records 有智能默认值 vector_store.drop_index() vector_store.create_index(ivfflat, num_lists20, num_records1000)注意事项单表单索引PostgreSQL 中一张表的一个列只能有一个索引。若想对比不同索引类型的性能可以建多张表、在同一张表加多个向量列分别建索引或反复 drop 后重建对比时机建议最好在数据大部分入库之后再创建 ANN 索引如 IVFFLAT 依赖数据分布统计推荐取舍官方示例建议日常优先使用timescale-vectorDiskANN或HNSW索引。时间感知检索TimescaleVectorStore 的核心差异化能力这是 Timescale Vector 区别于普通 pgvector 方案的关键特性向量与元数据按时间自动分区检索时可以同时约束向量相似度 时间范围并且只扫描相关分区效率很高。典型应用场景包括LLM 对话历史存储与召回、按最近时间检索相似新闻、对知识库做时间段限定问答。1. 启用时间分区在创建 store 时传入time_partition_interval例如按 7 天一个分区from datetime import timedelta ts_vector_store TimescaleVectorStore.from_params( service_urlTIMESCALE_SERVICE_URL, table_nameli_commit_history, time_partition_intervaltimedelta(days7), )分区粒度需按查询习惯权衡频繁查最近数据可用timedelta(days1)跨十年的大时间窗可用半年或一年。2. 让节点携带历史时间戳启用分区后主键必须是 UUID v1。如果节点代表过去某时刻的数据例如 git 提交记录需用时间戳手工生成 UUID v1如果希望绑定当前时间则无需处理——入库时源码会自动生成 UUID v1。示例 Notebook 中通过timescale_vector客户端的uuid_from_time完成from timescale_vector import client from datetime import datetime def create_uuid(date_string: str): time_format %a %b %d %H:%M:%S %Y %z datetime_obj datetime.strptime(date_string, time_format) return str(client.uuid_from_time(datetime_obj)) # 构造带历史时间戳 id 的 TextNode node TextNode( id_create_uuid(record[date]), textrecord_content, metadata{commit: ..., author: ..., date: ...}, )3. 三种时间过滤查询方式query()额外接受时间过滤关键字参数内部经date_to_range_filter构造client.UUIDTimeRangebase.py关键字含义start_date起始时间含边界由start_inclusive控制默认含end_date结束时间含边界由end_inclusive控制默认含time_delta时间增量配合start_date或end_date使用start_inclusive/end_inclusive边界是否包含默认均为包含方法一给定起止日期范围from llama_index.core.vector_stores import VectorStoreQuery vector_store_query VectorStoreQuery(query_embeddingquery_embedding, similarity_top_k5) query_result ts_vector_store.query( vector_store_query, start_datestart_dt, end_dateend_dt )方法二从起始日期向后推一个时间窗start_date time_deltaquery_result ts_vector_store.query( vector_store_query, start_datestart_dt, time_deltatimedelta(days7) )方法三从结束日期向前推一个时间窗end_date - time_deltaquery_result ts_vector_store.query( vector_store_query, end_dateend_dt, time_deltatimedelta(days7) )三种方式返回的都是VectorStoreQueryResult其中nodes只包含落在指定时间范围内的向量且只扫描相关分区查询效率很高。4. 在 Retriever 与 Query Engine 中使用时间过滤时间过滤参数可以通过vector_store_kwargs透传给 Retriever 与 Query Engine从而把时间段限定直接融入 RAG 链路Timescalevector.ipynb 第四节from llama_index.core import VectorStoreIndex index VectorStoreIndex.from_vector_store(ts_vector_store) # Retriever 限定时间窗 retriever index.as_retriever( vector_store_kwargs{start_date: start_dt, time_delta: timedelta(days7)} ) nodes retriever.retrieve(Whats new with TimescaleDB functions?) # Query Engine 限定时间窗 query_engine index.as_query_engine( vector_store_kwargs{start_date: start_dt, end_date: end_dt} ) response query_engine.query(Whats new with TimescaleDB functions?)这样即可实现只基于某个时间段内的知识回答近期问题等时间感知 RAG 应用。使用流程总结在 Timescale 云平台创建 PostgreSQL 数据库获取形如postgres://tsdbadmin:passwordid.tsdb.cloud.timescale.com:port/tsdb?sslmoderequire的service_urlpip install llama-index-vector-stores-timescalevector如需嵌入一并安装对应 embedding 包通过from_params(service_url..., table_name..., num_dimensions..., time_partition_interval...)创建实例表会自动创建用StorageContext将 store 注入VectorStoreIndex从文档建索引或通过from_vector_store复用已有表数据量上来后用create_index创建 DiskANN / HNSW / IVFFLAT 索引加速检索需要时间感知检索时设置time_partition_interval、使用 UUID v1 节点 id并在query、as_retriever、as_query_engine中传入start_date/end_date/time_delta。延伸阅读集成包完整源码base.py官方实战示例Timescalevector.ipynb通用向量存储协议与查询结构types.py向量存储集成总览vector_stores.md赞分享人工智能RAG大模型【免费下载链接】llama_indexLlamaIndex is the document processing platform for AI项目地址https://gitcode.com/GitHub_Trending/ll/llama_index点击查看免费下载相关推荐AI Engineer 路线图中的 Supabase Vector基于 pgvector 的 PostgreSQL 向量存储与相似度检索AI Engineer 路线图中的 Supabase Vector基于 pgvector 的 PostgreSQL 向量存储与相似度检索 本文围绕 devel文档教程知识库Feast Faiss 在线存储基于向量相似度检索的在线特征存储实现指南Feast Faiss 在线存储基于向量相似度检索的在线特征存储实现指南 Faiss 在线存储Faiss Online Store是 Feast 针对 EMLOps后端数据工程Dataherald向量存储查询基于语义的相似内容检索Dataherald向量存储查询基于语义的相似内容检索 引言从关键词匹配到语义理解的革命 你是否还在为传统SQL查询的局限性而苦恼当用户用自然语言提问显后端人工智能大模型RAG微调创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考