← All posts

Tutorial

Semantic Search in Python With Embeddings (Step by Step)

Build semantic search in Python with embeddings and cosine similarity. Find notes by meaning, not keywords, using a free local model.

8 min read

Copy this article

Clipboard access is unavailable. Select the Markdown and copy it, then paste it into your chat.

Quick answer

Semantic search finds text by meaning instead of exact words. Search your notes for “how do I get a refund” and it can surface a note titled “returning an order”, even though the two share no keywords. You can build it in Python with embeddings and about thirty lines of code.

This tutorial uses a free local embedding model through Ollama, so there is no API key or hosted API fee. If Ollama is new to you, set it up first with Run a Local LLM with Ollama.

What is an embedding?

An embedding turns a piece of text into a list of numbers, called a vector. The model is trained so that texts with similar meaning end up with similar vectors. Once text is a vector, “how similar are these two sentences?” becomes a numerical comparison.

The usual measure is cosine similarity, which compares the direction of two vectors and ignores their length. Higher scores mean more aligned vectors, but a useful relevance threshold depends on the embedding model and your documents. A score is not a probability that the answer is correct.

Setup

Download an embedding model and install the two Python packages:

ollama pull nomic-embed-text
pip install numpy requests

nomic-embed-text is a small embedding model. Embedding models and chat models are different things, so you pull one for each. The endpoint is described in the Ollama embeddings guide. You need Python 3.9 or newer.

One quirk matters for search quality. According to the model card, this model expects a short task prefix on the text: search_document: before documents and search_query: before questions. The code below adds them. Other embedding models may not need prefixes, so check the card for whichever model you use.

Step 1: Turn text into vectors

Save everything below into one file called search.py, in order. First, a helper that sends a list of strings to Ollama and returns a matrix with one row per string:

import numpy as np
import requests

EMBED_URL = "http://localhost:11434/api/embed"
EMBED_MODEL = "nomic-embed-text"


def embed(texts: list[str]) -> np.ndarray:
    if not texts:
        return np.empty((0, 0), dtype=np.float32)
    response = requests.post(
        EMBED_URL,
        json={"model": EMBED_MODEL, "input": texts},
        timeout=120,
    )
    response.raise_for_status()
    vectors = np.array(response.json()["embeddings"], dtype=np.float32)
    # Scale every vector to length 1 so a dot product equals cosine similarity.
    if vectors.ndim != 2 or vectors.shape[0] != len(texts) or vectors.shape[1] == 0:
        raise ValueError("embedding response has the wrong shape")
    norms = np.linalg.norm(vectors, axis=1, keepdims=True)
    if not np.isfinite(vectors).all() or not np.isfinite(norms).all() or (norms <= 0).any():
        raise ValueError("embedding vectors must be finite and nonzero")
    return vectors / norms

Ollama’s /api/embed already returns unit-length vectors, so this step is a cheap safeguard. It also makes the key idea explicit: when every vector has length 1, cosine similarity is just a dot product.

Step 2: Embed your documents once

notes = [
    "Returning an order: print the label, box the item and drop it at any post office.",
    "Reset your password from the account page by choosing 'Forgot password'.",
    "Our office is closed on public holidays and reopens the next business day.",
    "Shipping usually takes three to five business days within Canada.",
    "To cancel a subscription, open Billing and choose 'Cancel plan'.",
]

note_vectors = embed([f"search_document: {note}" for note in notes])

You embed the documents once and reuse the result. Only the query needs a fresh embedding each time you search.

Step 3: Rank by similarity

def search(query: str, top_k: int = 3) -> list[tuple[float, str]]:
    query_vector = embed([f"search_query: {query}"])[0]
    scores = note_vectors @ query_vector  # cosine similarity for every note
    best = np.argsort(scores)[::-1][:top_k]  # highest scores first
    return [(float(scores[i]), notes[i]) for i in best]


for score, note in search("how do I get my money back for something I bought?"):
    print(f"{score:.3f}  {note}")

Run python search.py. With a good embedding model, the return instructions should land at or near the top, even though the query never says “return” or “order”. Exact scores differ from model to model, so focus on the ranking rather than the numbers. That is semantic search working.

The @ operator multiplies the matrix of note vectors by the query vector in one step, and np.argsort gives you the indexes of the best scores.

Tips for better results

  • Chunk long documents. Embedding a whole article blurs its meaning. Split it into paragraphs or sections of a few hundred words.
  • Keep one model per index. Vectors from different models cannot be compared, so if you change the model, re-embed everything.
  • Cache your vectors. Save the matrix with np.save("vectors.npy", note_vectors) so you do not recompute it every run.
  • Combine with keyword search when exact terms matter, such as product codes or names.

When you need a vector database

A NumPy array is a useful starting point for a small collection; memory and latency depend on vector dimensions and hardware. Once you have hundreds of thousands, or you need filtering and persistence, look at a vector database or an extension for the database you already use. Do not reach for one before you feel the pain.

FAQ

What is semantic search in Python?

Semantic search finds text by meaning instead of exact words. You turn text into embeddings, which are lists of numbers called vectors, and compare them with cosine similarity. This tutorial builds it in about thirty lines of code with a free local embedding model through Ollama, so there is no API key or hosted API fee.

How do you build semantic search with embeddings in Python?

Run ollama pull nomic-embed-text and pip install numpy requests, and use Python 3.9 or newer. Embed your documents once, embed each query when you search, and rank by the dot product of the unit-length vectors, which equals cosine similarity. The search.py script in this post shows each step.

Do embedding models need a prefix on the text?

According to the model card, nomic-embed-text expects search_document: before documents and search_query: before questions. The code in this post adds them. Other embedding models may not need prefixes, so check the card for whichever model you use.

Does a high cosine similarity score mean the result is correct?

No. Higher scores mean more aligned vectors, but a useful relevance threshold depends on the embedding model and your documents. A score is not a probability that the answer is correct. Exact scores differ from model to model, so focus on the ranking rather than the numbers.

A NumPy array is a useful starting point for a small collection, and memory and latency depend on vector dimensions and hardware. Once you have hundreds of thousands of vectors, or you need filtering and persistence, look at a vector database or an extension for the database you already use. Vectors from different models can’t be compared, so if you change the model, re-embed everything.

Where to go next

Search finds the right passages. The next step is to let a language model read them and answer your question, which is called retrieval-augmented generation. Build that in Chat With Your Own Notes: A Simple RAG App in Python.

  • #embeddings
  • #semantic-search
  • #python