在现代AI技术中,如何高效地索引和检索数据对象是一个关键问题。本文将介绍如何使用 ObjectIndex 来构建灵活的对象索引,并提供相关的示例代码。通过使用 ObjectIndex,我们可以索引任意的 Python 对象,从而实现多种应用场景,如工具对象的索引、数据库表模式对象的索引等。
构建 ObjectIndex
要构建一个 ObjectIndex,我们需要一个索引以及另一个抽象概念,即 ObjectNodeMapping。这个映射提供了在节点和关联对象之间转换的方法。此外,我们可以使用 from_objects() 方法方便地从一组对象构建 ObjectIndex。
from llama_index.core import Settings
Settings.embed_model = "local"
from llama_index.core import VectorStoreIndex
from llama_index.core.objects import ObjectIndex, SimpleObjectNodeMapping
# 一些任意的对象
obj1 = {"input": "Hey, how's it going"}
obj2 = ["a", "b", "c", "d"]
obj3 = "llamaindex is an awesome library!"
arbitrary_objects = [obj1, obj2, obj3]
# 对象节点映射
obj_node_mapping = SimpleObjectNodeMapping.from_objects(arbitrary_objects)
nodes = obj_node_mapping.to_nodes(arbitrary_objects)
# 对象索引
object_index = ObjectIndex(
index=VectorStoreIndex(nodes=nodes),
object_node_mapping=obj_node_mapping,
)
# 使用 from_objects 方法构建对象索引
object_index = ObjectIndex.from_objects(
arbitrary_objects, index_cls=VectorStoreIndex
)
使用 ObjectIndex 进行检索
构建好 ObjectIndex 后,我们可以将其用作检索器,以便从索引对象中进行检索。
object_retriever = object_index.as_retriever(similarity_top_k=1)
results = object_retriever.retrieve("llamaindex")
print(results)
# ['llamaindex is an awesome library!']
使用存储集成(例如 Chroma)
ObjectIndex 支持与任何现有的存储后端集成,下面是使用 Chroma 作为示例的设置方法。
!pip install llama-index-vector-stores-chroma
from llama_index.core import StorageContext, VectorStoreIndex
from llama_index.vector_stores.chroma import ChromaVectorStore
import chromadb
db = chromadb.PersistentClient(path="./chroma_db")
chroma_collection = db.get_or_create_collection("quickstart2")
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
object_index = ObjectIndex.from_objects(
arbitrary_objects,
index_cls=VectorStoreIndex,
storage_context=storage_context,
)
可能遇到的错误
- 文件路径错误:在使用 Chroma 时,如果提供的路径不存在,会引发
FileNotFoundError。确保路径正确且存在。
db = chromadb.PersistentClient(path="./chroma_db2") # 错误路径示例
# 错误: FileNotFoundError: [Errno 2] No such file or directory: './chroma_db2'
- 对象序列化错误:当尝试持久化对象映射时,如果对象不可序列化,将会引发
NotImplementedError或UserWarning。
# 尝试直接持久化对象映射会引发错误
object_mapping.persist()
# 错误: NotImplementedError: Subclasses should implement this!
# 尝试持久化对象索引会引发警告
object_index.persist()
# 警告: UserWarning: Unable to persist ObjectNodeMapping. You will need to reconstruct the same object node mapping to build this ObjectIndex
如果你觉得这篇文章对你有帮助,请点赞,关注我的博客,谢谢!
参考资料:
- LlamaIndex 文档: LlamaIndex Documentation
- Chroma 文档: Chroma Documentation

1435

被折叠的 条评论
为什么被折叠?



