Database / ChromaDB Interview Questions
How do you filter query results using metadata in ChromaDB?
ChromaDB supports a MongoDB-style where clause for filtering by metadata fields. Filters can be applied during query() (combines semantic search with filtering) or during get() (exact retrieval with filtering). Filters run before or alongside the ANN search.
import chromadb
client = chromadb.Client()
col = client.create_collection("articles")
col.add(
documents=["Python intro", "Python advanced", "JS basics", "Rust guide", "Go tutorial"],
metadatas=[
{"lang": "python", "level": "beginner", "year": 2022},
{"lang": "python", "level": "advanced", "year": 2023},
{"lang": "js", "level": "beginner", "year": 2023},
{"lang": "rust", "level": "beginner", "year": 2024},
{"lang": "go", "level": "intermediate", "year": 2024},
],
ids=["a1","a2","a3","a4","a5"],
)
# Equality filter
results = col.query(
query_texts=["programming tutorial"],
n_results=3,
where={"lang": "python"}, # shorthand for $eq
)
# Comparison operators
results = col.query(
query_texts=["tutorial"],
n_results=5,
where={"year": {"$gte": 2023}}, # year >= 2023
)
# Logical AND — all conditions must match
results = col.query(
query_texts=["guide"],
n_results=3,
where={"$and": [
{"lang": {"$in": ["python", "go"]}},
{"level": {"$ne": "advanced"}},
]},
)
# Logical OR
results = col.query(
query_texts=["code"],
n_results=3,
where={"$or": [
{"year": {"$eq": 2024}},
{"level": {"$eq": "beginner"}},
]},
)
# Filter on document text content (where_document)
results = col.query(
query_texts=["programming"],
n_results=5,
where_document={"$contains": "Python"}, # document text contains "Python"
)| Operator | Meaning | Example |
|---|---|---|
| $eq | Equal | {"lang": {"$eq": "python"}} or {"lang": "python"} |
| $ne | Not equal | {"level": {"$ne": "advanced"}} |
| $gt / $gte | Greater than / or equal | {"year": {"$gte": 2023}} |
| $lt / $lte | Less than / or equal | {"year": {"$lt": 2024}} |
| $in | Value in list | {"lang": {"$in": ["python", "go"]}} |
| $nin | Value not in list | {"lang": {"$nin": ["js"]}} |
| $and | All conditions true | {"$and": [{...}, {...}]} |
| $or | Any condition true | {"$or": [{...}, {...}]} |
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...
