跳转到内容

存储

一旦您将数据加载建立索引,您可能希望将其存储起来以避免重新索引所需的时间和成本。默认情况下,您的索引数据仅存储在内存中。

存储索引数据的最简单方法是使用每个索引的内置 .persist() 方法,该方法将所有数据写入指定位置的磁盘。这适用于任何类型的索引。

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

以下是一个可组合图的示例:

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

然后你可以像这样加载持久化索引,避免重新加载和重新索引数据:

from llama_index.core import StorageContext, load_index_from_storage
# rebuild storage context
storage_context = StorageContext.from_defaults(persist_dir="<persist_dir>")
# load index
index = load_index_from_storage(storage_context)

正如在索引中所讨论的,最常见的索引类型之一是向量存储索引。在向量存储索引中创建嵌入的API调用在时间和金钱方面可能很昂贵,因此您会希望存储它们以避免不得不频繁重新索引内容。

LlamaIndex 支持大量向量数据库,它们在架构、复杂性和成本方面各不相同。在本示例中,我们将使用 Chroma,一个开源的向量数据库。

首先你需要安装 chroma:

pip install chromadb

要使用 Chroma 存储来自 VectorStoreIndex 的嵌入向量,您需要:

  • 初始化 Chroma 客户端
  • 在 Chroma 中创建一个集合来存储您的数据
  • 将 Chroma 分配为 vector_store 中的 StorageContext
  • 使用该存储上下文初始化您的 VectorStoreIndex

以下是具体实现方式,并抢先预览实际查询数据的过程:

import chromadb
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores.chroma import ChromaVectorStore
from llama_index.core import StorageContext
# load some documents
documents = SimpleDirectoryReader("./data").load_data()
# initialize client, setting path to save data
db = chromadb.PersistentClient(path="./chroma_db")
# create collection
chroma_collection = db.get_or_create_collection("quickstart")
# assign chroma as the vector_store to the context
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
# create your index
index = VectorStoreIndex.from_documents(
documents, storage_context=storage_context
)
# create a query engine and query
query_engine = index.as_query_engine()
response = query_engine.query("What is the meaning of life?")
print(response)

如果您已经创建并存储了嵌入向量,您会希望直接加载它们,而无需加载文档或创建新的向量存储索引:

import chromadb
from llama_index.core import VectorStoreIndex
from llama_index.vector_stores.chroma import ChromaVectorStore
from llama_index.core import StorageContext
# initialize client
db = chromadb.PersistentClient(path="./chroma_db")
# get collection
chroma_collection = db.get_or_create_collection("quickstart")
# assign chroma as the vector_store to the context
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
# load your index from stored vectors
index = VectorStoreIndex.from_vector_store(
vector_store, storage_context=storage_context
)
# create a query engine
query_engine = index.as_query_engine()
response = query_engine.query("What is llama2?")
print(response)

您已准备好进行查询!

Section titled “You’re ready to query!”

现在您已经加载了数据、建立了索引并存储了该索引,接下来可以查询您的数据

如果您已经创建了一个索引,可以使用 insert 方法向索引中添加新文档。

from llama_index.core import VectorStoreIndex
index = VectorStoreIndex([])
for doc in documents:
index.insert(doc)

查看文档管理指南获取更多关于管理文档的详细信息和一个示例笔记本。