柬埔寨金边华群学校
发布日期:2025-12-17 13:15 点击次数:141前边著述 两行代码就完毕了文档的切分和向量化存储以及执久化存储。如若咱们思用自界说的向量化数据库呢?
0. 布景前边著述 两行代码就完毕了文档的切分和向量化存储以及执久化存储。
index = VectorStoreIndex.from_documents(documents)# store it for laterindex.storage_context.persist(persist_dir=PERSIST_DIR)
然而偶而辰咱们更但愿使用我方常用的向量数据库和向量化面貌。底下以 chromadb 为例,先容怎样使用。
1. 在 LlamaIndex 中使用自界说的向量数据库(1)环境准备
写代码之前,需要最初装配 LlamaIndex 中的 chromadb。
pip install -U llama-index-vector-stores-chroma -i https://pypi.tuna.tsinghua.edu.cn/simple
(2)创建一个chromadb 数据库的实例
db = chromadb.PersistentClient(path="D:\\GitHub\\LEARN_LLM\\LlamaIndex\\vector_store\\chroma_db")
(3)创建 chroma 数据库的 collection
chroma_collection = db.get_or_create_collection("quickstart")(4)将 chroma_collection 使用 LlamaIndex 的 ChromaVectorStore 进行以下类型治愈和封装,治愈成 LlamaIndex 的 VectorStore。
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
(5)将 VectorStore 封装到 StorageContext 中
storage_context = StorageContext.from_defaults(vector_store=vector_store)
(6)创建 VectorStoreIndex 时,使用 from_documents 函数中的 storage_context 参数,将上头自界说的 storage_context 传入。
index = VectorStoreIndex.from_documents( documents, storage_context=storage_context)
完好意思代码如下:
import chromadbfrom llama_index.core import VectorStoreIndex, SimpleDirectoryReaderfrom llama_index.vector_stores.chroma import ChromaVectorStorefrom llama_index.core import StorageContext# load some documentsdocuments = SimpleDirectoryReader("D:\\GitHub\\LEARN_LLM\\LlamaIndex\\data").load_data()# initialize client, setting path to save datadb = chromadb.PersistentClient(path="D:\\GitHub\\LEARN_LLM\\LlamaIndex\\vector_store\\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("什么是变装指示?")print(response)2. 追想本文咱们学习了如安在 LlamaIndex 中使用自界说的向量数据库,并详备先容了其完毕规范。再追想一下,在 LlamaIndex 中使用自界说的向量数据库,最主要的是创建 LlamaIndex 的 VectorStore,然后将 VectorStore 封装到 StorageContext 中,泰国按摩群终末将 StorageContext 传入 VectorStoreIndex 的 from_documents 函数中。
3. 参考· https://docs.llamaindex.ai/en/stable/understanding/storing/storing/
如若以为本文对你有匡助,遮蔽点个赞和见谅呗 ~~~点击上方公众号,见谅↑↑↑
· 专家好,我是 同学小张,畴昔共享AI学问和实战案例
· 接待 点赞 + 见谅 👏,执续学习柬埔寨金边华群学校,执续干货输出。
本站仅提供存储劳动,统统实质均由用户发布,如发现存害或侵权实质,请点击举报。