Skip to content
LlamaIndex 文档版本 跟随上游 源快照 6c185028 更新于 2026-10-15

持久化数据

默认情况下,LlamaIndex 把数据存在内存中,如需保留可以显式持久化:

storage_context.persist(persist_dir="<persist_dir>")

这会把数据写到磁盘,位于指定的 persist_dir(默认为 ./storage)。

多个索引可以持久化并加载自同一个目录,前提是你自己记住各索引的 ID 以便加载。

用户也可以配置其他存储后端(例如 MongoDB),它们天然就会持久化数据。这种情况下调用 storage_context.persist() 不会做任何事。

加载数据

要加载数据,只需用相同的配置重建存储上下文(例如传入同样的 persist_dir 或向量库客户端)。

storage_context = StorageContext.from_defaults(
    docstore=SimpleDocumentStore.from_persist_dir(persist_dir="<persist_dir>"),
    vector_store=SimpleVectorStore.from_persist_dir(
        persist_dir="<persist_dir>"
    ),
    index_store=SimpleIndexStore.from_persist_dir(persist_dir="<persist_dir>"),
)

随后我们就可以通过下面几个便捷函数,从 StorageContext 加载指定索引。

from llama_index.core import (
    load_index_from_storage,
    load_indices_from_storage,
    load_graph_from_storage,
)

# load a single index
# need to specify index_id if multiple indexes are persisted to the same directory
index = load_index_from_storage(storage_context, index_id="<index_id>")

# don't need to specify index_id if there's only one index in storage context
index = load_index_from_storage(storage_context)

# load multiple indices
indices = load_indices_from_storage(storage_context)  # loads all indices
indices = load_indices_from_storage(
    storage_context, index_ids=[index_id1, ...]
)  # loads specific indices

# load composable graph
graph = load_graph_from_storage(
    storage_context, root_id="<root_id>"
)  # loads graph with the specified root_id

使用远端后端

默认情况下,LlamaIndex 用本地文件系统读写文件。不过你可以传入一个 fsspec.AbstractFileSystem 对象来覆盖这一行为。

这里给一个简单例子,先实例化一个向量库:

import dotenv
import s3fs
import os

dotenv.load_dotenv("../../../.env")

# load documents
documents = SimpleDirectoryReader(
    "../../../examples/paul_graham_essay/data/"
).load_data()
print(len(documents))
index = VectorStoreIndex.from_documents(documents)

到这一步为止都一样的。接下来我们实例化一个 S3 文件系统,并从那里保存/加载。

# set up s3fs
AWS_KEY = os.environ["AWS_ACCESS_KEY_ID"]
AWS_SECRET = os.environ["AWS_SECRET_ACCESS_KEY"]
R2_ACCOUNT_ID = os.environ["R2_ACCOUNT_ID"]

assert AWS_KEY is not None and AWS_KEY != ""

s3 = s3fs.S3FileSystem(
    key=AWS_KEY,
    secret=AWS_SECRET,
    endpoint_url=f"https://{R2_ACCOUNT_ID}.r2.cloudflarestorage.com",
    s3_additional_kwargs={"ACL": "public-read"},
)

# If you're using 2+ indexes with the same StorageContext,
# run this to save the index to remote blob storage
index.set_index_id("vector_index")

# persist index to s3
s3_bucket_name = "llama-index/storage_demo"  # {bucket_name}/{index_name}
index.storage_context.persist(persist_dir=s3_bucket_name, fs=s3)

# load index from s3
index_from_s3 = load_index_from_storage(
    StorageContext.from_defaults(persist_dir=s3_bucket_name, fs=s3),
    index_id="vector_index",
)

默认情况下,如果没有传入文件系统,我们就按本地文件系统处理。

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。