Módulo 4: ChromaDB Setup y Configuración

Cápsula 02: ChromaDB Installation y Setup

🎯 Objetivo de la cápsula

Instalar ChromaDB correctamente, entender client modes (ephemeral, persistent, client-server), y crear tu primera collection funcional.

Al finalizar esta cápsula:

  • ✅ ChromaDB instalado y funcionando
  • ✅ Entenderás client modes y cuándo usar cada uno
  • ✅ Primera collection creada (hello world)
  • ✅ Verificación de instalación exitosa

Tiempo estimado: 12-15 minutos


📦 Installation

Step 1: Instalar ChromaDB

# Opción A: En virtual environment (recomendado)
python -m venv venv
source venv/bin/activate  # Mac/Linux
# venv\Scripts\activate   # Windows

pip install chromadb

# Opción B: Global (no recomendado)
pip install chromadb

Versión recomendada: 0.4.22+ (latest stable)

Step 2: Verificar instalación

import chromadb

print(f"ChromaDB version: {chromadb.__version__}")
# Expected output: ChromaDB version: 0.4.22 (o superior)

Si funciona → ✅ Installation exitosa

Troubleshooting común

Error 1: "No module named 'chromadb'"

# Fix: Asegúrate de que virtual env está activado
which python  # Debe apuntar a venv/bin/python
pip install chromadb

Error 2: "ImportError: DLL load failed" (Windows)

# Fix: Instalar Microsoft Visual C++ Redistributable
# https://aka.ms/vs/17/release/vc_redist.x64.exe

Error 3: Dependency conflicts

# Fix: Crear virtual environment limpio
rm -rf venv
python -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install chromadb

🔧 Client Modes

Mode 1: Ephemeral Client (In-Memory)

Uso: Testing, prototyping rápido

import chromadb

# Crear client in-memory
client = chromadb.Client()

# Data se pierde al terminar proceso
collection = client.create_collection("test")
collection.add(documents=["hello"], ids=["1"])

print(collection.count())  # Output: 1

# Al cerrar Python → Data desaparece

Ventajas:

  • ✅ Setup instantáneo (no config)
  • ✅ Rápido (todo en RAM)
  • ✅ Perfecto para unit tests

Desventajas:

  • ❌ Data no persiste
  • ❌ No compartible entre procesos

Cuándo usar: Unit tests, experimentación rápida.

Mode 2: Persistent Client (Disk Storage)

Uso: Desarrollo, producción local

import chromadb

# Crear client con persistencia
client = chromadb.PersistentClient(path="./chroma_db")

# Data persiste en disco
collection = client.create_collection("docs")
collection.add(documents=["hello"], ids=["1"])

# Cerrar y reabrir Python
# Data sigue disponible
client2 = chromadb.PersistentClient(path="./chroma_db")
collection2 = client2.get_collection("docs")
print(collection2.count())  # Output: 1 (persistió!)

Ventajas:

  • ✅ Data persiste
  • ✅ Backups simples (copiar carpeta)
  • ✅ Production-ready (single machine)

Desventajas:

  • ❌ Single process (no concurrent writes safe)
  • ❌ No distributed

Cuándo usar: Desarrollo, MVP, producción single-node.

Mode 3: Client-Server (HTTP)

Uso: Producción multi-proceso, remote access

# Terminal 1: Iniciar servidor
# chroma run --path ./chroma_db

# Terminal 2: Conectar como cliente
import chromadb

client = chromadb.HttpClient(host="localhost", port=8000)
collection = client.create_collection("docs")
collection.add(documents=["hello"], ids=["1"])

Ventajas:

  • ✅ Multi-proceso (concurrent queries safe)
  • ✅ Remote access (network)
  • ✅ Production-ready

Desventajas:

  • ❌ Requiere servidor corriendo
  • ❌ Setup más complejo

Cuándo usar: Producción multi-proceso, microservices.

Comparación

FeatureEphemeralPersistentClient-Server
Persistencia❌ No✅ Sí✅ Sí
Setup✅ Instant✅ Simple⚠️ Medium
Multi-proceso❌ No❌ No✅ Sí
Production❌ No⚠️ Single-node✅ Sí
Uso típicoTestingMVP/DevProduction

Recomendación para este módulo: Usar Persistent Client (balance entre simplicidad y persistencia).


🎯 Primera Collection - Hello World

Code completo

import chromadb

# 1. Crear client persistente
client = chromadb.PersistentClient(path="./chroma_db")

# 2. Crear collection
collection = client.create_collection(name="hello_world")

# 3. Agregar documentos
collection.add(
    documents=["Hello World", "Goodbye World"],
    metadatas=[{"type": "greeting"}, {"type": "farewell"}],
    ids=["1", "2"]
)

# 4. Query
results = collection.query(
    query_texts=["Hello"],
    n_results=2
)

# 5. Output
print(f"Documents: {results['documents']}")
print(f"Distances: {results['distances']}")
print(f"Metadatas: {results['metadatas']}")

Expected output:

