在ChromaDB中使用集合 本教程将引导您完成创建、检查和删除集合,以及更改ChromaDB中的距离函数。 创建集合 我们首先初始化ChromaDB客户端,并创建一个名为 的集合。 检查集合 要检查一个集合,我们只需打印该集合对象。这将向我们展示集合的名称、ID和元数据。 修改集合 可以使用 method. In this case, we change the name of our collection from to 来修改集合。 统计集合中的项数 我们可以使用 method. Since we have not added any items to our collection yet, the count returns 来统计集合中的项数。
本教程将引导您完成创建、检查和删除集合,以及更改ChromaDB中的距离函数。
client = chromadb.Client() neo_collection = client.create_collection(name="neo")
我们首先初始化ChromaDB客户端,并创建一个名为neo的集合。
print(neo_collection)
要检查一个集合,我们只需打印该集合对象。这将向我们展示集合的名称、ID和元数据。
neo_collection.modify(name="mr_anderson") print(neo_collection)
可以使用modify method. In this case, we change the name of our collection from neo to mr_anderson来修改集合。
item_count = neo_collection.count() print(f"Count of items in collection: {item_count}")
我们可以使用count method. Since we have not added any items to our collection yet, the count returns 0来统计集合中的项数。
trinity_collection = client.get_or_create_collection( name="trinity", metadata={"hnsw:space": "cosine"} ) print(trinity_collection)
在ChromaDB中,距离函数决定了如何计算集合中两个项之间的“距离”或“差异”。这在执行诸如查询相似项等操作时至关重要。
ChromaDB的默认距离函数是"l2", which stands for Euclidean distance. It's a common measure of distance in a plane.
However, sometimes other measures of distance might be more appropriate, depending on the nature of the data in the collection.
In this tutorial, we use the get_or_create_collection method to either get an existing collection named trinity or create it if it doesn't exist. We set the distance function to "cosine". The Cosine distance is a measure of similarity between two vectors by taking the cosine of the angle between them. This can be useful in many domains including text analysis where high dimensionality and sparsity are common.
You can choose the distance function that best suits your needs when creating a collection. Other valid options for the distance function include "ip"(内积)。
请记住,距离函数的选择会显著影响查询结果,因此请谨慎选择!
try: client.delete_collection(name="mr_anderson") print("Mr. Anderson collection deleted.") except ValueError as e: print(f"Error: {e}")
我们尝试删除mr_anderson collection using the delete_collection method. Please note that delete_collection raises a ValueError if the collection does not exist. In our Python code, we handle this potential error using a try/except block. If the collection is successfully deleted, we print a success message. If the collection does not exist, we print the error message.
Please refer to the matrix_collections.py文件,以获取本教程中使用的完整Python代码。
免责声明:
本文档采用基于机器的 AI 翻译服务进行翻译。尽管我们力求准确,但请注意,自动翻译可能存在错误或不准确之处。应以原文语言版本的文档作为权威依据。如需获取关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。