ChromaDB Python教程:最简单的向量数据库
Chroma是对新手最友好的向量数据库(28.9k星)。
ChromaDB Tutorial Python 2026: The Easiest Vector Database for Beginners
Chroma is an open-source vector database designed for simplicity (28,900 GitHub stars, Apache-2.0). Its killer feature: embeddings are handled for you. You give it text, it embeds and stores it, and you search with text. No separate embedding pipeline needed.
Step 1: Install
pip install chromadb
Step 2: Create a Collection and Add Documents
import chromadb
client = chromadb.Client() # in-memory; use PersistentClient for saving
collection = client.create_collection("docs")
collection.add(
documents=[
"The Eiffel Tower is in Paris.",
"Python is a programming language.",
"Paris is the capital of France."
],
ids=["doc1", "doc2", "doc3"]
)
Chroma auto-embeds the documents with its default embedding function (all-MiniLM-L6-v2, a 384-dim model). No API key needed.
Step 3: Search
results = collection.query(
query_texts=["What is the capital of France?"],
n_results=2
)
print(results["documents"])
# [['Paris is the capital of France.', 'The Eiffel Tower is in Paris.']]
That is semantic search - "capital of France" matches documents containing "Paris" even without the literal word.
Step 4: Persistent Storage
client = chromadb.PersistentClient(path="./chroma_data")
Step 5: Use Your Own Embeddings (for better quality)
from chromadb.utils.embedding_functions import OllamaEmbeddingFunction
ef = OllamaEmbeddingFunction(model_name="nomic-embed-text", url="http://localhost:11434/api/embeddings")
collection = client.create_collection("docs", embedding_function=ef)
The 3-Command RAG Pattern
- Add documents (auto-embedded)
- Query with a question (returns top-k chunks)
- Feed chunks + question to an LLM for the answer
FAQ
Chroma vs FAISS? FAISS is a library (no persistence, no metadata); Chroma is a database (persistence, metadata filters, simple API). Chroma for apps, FAISS for research.
Is Chroma production-ready? Yes for moderate scale (millions of vectors); it is the default vectorstore in LangChain tutorials. For very large scale, consider Qdrant or Milvus.
Does it need Docker? No - runs in-process or as a local server. Docker optional.
