How to create a ChromaDB collection
Quick answer
To create a
ChromaDB collection, use the chromadb.Client from the chromadb Python package and call client.create_collection(name="your_collection_name"). This initializes a new collection where you can add and query vectors.PREREQUISITES
Python 3.8+pip install chromadbBasic knowledge of Python
Setup
Install the chromadb Python package using pip and import the client. No API key is required for local usage.
pip install chromadb Step by step
This example shows how to create a ChromaDB collection named my_collection and verify its creation.
import chromadb
# Initialize the Chroma client
client = chromadb.Client()
# Create a new collection
collection = client.create_collection(name="my_collection")
# Print collection info
print(f"Collection created with name: {collection.name}")
# List all collections to verify
collections = client.list_collections()
print("Existing collections:")
for col in collections:
print(f"- {col.name}") output
Collection created with name: my_collection Existing collections: - my_collection
Common variations
- You can specify metadata when creating a collection using the
metadataparameter. - Use
client.get_collection(name="my_collection")to retrieve an existing collection. - ChromaDB supports async usage with
asyncioif you use the async client variant.
import chromadb
client = chromadb.Client()
# Create collection with metadata
collection = client.create_collection(
name="my_collection_with_meta",
metadata={"description": "Test collection"}
)
print(collection.metadata)
# Retrieve existing collection
existing = client.get_collection(name="my_collection_with_meta")
print(f"Retrieved collection: {existing.name}") output
{'description': 'Test collection'}
Retrieved collection: my_collection_with_meta Troubleshooting
- If you get an error like
CollectionAlreadyExistsError, useget_collectioninstead ofcreate_collection. - Ensure the
chromadbpackage is up to date to avoid compatibility issues. - For persistent storage, configure ChromaDB with a persistent client instead of the default in-memory client.
Key Takeaways
- Use
chromadb.Client().create_collection(name)to create a new collection. - Collections can include optional metadata for better organization.
- Use
get_collectionto avoid errors if the collection already exists. - Install
chromadbvia pip for easy Python integration. - Check your client configuration for persistence if needed.