索引 Indexes

Index 把 Node 组织成查询时能快速取回的结构。LlamaIndex 里最常用的是 VectorStoreIndex:每个 Node 有一条 embedding,查询时做相似度检索。其他索引(摘要、关键词、树、属性图)解决不同取回模式;入门先把向量索引吃透,再按官方模块指南扩展。

本站 RAG 课讲「为什么要索引」;本章讲 LlamaIndex 里 怎么建、怎么存、怎么增量插入


VectorStoreIndex.from_documents

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

documents = SimpleDirectoryReader("data").load_data()
index = VectorStoreIndex.from_documents(documents)

幕后步骤(可被 Settings / transformations / storage_context 改写):

  1. 按 splitter 把 Document 切成 Node
  2. Settings.embed_model(未设置时走捆绑的 OpenAI embedding,历史默认 text-embedding-ada-002)计算向量
  3. 写入 StorageContext 里的 vector store(默认内存 SimpleVectorStore

指定切分与 LLM(示例用 gpt-4o-mini,以当前文档为准):

from llama_index.core import Settings, VectorStoreIndex
from llama_index.core.node_parser import SentenceSplitter
from llama_index.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding

Settings.llm = OpenAI(model="gpt-4o-mini")
Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small")

index = VectorStoreIndex.from_documents(
    documents,
    transformations=[SentenceSplitter(chunk_size=512, chunk_overlap=50)],
    show_progress=True,
)

从已有 Node 构建:VectorStoreIndex(nodes)。已经把向量放进外部库时:VectorStoreIndex.from_vector_store(vector_store)(见 向量库)。


磁盘持久化(默认存储)

内存索引进程一结束就没了,embedding 既贵又慢,所以要 persist:

index.storage_context.persist(persist_dir="storage")

from llama_index.core import StorageContext, load_index_from_storage

storage_context = StorageContext.from_defaults(persist_dir="storage")
index = load_index_from_storage(storage_context)

StorageContext 同时管 docstore / index store / vector store。自定义过 embed 或 transformations 的,加载时必须恢复同样的 Settings

增量插入:

from llama_index.core import Document

index.insert(Document(text="新公告:下周系统维护。", metadata={"source": "notice"}))
index.storage_context.persist(persist_dir="storage")

其他索引类型(知道即可)

类型取回直觉何时考虑
VectorStoreIndex语义相似的 top-k 块默认;绝大多数 RAG
SummaryIndex(列表/摘要)按序或摘要式扫过节点需要「整份文档总结」多于「局部问答」
KeywordTableIndex关键词 → 节点专有名词多、语义检索不稳
TreeIndex分层摘要树长文档先粗后细
PropertyGraphIndex实体关系图 + 向量多跳「谁和谁有关」

不必一上来组合多种索引。先向量检索稳定,再按评测加关键词或图。组合查询可在 查询引擎 / 检索 用 Router 或融合 Retriever,而不是把所有数据复制进五套结构。


索引不是数据库全文

Index 为 给 LLM 用的上下文选择 优化,不是替代 Postgres 里的业务表。结构化过滤、权限、事务仍应放在原系统;LlamaIndex 负责「这段自然语言该带上哪些块」。权限模型简单做法:按租户分 collection / persist 目录,或在 metadata 里打 tenant_id 并在检索时过滤。


常见问题

重复 from_documents 导致账单翻倍?
启动时先看 storage/ 是否存在,存在就 load_index_from_storage,不要每次重建。

换了 embedding 模型答案变差?
新旧向量不在同一空间。必须清空存储后全量重建。

from_documents 卡在 embedding?
检查网络与 Key;可 show_progress=True。大批量用 ingestion pipeline + 外部向量库批写。


下一步

评论