Database / ChromaDB Interview Questions
How do you add documents to a ChromaDB collection?
The collection.add() method inserts items into a collection. Each item requires a unique id. You can provide raw documents (strings) and let ChromaDB embed them, or supply pre-computed embeddings directly. Optional metadatas store filterable key-value pairs alongside each document.
import chromadb client = chromadb.Client() collection = client.create_collection("articles") # Basic add â ChromaDB embeds documents automatically collection.add( documents=[ "ChromaDB is an open-source vector database.", "Retrieval-augmented generation improves LLM accuracy.", "Python is a popular language for data science.", ], ids=["art-001", "art-002", "art-003"], ) # Add with metadata â enables filtered queries later collection.add( documents=[ "FastAPI is a modern Python web framework.", "React is a JavaScript library for building UIs.", ], metadatas=[ {"source": "docs", "category": "backend", "year": 2024}, {"source": "docs", "category": "frontend", "year": 2024}, ], ids=["art-004", "art-005"], ) # Add pre-computed embeddings (skip ChromaDB's embedding step) import numpy as np collection_custom = client.create_collection( "custom_embeddings", metadata={"hnsw:space": "cosine"}, ) collection_custom.add( embeddings=[ [0.1, 0.5, -0.3, 0.8], # must match embedding_function dimension [0.4, 0.2, 0.9, -0.1], ], documents=["Doc A", "Doc B"], # stored as-is for retrieval ids=["e-1", "e-2"], )
ID rules: IDs must be strings, must be unique within the collection, and must not be empty. Adding a duplicate ID raises a chromadb.errors.IDAlreadyExistsError.
More Related questions...