Skip to content

Build semantic search with embeddings in 40 lines of Python

Turn text into vectors, compare them with cosine similarity, and search by meaning instead of keywords.

NZNarjis Zekhnini12 Oct 20263 min readDrafted with Inky · reviewed by Narjis

Keyword search fails when users don't use your words. Ask "how do I get my money back" and a page titled "Refund policy" might never match. Embeddings fix this by representing text as vectors whose distance reflects meaning.

What an embedding is

An embedding model maps a piece of text to a list of numbers — often a few hundred to a few thousand. Texts with similar meaning end up close together in that space.

Step 1: embed your documents

# pip install sentence-transformers numpy
import numpy as np
from sentence_transformers import SentenceTransformer
 
model = SentenceTransformer("all-MiniLM-L6-v2")  # small, runs on a laptop
 
docs = [
    "Refund policy: you can return items within 30 days.",
    "Shipping takes 3 to 5 business days in Europe.",
    "Reset your password from the account settings page.",
    "We accept card payments and bank transfers.",
]
doc_vecs = model.encode(docs, normalize_embeddings=True)  # shape (4, 384)

Step 2: search by cosine similarity

With normalised vectors, cosine similarity is just a dot product.

def search(query, k=2):
    q = model.encode([query], normalize_embeddings=True)[0]
    scores = doc_vecs @ q                 # (4,)
    best = np.argsort(scores)[::-1][:k]
    return [(round(float(scores[i]), 3), docs[i]) for i in best]
 
print(search("how do I get my money back?"))

The refund document should come first, even though it shares almost no words with the query.

Step 3: scale it up

  • Chunk long documents into passages of a few hundred words, so each vector represents one idea.
  • Store vectors in a vector index once you have more than a few thousand: pgvector (Postgres), FAISS, or a hosted vector database.
  • Combine with keywords. Hybrid search (keyword + embedding) handles product codes and names better than either alone.
  • Use the same model for documents and queries, and re-embed everything if you switch models.

Where this leads

Semantic search is the retrieval half of RAG: find the most relevant passages, then give them to a language model to write the answer. Get retrieval right and the rest gets much easier.

Takeaways

  • Embeddings turn meaning into geometry.
  • Normalise vectors and cosine similarity becomes a dot product.
  • Chunking and hybrid search matter more than the choice of model.

Keep reading

Get the next tutorial by email

One email a week. No spam.

Build semantic search with embeddings in 40 lines of Python · Tokenfield