Tutorial
Embeddings and vector search, hands on
Embed documents, store them in Postgres with pgvector, index them and run similarity and hybrid search.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
An embedding is a list of numbers (a vector) that represents the meaning of a piece of text. Texts with similar meaning get vectors that point in similar directions, so “how do I undo a release?” lands near “rolling back a deployment” even though they share no words. Vector search is finding the stored vectors closest to a query vector.
In this tutorial you will store embeddings in Postgres with the pgvector extension, index them, run semantic searches, and then combine vector search with Postgres full-text search into hybrid search. Postgres is a good place to start: you probably already run it, your documents and their permissions can live in the same database, and pgvector handles millions of vectors comfortably.
1. Start Postgres with pgvector
The pgvector project publishes Docker images with the extension installed:
docker run -d --name pgvector \
-e POSTGRES_PASSWORD=postgres \
-p 5432:5432 \
pgvector/pgvector:pg18
If you use a managed Postgres (Neon, Supabase, RDS, Cloud SQL and others), pgvector is usually available; you enable it with CREATE EXTENSION vector.
Install the Python packages and pull a local embedding model:
pip install "psycopg[binary]" pgvector numpy ollama
ollama pull embeddinggemma
We use EmbeddingGemma through Ollama so you can run everything locally without an API key. The code does not hard-code the vector size; it reads it from the first embedding, so you can switch to a hosted embedding API later by changing one function.
2. Look at an embedding
Before building anything, look at what you are storing:
import numpy as np
import ollama
texts = ["How do I roll back a deployment?", "Undoing a bad release", "Office opening hours"]
vectors = np.array(ollama.embed(model="embeddinggemma", input=texts).embeddings)
print(vectors.shape) # (3, number_of_dimensions)
unit = vectors / np.linalg.norm(vectors, axis=1, keepdims=True)
print(np.round(unit @ unit.T, 2)) # cosine similarity between every pair
The similarity between the first two should be clearly higher than either’s similarity with the third. That is the whole trick. Note that the absolute numbers mean little on their own; what matters is the ranking.
3. Create the table and indexes
Create vectors.py. The first part connects, enables the extension and defines the schema:
# vectors.py
import os
import sys
from pathlib import Path
import numpy as np
import ollama
import psycopg
from pgvector.psycopg import register_vector
DSN = os.environ.get("DATABASE_URL", "postgresql://postgres:postgres@localhost:5432/postgres")
EMBED_MODEL = "embeddinggemma"
def embed(texts: list[str]) -> list[np.ndarray]:
return [np.array(v, dtype=np.float32) for v in ollama.embed(model=EMBED_MODEL, input=texts).embeddings]
def connect() -> psycopg.Connection:
conn = psycopg.connect(DSN, autocommit=True)
conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
register_vector(conn) # teach psycopg to send and receive numpy arrays as vectors
return conn
def create_schema(conn: psycopg.Connection, dimensions: int) -> None:
conn.execute(f"""
CREATE TABLE IF NOT EXISTS chunks (
id bigserial PRIMARY KEY,
source text NOT NULL,
content text NOT NULL,
embedding vector({dimensions}) NOT NULL,
tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED
)""")
conn.execute("CREATE INDEX IF NOT EXISTS chunks_embedding_idx ON chunks USING hnsw (embedding vector_cosine_ops)")
conn.execute("CREATE INDEX IF NOT EXISTS chunks_tsv_idx ON chunks USING gin (tsv)")
What the schema does:
vector(n)is pgvector’s column type. Every row must have exactlyndimensions.tsvis a generated full-text search column, kept up to date by Postgres, for the keyword half of hybrid search.- The HNSW index makes nearest-neighbour search fast on large tables.
vector_cosine_opstells it to optimise for cosine distance, which must match the operator you query with. - The GIN index does the same job for full-text search.
4. Ingest documents
Add an ingest function that splits Markdown files into paragraphs, embeds them in one batch and inserts them:
def ingest(conn: psycopg.Connection, folder: str) -> None:
paragraphs = [
(str(path), para.strip())
for path in sorted(Path(folder).glob("**/*.md"))
for para in path.read_text(encoding="utf-8").split("\n\n")
if len(para.strip()) > 40
]
vectors = embed([text for _, text in paragraphs])
create_schema(conn, dimensions=len(vectors[0]))
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO chunks (source, content, embedding) VALUES (%s, %s, %s)",
[(source, text, vec) for (source, text), vec in zip(paragraphs, vectors)],
)
print(f"stored {len(paragraphs)} chunks with {len(vectors[0])}-dimensional embeddings")
Paragraph splitting is the simplest chunking that respects document structure. The RAG fundamentals tutorial discusses better strategies. For a large corpus, embed in batches of a few hundred rather than all at once.
5. Semantic and hybrid search
Now the two queries. Semantic search orders by cosine distance, which pgvector writes as <=>; similarity is one minus the distance:
SEMANTIC = """
SELECT source, left(content, 80) AS preview, 1 - (embedding <=> %(q)s) AS similarity
FROM chunks
ORDER BY embedding <=> %(q)s
LIMIT 5
"""
Hybrid search runs a vector search and a keyword search, then merges the two rankings with reciprocal rank fusion (RRF). Each result scores 1 / (60 + rank) in each list it appears in, and the scores are added. RRF only uses ranks, so you never have to compare a cosine similarity with a full-text score:
HYBRID = """
WITH semantic AS (
SELECT id, row_number() OVER (ORDER BY embedding <=> %(q)s) AS rank
FROM chunks
ORDER BY embedding <=> %(q)s
LIMIT 20
),
keyword AS (
SELECT id, row_number() OVER (ORDER BY ts_rank_cd(tsv, query) DESC) AS rank
FROM chunks, websearch_to_tsquery('english', %(text)s) AS query
WHERE tsv @@ query
ORDER BY ts_rank_cd(tsv, query) DESC
LIMIT 20
)
SELECT c.source, left(c.content, 80) AS preview,
coalesce(1.0 / (60 + s.rank), 0) + coalesce(1.0 / (60 + k.rank), 0) AS score
FROM semantic s
FULL OUTER JOIN keyword k ON s.id = k.id
JOIN chunks c ON c.id = coalesce(s.id, k.id)
ORDER BY score DESC
LIMIT 5
"""
def search(conn: psycopg.Connection, question: str) -> None:
q = embed([question])[0]
for title, sql in (("semantic", SEMANTIC), ("hybrid", HYBRID)):
print(f"\n{title}:")
for source, preview, score in conn.execute(sql, {"q": q, "text": question}).fetchall():
print(f" {float(score):.4f} {source} {preview}")
if __name__ == "__main__":
with connect() as conn:
if sys.argv[1] == "ingest":
ingest(conn, sys.argv[2])
else:
search(conn, sys.argv[2])
Run it against a folder of Markdown documentation:
python vectors.py ingest docs
python vectors.py search "how do I undo a release"
python vectors.py search "error E1042"
Compare the two result lists for each query. For the natural-language question, semantic search usually does well on its own. For the error code, keyword search finds the exact string while vector search may return paragraphs that are merely about errors. Hybrid gives you both, which is why most production retrieval uses it.
6. Filter with ordinary SQL
Because the vectors live next to your data, filters are just WHERE clauses. If you add a team_id or visibility column, you can restrict results to what the current user may see:
SELECT source, content
FROM chunks
WHERE team_id = %(team)s
ORDER BY embedding <=> %(q)s
LIMIT 5;
With an approximate index, a selective filter can leave you with fewer results than you asked for, because the index returns its nearest candidates first and the filter removes some afterwards. pgvector 0.8 added iterative index scans for this (SET hnsw.iterative_scan = relaxed_order;), which keep scanning until enough rows pass the filter.
Pitfalls
Mixing embedding models. Vectors from different models are not comparable, even with the same number of dimensions. Store the model name with each row and re-embed everything when you switch.
Wrong operator for the index. An index built with vector_cosine_ops is used for <=> queries only. <-> (Euclidean) or <#> (negative inner product) will fall back to a full scan.
Re-running ingest. The example inserts every time it runs. In real code, store a content hash and upsert, so unchanged chunks are not duplicated or re-embedded.
Judging by eye. A few good-looking results prove little. Build a small set of questions with known answer documents and measure the hit rate, as described in the golden set workflow.
Reaching for a dedicated vector database too early. Systems like Qdrant earn their place at large scale or with demanding filtering; for most applications, Postgres with pgvector is enough and keeps your architecture simple.
Next steps
- Connect this retrieval to an answer step: the RAG pipeline in a day workflow.
- Measure retrieval quality with Evaluate RAG with a golden set.
- Review the concepts in RAG fundamentals.
- Decide whether Postgres is enough for your workload in pgvector vs Pinecone, Qdrant and Weaviate.
- Improve what you retrieve with RAG chunking strategies and hybrid search and reranking.
Covers
Check your understanding
Embeddings and vector search quiz
Embeddings, similarity measures, pgvector operators and indexes, and hybrid search in Postgres.
7 questions · pass mark 70%
Review
Related
- RAG fundamentals: retrieval before generation
What RAG is and how retrieval-augmented generation works, when it beats long context or fine-tuning, and a minimal working pipeline in about 80 lines of Python.
- RAG pipeline in a day with Postgres and pgvector
Ingest your documents, answer with citations and measure retrieval against 20 questions written first.
- Evaluate RAG answers with a golden dataset
Set up RAG evaluation with a golden dataset and promptfoo: score retrieval, correctness and grounding for every question, and fail CI when answer quality drops.
- Embedding
A vector representation of text or other data that places items with similar meaning close together, so they can be searched by similarity.
- Qdrant
Open-source vector database in Rust with payload filtering and hybrid search.