Database / ChromaDB Interview Questions
How do you reset or clear a ChromaDB collection without deleting and recreating it?
ChromaDB does not have a direct clear() or truncate() method. The idiomatic way to reset a collection is to delete it and recreate it with the same parameters. For selective deletion, use delete() with ID lists or where filters.
import chromadb
client = chromadb.PersistentClient(path="./reset_demo")
# Setup
col = client.get_or_create_collection(
"my_col",
metadata={"hnsw:space": "cosine", "version": "1"},
)
col.add(
documents=[f"Document {i}" for i in range(100)],
ids=[str(i) for i in range(100)],
metadatas=[{"batch": i // 10} for i in range(100)],
)
print(col.count()) # 100
# --- Option 1: Reset (delete all + recreate) ---
def reset_collection(client, name: str, metadata: dict = None):
"""Delete and recreate a collection, preserving its configuration."""
saved_meta = {}
try:
saved_meta = client.get_collection(name).metadata or {}
except Exception:
pass
client.delete_collection(name)
return client.create_collection(
name=name,
metadata=metadata or saved_meta,
)
col = reset_collection(client, "my_col")
print(col.count()) # 0
# Re-add fresh data after reset
col.add(documents=["Fresh start"], ids=["new-1"])
# --- Option 2: Selective delete by filter ---
col2 = client.get_or_create_collection("selective")
col2.add(
documents=[f"Doc {i}" for i in range(20)],
ids=[str(i) for i in range(20)],
metadatas=[{"batch": i // 5} for i in range(20)],
)
# Delete only batch 0 (documents 0-4)
col2.delete(where={"batch": 0})
print(col2.count()) # 15 remaining
# Delete specific IDs
col2.delete(ids=["5","6","7"])
print(col2.count()) # 12 remaining
# Delete ALL via get + delete (when no useful metadata filter exists)
all_ids = col2.get(include=[])["ids"] # get all IDs
if all_ids:
col2.delete(ids=all_ids)
print(col2.count()) # 0| Method | When to use | Preserves schema? |
|---|---|---|
| delete_collection + create_collection | Full reset — cleanest approach | Yes (manual) |
| delete(where={...}) | Selective clear by metadata condition | Yes |
| delete(ids=[...]) | Remove specific known documents | Yes |
| get all IDs then delete | Clear all without metadata | Yes |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
