存储
一旦您将数据加载并建立索引,您可能希望将其存储起来以避免重新索引所需的时间和成本。默认情况下,您的索引数据仅存储在内存中。
存储索引数据的最简单方法是使用每个索引的内置 .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 contextstorage_context = StorageContext.from_defaults(persist_dir="<persist_dir>")
# load indexindex = load_index_from_storage(storage_context)正如在索引中所讨论的,最常见的索引类型之一是向量存储索引。在向量存储索引中创建嵌入的API调用在时间和金钱方面可能很昂贵,因此您会希望存储它们以避免不得不频繁重新索引内容。
LlamaIndex 支持大量向量数据库,它们在架构、复杂性和成本方面各不相同。在本示例中,我们将使用 Chroma,一个开源的向量数据库。
首先你需要安装 chroma:
pip install chromadb要使用 Chroma 存储来自 VectorStoreIndex 的嵌入向量,您需要:
- 初始化 Chroma 客户端
- 在 Chroma 中创建一个集合来存储您的数据
- 将 Chroma 分配为
vector_store中的StorageContext - 使用该存储上下文初始化您的 VectorStoreIndex
以下是具体实现方式,并抢先预览实际查询数据的过程:
import chromadbfrom llama_index.core import VectorStoreIndex, SimpleDirectoryReaderfrom llama_index.vector_stores.chroma import ChromaVectorStorefrom llama_index.core import StorageContext
# load some documentsdocuments = SimpleDirectoryReader("./data").load_data()
# initialize client, setting path to save datadb = chromadb.PersistentClient(path="./chroma_db")
# create collectionchroma_collection = db.get_or_create_collection("quickstart")
# assign chroma as the vector_store to the contextvector_store = ChromaVectorStore(chroma_collection=chroma_collection)storage_context = StorageContext.from_defaults(vector_store=vector_store)
# create your indexindex = VectorStoreIndex.from_documents( documents, storage_context=storage_context)
# create a query engine and queryquery_engine = index.as_query_engine()response = query_engine.query("What is the meaning of life?")print(response)如果您已经创建并存储了嵌入向量,您会希望直接加载它们,而无需加载文档或创建新的向量存储索引:
import chromadbfrom llama_index.core import VectorStoreIndexfrom llama_index.vector_stores.chroma import ChromaVectorStorefrom llama_index.core import StorageContext
# initialize clientdb = chromadb.PersistentClient(path="./chroma_db")
# get collectionchroma_collection = db.get_or_create_collection("quickstart")
# assign chroma as the vector_store to the contextvector_store = ChromaVectorStore(chroma_collection=chroma_collection)storage_context = StorageContext.from_defaults(vector_store=vector_store)
# load your index from stored vectorsindex = VectorStoreIndex.from_vector_store( vector_store, storage_context=storage_context)
# create a query enginequery_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)查看文档管理指南获取更多关于管理文档的详细信息和一个示例笔记本。