03
2025
07

国产 视频 【LlamaIndex教程】2. 存储模块:如安在 LlamaIndex 中使用自界说的向量数据库?(附代码)

发布日期:2025-07-03 15:39    点击次数:93

国产 视频 【LlamaIndex教程】2. 存储模块:如安在 LlamaIndex 中使用自界说的向量数据库?(附代码)

前边著作 两行代码就达成了文档的切分和向量化存储以及握久化存储。若是咱们思用自界说的向量化数据库呢?

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学问和实战案例

· 宽贷 点赞 + 眷注 👏国产 视频,握续学习,握续干货输出。 

本站仅提供存储劳动,所有履行均由用户发布,如发现存害或侵权履行,请点击举报。

相关资讯
热点资讯


Powered by 少妇 @2013-2022 RSS地图 HTML地图

Copyright Powered by站群系统 © 2013-2024