DEV Community

Cover image for Search by Meaning, Not Words: Embeddings Explained in 30 Lines of Python
Muiduzzaman Lipu for Refactorly

Posted on

Search by Meaning, Not Words: Embeddings Explained in 30 Lines of Python

A user types "How do I cancel my plan?" Your help page says "To unsubscribe, open Billing and click End subscription."

Same meaning, zero shared words, so keyword search finds nothing. In this post we fix that with embeddings, the idea behind semantic search and RAG. It takes about 30 lines of plain Python (no libraries) and a free model running locally with Ollama.

Video version:

Keyword search compares spelling

def keyword_search(query):
    words = set(query.lower().replace("?", "").split())
    return max(DOCS, key=lambda d: len(words & set(d.lower().replace(".", "").replace(",", "").split())))
Enter fullscreen mode Exit fullscreen mode

For each of my four test questions below, the correct help article shared no words at all with the query. Keyword search has nothing to go on.

What's an embedding?

An embedding model turns text into a list of numbers (a vector). nomic-embed-text returns 768 of them. Texts with similar meaning get vectors that point in similar directions.

>>> v = embed(["cat", "kitten", "car"])
>>> v[0][:4]
[0.0317, 0.0623, -0.1354, -0.0382, ...]
>>> cosine(v[0], v[1])   # cat vs kitten
0.836
>>> cosine(v[0], v[2])   # cat vs car
0.558
Enter fullscreen mode Exit fullscreen mode

"cat" and "car" are one letter apart but much less similar than "cat" and "kitten". The model captures meaning, not spelling.

Step 1: get embeddings (free, local)

ollama pull nomic-embed-text
Enter fullscreen mode Exit fullscreen mode
import json, math, urllib.request

def embed(texts):
    req = urllib.request.Request(
        "http://localhost:11434/api/embed",
        data=json.dumps({"model": "nomic-embed-text", "input": texts}).encode(),
        headers={"Content-Type": "application/json"},
    )
    return json.load(urllib.request.urlopen(req))["embeddings"]
Enter fullscreen mode Exit fullscreen mode

One request to Ollama's local API returns one vector per input text. No API key, no extra packages, and the data never leaves your machine. (nomic-embed-text is Apache-2.0 licensed.)

Step 2: cosine similarity

def cosine(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
Enter fullscreen mode Exit fullscreen mode

The dot product divided by both vectors' lengths is the cosine of the angle between them. 1.0 means same direction (same meaning); values near 0 mean unrelated. In real code you'd use NumPy, but this is the whole idea.

Step 3: semantic search

DOCS = [
    "To unsubscribe, open Billing and click End subscription.",
    "You can change your password in Settings, under Security.",
    "Invoices are emailed on the first day of every month.",
    "Export all your data as a CSV file from the Account page.",
    "Our support team replies within 24 hours on weekdays.",
]

doc_vectors = embed(DOCS)          # once, then store them

def semantic_search(query):
    q = embed([query])[0]
    scores = [(cosine(q, v), d) for v, d in zip(doc_vectors, DOCS)]
    return sorted(scores, reverse=True)
Enter fullscreen mode Exit fullscreen mode

Embed the documents once and store the vectors. For each search, embed the query and rank documents by similarity.

Results

Query Top result Score
How do I cancel my plan? To unsubscribe, open Billing… ✅ 0.596
I forgot my login You can change your password… ✅ 0.488
when do I get my bill Invoices are emailed… ✅ 0.591
can I download everything I uploaded Export all your data as a CSV… ✅ 0.511

4 out of 4, with zero shared words between each query and its answer.

Tip: nomic's task prefixes

The nomic-embed-text model card recommends prefixing inputs with search_document: (for documents) and search_query: (for queries). With prefixes, the ranking stayed the same in my test and the top scores mostly went up. For example, "cancel my plan" went from 0.596 to 0.656, and "bill" from 0.591 to 0.718. Other embedding models have their own conventions, so check the model card.

Where this goes next: RAG

This is the retrieval step of RAG (retrieval-augmented generation): find the most relevant chunks of your docs, then paste them into an LLM's prompt so it answers from your content. For real apps:

  • Chunk long documents (a few paragraphs each) before embedding.
  • Store vectors in a database: pgvector for Postgres, a SQLite vector extension, Chroma, and others.
  • Use the same model for documents and queries. Vectors from different models aren't comparable.

Recap

  • Keyword search compares spelling; embeddings compare meaning.
  • An embedding is a vector (768 numbers for nomic-embed-text).
  • Cosine similarity: 1 = same meaning.
  • Embed docs once, embed each query, sort by score.
  • Free and local: ollama pull nomic-embed-text.

Should I build a full RAG chatbot on top of this next? 👇


I post one tested coding tip every day on YouTube at Refactorly. The 30-second version of this one is here.

Top comments (0)