pythonchromadb

ChromaDB: How to check if collection exists?


I want to create a script that recreates a chromadb collection - delete previous version and creates a new from scratch.

client.delete_collection(name=COLLECTION_NAME)
collection = client.create_collection(
    name=COLLECTION_NAME,
    embedding_function=embedding_func,
    metadata={"hnsw:space": "cosine"},
)

However, if the collection does not exist, I receive error:

 File "*/lib/python3.11/site-packages/chromadb/api/segment.py", line 347, in delete_collection
raise ValueError(f"Collection {name} does not exist.")

ValueError: Collection operations does not exist.

Is there any command to check if a collection exists? I haven't found any in documentation.


Solution

  • You can use the following function

        collection = client.get_or_create_collection(name="test")
    

    It either gets the collection or creates it