Search Tutorials
--Ads--Vector Store Options: FAISS, Chroma, pgvector, Qdrant and More
A tour of the popular vector stores with working code for each.
So far we have stored vectors in a NumPy matrix. That works for tens of thousands of chunks, but production systems need persistence, fast approximate search over millions of vectors, metadata filtering, updates and deletes. That is what vector stores provide. This lesson tours the main options with working code for four of them: FAISS, Chroma, pgvector and Qdrant.
Categories of vector stores
| Category | Examples | Good for |
|---|---|---|
| Search libraries | FAISS, hnswlib, Annoy, ScaNN | Fast in-process search; you handle storage and metadata |
| Embedded databases | Chroma, LanceDB, Qdrant local mode | Prototypes, desktop apps, single-server deployments |
| Extensions of existing databases | pgvector (PostgreSQL), Elasticsearch / OpenSearch, MongoDB Atlas, Redis | Teams that already run that database |
| Dedicated vector databases | Qdrant, Weaviate, Milvus, Vespa | Large scale, heavy filtering, hybrid search |
| Fully managed services | Pinecone, and the cloud versions of the above | No infrastructure to operate |
All examples below use the same data: chunks with a little metadata, embedded with embed() from rag_helpers.py.
from rag_helpers import embed
chunks = [
{"id": "leave-0", "text": "Employees get 18 days of paid leave in their first year.", "department": "hr"},
{"id": "leave-1", "text": "Up to 5 unused leave days can be carried over.", "department": "hr"},
{"id": "exp-0", "text": "Expense claims must be submitted within 30 days.", "department": "finance"},
{"id": "it-0", "text": "Laptops must use full-disk encryption.", "department": "it"},
]
vectors = embed([c["text"] for c in chunks]) # shape (4, 384), normalised
query = embed("How much holiday do I get?", query=True)[0]
FAISS
FAISS, from Meta AI, is a library for fast similarity search. It is extremely fast and supports every index type discussed in the next lesson, but it stores only vectors and integer IDs; you keep the text and metadata yourself.
pip install faiss-cpu
import faiss
index = faiss.IndexFlatIP(vectors.shape[1]) # exact search, inner product (= cosine here)
index.add(vectors)
scores, ids = index.search(query.reshape(1, -1), 2)
for score, i in zip(scores[0], ids[0]):
print(f"{score:.3f} {chunks[i]['text']}")
faiss.write_index(index, "policies.faiss") # save; faiss.read_index() to load
Chroma
Chroma is an open-source embedded database that stores vectors, documents and metadata together, with filtering. It is the quickest way to get a persistent store running.
pip install chromadb
import chromadb
client = chromadb.PersistentClient(path="chroma_db")
collection = client.get_or_create_collection("policies")
collection.upsert(
ids=[c["id"] for c in chunks],
documents=[c["text"] for c in chunks],
embeddings=vectors.tolist(),
metadatas=[{"department": c["department"]} for c in chunks],
)
result = collection.query(query_embeddings=[query.tolist()], n_results=2,
where={"department": "hr"})
for doc, distance in zip(result["documents"][0], result["distances"][0]):
print(f"{distance:.3f} {doc}")
Chroma's default distance is squared Euclidean (lower is better). For normalised vectors it ranks results exactly like cosine similarity. If you omit embeddings, Chroma embeds the documents itself with a small default model; passing your own vectors keeps you in control of the model.
pgvector (PostgreSQL)
If your application already uses PostgreSQL, pgvector adds a vector column type and approximate indexes. You get transactions, joins, backups and SQL filtering for free.
pip install "psycopg[binary]" pgvector
import psycopg
from pgvector.psycopg import register_vector
conn = psycopg.connect("postgresql://localhost/ragdb", autocommit=True)
conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
register_vector(conn)
conn.execute("""
CREATE TABLE IF NOT EXISTS chunks (
id text PRIMARY KEY,
text text NOT NULL,
department text,
embedding vector(384)
)""")
conn.execute("CREATE INDEX IF NOT EXISTS chunks_hnsw ON chunks USING hnsw (embedding vector_cosine_ops)")
with conn.cursor() as cur:
for c, v in zip(chunks, vectors):
cur.execute(
"INSERT INTO chunks (id, text, department, embedding) VALUES (%s, %s, %s, %s) "
"ON CONFLICT (id) DO UPDATE SET text = EXCLUDED.text, embedding = EXCLUDED.embedding",
(c["id"], c["text"], c["department"], v),
)
rows = conn.execute(
"SELECT text, 1 - (embedding <=> %s) AS similarity FROM chunks "
"WHERE department = %s ORDER BY embedding <=> %s LIMIT 2",
(query, "hr", query),
).fetchall()
for text, similarity in rows:
print(f"{similarity:.3f} {text}")
The <=> operator is cosine distance; <#> is negative inner product and <-> is Euclidean distance. Use the index operator class that matches the operator in your queries.
Qdrant
Qdrant is an open-source vector database written in Rust, with rich filtering, hybrid search and quantization. The Python client has a local mode that runs without a server, which is handy for learning; the same code works against a Qdrant server or Qdrant Cloud.
pip install qdrant-client
from qdrant_client import QdrantClient, models
client = QdrantClient(path="qdrant_db") # or QdrantClient(url="http://localhost:6333")
if not client.collection_exists("policies"):
client.create_collection(
"policies",
vectors_config=models.VectorParams(size=384, distance=models.Distance.COSINE),
)
client.upsert("policies", points=[
models.PointStruct(id=i, vector=v.tolist(),
payload={"chunk_id": c["id"], "text": c["text"], "department": c["department"]})
for i, (c, v) in enumerate(zip(chunks, vectors))
])
hits = client.query_points(
"policies",
query=query.tolist(),
limit=2,
query_filter=models.Filter(must=[
models.FieldCondition(key="department", match=models.MatchValue(value="hr")),
]),
).points
for hit in hits:
print(f"{hit.score:.3f} {hit.payload['text']}")
Qdrant point IDs must be unsigned integers or UUIDs, so the string chunk ID is kept in the payload.
Other popular options
- Weaviate: open-source, with built-in hybrid search and modules that call embedding models for you.
- Milvus: open-source and built for billions of vectors, with many index types including GPU indexes.
- Pinecone: a fully managed, serverless vector database.
- Elasticsearch and OpenSearch: mature full-text search engines with vector fields; strong choices when keyword search matters as much as vectors.
- LanceDB: an embedded database on a columnar file format, good for multimodal data and data on object storage.
Key takeaways
- Vector stores range from libraries (FAISS) to embedded databases (Chroma), database extensions (pgvector) and dedicated servers (Qdrant, Weaviate, Milvus).
- The core operations are the same everywhere: upsert vectors with IDs and metadata, then query with a vector, a limit and a filter.
- Make sure the index distance metric matches how your vectors were trained (cosine for most text models).