Velamuvi AIAcademy

Lesson 5 of 9 · Tools

Chroma

Get started with Chroma, the open-source vector database for Python: create a collection, add documents, query with filters, and update or delete records.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Install Chroma and choose between in-memory, on-disk and server modes
  • Create a collection with the right distance metric
  • Add, query, filter, update and delete records
  • Read Chroma's results, including turning distances into similarities

Why start with Chroma?

Chroma runs on your own computer, not in this page, so the Chroma code below is shown without a Run button. The outputs shown are from real runs. The parts you can run here work with the results Chroma returns.

Install it with:

pip install chromadb

Three ways to start

import chromadb

client = chromadb.Client()                                  # in memory: gone when the program ends
client = chromadb.PersistentClient(path="./chroma_data")    # saved in a folder on disk
client = chromadb.HttpClient(host="localhost", port=8000)   # talk to a Chroma server

Use the in-memory client for experiments and tests, the persistent client for a single app on one machine, and a server (started with chroma run --path ./chroma_data) when several programs need the same data.

Create a collection and add records

collection = client.get_or_create_collection(
    name="help_articles",
    configuration={"hnsw": {"space": "cosine"}},     # cosine distance, right for most text models
)

collection.add(
    ids=["a1", "a2", "a3"],
    embeddings=[[0.9, 0.1, 0.0], [0.1, 0.9, 0.0], [0.0, 0.2, 0.9]],
    documents=["Booking flights", "Hotel check-in", "Weather forecast"],
    metadatas=[
        {"category": "travel", "year": 2025},
        {"category": "hotels", "year": 2024},
        {"category": "weather", "year": 2025},
    ],
)
print(collection.count())          # 3

These tiny three-number vectors keep the example readable. In a real app, they come from your embedding model, and every vector in a collection must have the same length: Chroma rejects a vector of the wrong size with an error such as “Collection expecting embedding with dimension of 3, got 4”.

Query

results = collection.query(
    query_embeddings=[[0.8, 0.2, 0.0]],        # one query (you can send several)
    n_results=2,
    where={"year": {"$gte": 2025}},           # metadata filter (optional)
)
print(results["ids"], results["distances"])
# [['a1', 'a3']] [[0.009, 0.947]]   (distances rounded here)

With built-in embeddings, you can pass text instead: query_texts=["how do I book a flight?"]. You can also filter on the document text itself with where_document={"$contains": "flights"}, and combine metadata conditions with {"$and": [...]}.

Every field in the result is a list of lists, one inner list per query. With cosine space, Chroma returns distances: 0 means identical direction, and similarity = 1 − distance. Here is how to read a real result:

Try it yourselfPython
# This is the shape of the dictionary Chroma's collection.query() returns.
# Every field is a list of lists: one inner list per query you sent.
results = {
    "ids":       [["a1", "a4", "a3"]],
    "documents": [["Booking cheap flights", "Travel insurance", "Weather forecast"]],
    "metadatas": [[{"category": "travel"}, {"category": "travel"}, {"category": "weather"}]],
    "distances": [[0.009, 0.143, 0.947]],
}

# Take the results for the first (and only) query
ids = results["ids"][0]
docs = results["documents"][0]
metas = results["metadatas"][0]
dists = results["distances"][0]

for id, doc, meta, dist in zip(ids, docs, metas, dists):
    similarity = 1 - dist          # with cosine space: distance = 1 - cosine similarity
    print(f"{id}  {similarity:.2f}  {doc}  ({meta['category']})")

Update and delete

collection.upsert(                              # add new IDs, replace existing ones
    ids=["a1", "a4"],
    embeddings=[[0.9, 0.1, 0.0], [0.5, 0.5, 0.0]],
    documents=["Booking cheap flights", "Travel insurance"],
    metadatas=[{"category": "travel", "year": 2025}, {"category": "travel", "year": 2026}],
)
collection.delete(ids=["a2"])                   # or delete(where={"category": "hotels"})
print(collection.get(ids=["a1"])["documents"])   # ['Booking cheap flights']

Common mistakes

Practice exercise

Chroma returns distances, not similarities. Keep only close matches: distance of 0.3 or less.

Your solutionPython
results = {
    "ids":       [["a1", "a4", "a3"]],
    "documents": [["Booking cheap flights", "Travel insurance", "Weather forecast"]],
    "distances": [[0.009, 0.143, 0.947]],
}
max_distance = 0.3

# Print only the documents whose distance is at most max_distance,
# one per line. If none pass, print: No good match
Knowledge check

With a cosine collection, Chroma returns a distance of 0.12 for a result. What is its cosine similarity?

Summary

  • Chroma runs in memory, on disk (PersistentClient) or as a server (HttpClient).
  • Create a collection with the cosine metric, then add or upsert IDs, embeddings, documents and metadata.
  • query returns lists of lists of IDs, documents, metadata and distances (similarity = 1 − distance).
  • Use where and where_document to filter, upsert to update, and delete to remove.

Next: vector search inside a database you may already use, PostgreSQL with pgvector.

Finished reading? Tick it off to track your progress.