ChromaDB Python教程:最简单的向量数据库

2026-08-01 约 5 分钟阅读

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

  1. Add documents (auto-embedded)
  2. Query with a question (returns top-k chunks)
  3. 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.

相关文章
2026-06-29
高收益主线龙头策略——不花钱的数据,也能抓到龙头
2026-06-29
你笔记本里,藏着一个AI
2026-07-14
免费AI编程助手 2026 配置指南:VS Code 5分钟装 Continue、Copilot、Windsurf

💬 评论 (0)

暂无评论,来说两句吧~

登录后评论