C.W.K.
Stream
Lesson 02 of 05 · published

Add, Query, and the Three Result Modes

~22 min · chroma, queries

Level 0Scout
0 XP0/41 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

The add contract

collection.add() takes parallel lists: ids, documents, metadatas, optionally embeddings. If you pass documents without embeddings, Chroma calls its default embedding function (which is not what you want in production — always control the model yourself).

The query contract

collection.query() takes query_embeddings (or query_texts) and returns the top-k nearest. The result includes ids, documents, metadatas, and distances. Distances are cosine DISTANCE, not similarity — 0 = identical, 2 = opposite.

Three result modes you should know

  • Default — returns ids, distances, and embeddings. Pass include=['documents','metadatas'] to get text/metadata back.
  • Embedding-only — useful for re-ranking with a separate model.
  • Where-filtered — pre-filter by metadata before ranking.

Code

Add chunks with explicit embeddings·python
vecs = model.encode([c['text'] for c in chunks], normalize_embeddings=True).tolist()

docs.add(
    ids       =[c['id']       for c in chunks],
    documents =[c['text']     for c in chunks],
    metadatas =[c['metadata'] for c in chunks],
    embeddings=vecs,
)
print(docs.count())
Query and convert distance to similarity·python
q_vec = model.encode(['how do I cancel?'], normalize_embeddings=True).tolist()

res = docs.query(
    query_embeddings=q_vec,
    n_results=5,
    include=['documents', 'metadatas', 'distances'],
)

for doc, meta, dist in zip(res['documents'][0], res['metadatas'][0], res['distances'][0]):
    similarity = 1 - dist
    print(f'{similarity:.3f}  {meta["source"]}  → {doc[:80]}')

External links

Exercise

Add 100 chunks to a collection with both documents and metadata. Query with 5 different phrasings of the same question. Print top-3 ids and distances for each. Note how stable the ranking is — that stability (or lack thereof) is your retrieval reliability signal.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.