Database / ChromaDB Interview Questions
How do you query a ChromaDB collection for similar documents?
The primary query method is collection.query(). You pass either query_texts (raw strings that ChromaDB embeds automatically) or query_embeddings (pre-computed vectors). ChromaDB returns the n_results nearest neighbours for each query.
import chromadb
client = chromadb.Client()
collection = client.create_collection("knowledge_base")
collection.add(
documents=[
"Python is great for data science and machine learning.",
"JavaScript is used for web development.",
"ChromaDB stores and retrieves vector embeddings.",
"Docker containers package applications with dependencies.",
],
ids=["d1", "d2", "d3", "d4"],
)
# Basic query — returns top 2 most similar documents
results = collection.query(
query_texts=["vector database for AI"],
n_results=2,
)
print(results["documents"]) # [[most_similar, second_most_similar]]
print(results["ids"]) # [["d3", "d1"]]
print(results["distances"]) # [[0.18, 0.74]] — lower = more similar
# Query multiple texts at once (batch query)
results = collection.query(
query_texts=["machine learning", "web frameworks"],
n_results=2,
)
# results["documents"][0] = top 2 for "machine learning"
# results["documents"][1] = top 2 for "web frameworks"
# Control what is returned with include=
results = collection.query(
query_texts=["Python programming"],
n_results=3,
include=["documents", "metadatas", "distances", "embeddings"],
)
# Default include: ["documents", "metadatas", "distances"]
# "embeddings" must be explicitly requested — adds response size| Field | Type | Description |
|---|---|---|
| ids | list[list[str]] | IDs of matching documents, outer list = per query |
| documents | list[list[str]] | Original text of matching documents |
| metadatas | list[list[dict]] | Metadata dicts of matching documents |
| distances | list[list[float]] | Similarity distances (lower = more similar for l2/cosine) |
| embeddings | list[list[list[float]]] | Raw vectors — only if include=['embeddings'] |
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...
