Database / ChromaDB Interview Questions
What distance metrics does ChromaDB support and how do you choose between them?
ChromaDB uses a distance metric to measure how similar two vectors are during nearest-neighbour search. The metric is set at collection creation time and cannot be changed afterward. Choosing the wrong metric for your embedding model can significantly degrade search quality.
| Metric | hnsw:space value | Formula | Best for |
|---|---|---|---|
| L2 (Euclidean) | l2 (default) | √Σ(aáµ¢−báµ¢)² | When vector magnitude matters; general purpose |
| Cosine similarity | cosine | 1 − (a·b)/(-) | Text embeddings focuses on direction not magnitude |
| Inner Product | ip | −(a·b) | When embeddings are pre-normalised to unit length |
import chromadb
# Set metric at collection creation cannot change later!
collection_cosine = client.create_collection(
name="text_cosine",
metadata={"hnsw:space": "cosine"}, # recommended for text
)
collection_l2 = client.create_collection(
name="general_l2",
metadata={"hnsw:space": "l2"}, # default if not specified
)
collection_ip = client.create_collection(
name="normalised_ip",
metadata={"hnsw:space": "ip"}, # use when vectors are unit-normalised
)
# Query returns "distances" field interpretation depends on metric:
# cosine: 0 = identical, 2 = opposite (lower = more similar)
# l2: 0 = identical, larger = more different (lower = more similar)
# ip: more negative = more similar (with normalised vectors)Rule of thumb: most popular text embedding models (OpenAI, Sentence Transformers) are optimised for cosine similarity. Use "hnsw:space": "cosine" for text RAG applications. L2 is the default but is less optimal for text embeddings that vary in magnitude.
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...