Documents: [['Hello World', 'Goodbye World']]
Distances: [[0.0, 0.5]]
Metadatas: [[{'type': 'greeting'}, {'type': 'farewell'}]]

Explicación línea por línea

# 1. Client setup
client = chromadb.PersistentClient(path="./chroma_db")
# Crea carpeta ./chroma_db si no existe
# Usa DuckDB como storage backend

# 2. Collection
collection = client.create_collection(name="hello_world")
# HNSW index default (M=16, space=cosine)
# Si collection existe → error (usar get_or_create_collection)

# 3. Add documents
collection.add(
    documents=["Hello World", "Goodbye World"],
    # ChromaDB genera embeddings automáticamente (default model)
    
    metadatas=[{"type": "greeting"}, {"type": "farewell"}],
    # Metadata para filtering (optional)
    
    ids=["1", "2"]
    # IDs únicos requeridos
)

# 4. Query
results = collection.query(
    query_texts=["Hello"],
    # ChromaDB embeddings automáticamente
    
    n_results=2
    # Top-2 documentos más similares
)

# 5. Results structure
# {
#   'documents': [[...]], 
#   'distances': [[...]],  # Cosine distance (0=identical)
#   'metadatas': [[...]],
#   'ids': [[...]]
# }

✅ Verificación de Setup

Test 1: Basic functionality

import chromadb

def test_basic():
    client = chromadb.Client()  # Ephemeral para test
    collection = client.create_collection("test")
    
    # Add
    collection.add(documents=["doc1"], ids=["1"])
    
    # Query
    results = collection.query(query_texts=["doc1"], n_results=1)
    
    # Assert
    assert results['ids'][0][0] == "1", "Query failed"
    assert len(results['documents'][0]) == 1, "Wrong count"
    
    print("✅ Basic functionality: PASS")

test_basic()

Test 2: Persistence

import chromadb
import os

def test_persistence():
    path = "./test_chroma_db"
    
    # Session 1: Create and add
    client1 = chromadb.PersistentClient(path=path)
    collection1 = client1.get_or_create_collection("persist_test")
    collection1.add(documents=["persist"], ids=["1"])
    
    # Simulate restart
    del client1
    
    # Session 2: Retrieve
    client2 = chromadb.PersistentClient(path=path)
    collection2 = client2.get_collection("persist_test")
    count = collection2.count()
    
    # Cleanup
    import shutil
    shutil.rmtree(path)
    
    # Assert
    assert count == 1, "Persistence failed"
    print("✅ Persistence: PASS")

test_persistence()

Test 3: HNSW configuration

import chromadb

def test_hnsw_config():
    client = chromadb.Client()
    
    # Collection con HNSW custom
    collection = client.create_collection(
        name="hnsw_test",
        metadata={
            "hnsw:space": "cosine",
            "hnsw:M": 32
        }
    )
    
    # Verificar metadata
    metadata = collection.metadata
    assert metadata["hnsw:space"] == "cosine", "Config failed"
    
    print("✅ HNSW configuration: PASS")

test_hnsw_config()

Si los 3 tests pasan → ✅ Setup completo y funcional


🐛 Debugging Tips

Problema 1: "Collection already exists"

# ❌ Error
collection = client.create_collection("docs")
collection = client.create_collection("docs")  # Error!

# ✅ Fix: Usar get_or_create_collection
collection = client.get_or_create_collection("docs")

# O delete primero
client.delete_collection("docs")
collection = client.create_collection("docs")

Problema 2: "IDs must be unique"

# ❌ Error
collection.add(documents=["a", "b"], ids=["1", "1"])  # Duplicate ID

# ✅ Fix: IDs únicos
collection.add(documents=["a", "b"], ids=["1", "2"])

Problema 3: Carpeta de persistencia crece mucho

# Causa: No hacer cleanup de collections viejas

# ✅ Fix: Delete collections no usadas
client.delete_collection("old_collection")

# O resetear completamente
client.reset()  # ⚠️ Elimina TODAS las collections

✅ Checklist de comprensión

  • ¿Cuál es diferencia entre Ephemeral y Persistent client?

    • Ephemeral: In-memory, no persiste. Persistent: Disco, persiste.
  • ¿Cuándo usar Client-Server mode?

    • Multi-proceso, remote access, producción distributed.
  • ¿Cómo verificar que ChromaDB está funcionando?

    • Crear collection, add doc, query, verificar results.
  • ¿Qué hacer si "Collection already exists"?

    • Usar get_or_create_collection() o delete_collection() primero.

Si respondiste 4/4 → ✅ Listo para Cápsula 03 (HNSW Configuration)


🚀 Siguiente paso

Ya tienes ChromaDB funcionando! Ahora aprenderás a configurar HNSW para optimizar accuracy y latency.

Próxima cápsula: 03 - Collection Configuration (HNSW Parameters)

Aprenderás:

  • Configurar M, efConstruction, efSearch
  • Elegir distance metric (cosine vs L2)
  • Benchmark configuraciones (A/B testing)
  • Validar accuracy vs latency trade-off

Tiempo: 12-15 minutos
Siguiente: 03-collection-configuration.md