New cohort: Agentic AI & LLM Engineering remote internship. Limited seats.Apply now
Lesson 08 of 21 25 minFree

Building Search Applications with Embeddings

Search by meaning, not keywords. Learn how embeddings, cosine similarity, chunking and vector databases power semantic search in AI apps.

By the end of this lesson you will be able to:

  • Explain the difference between keyword search and semantic search.
  • Describe what an embedding is and how cosine similarity compares them.
  • Split documents into chunks and build a simple search index.
  • Choose where to store vectors: in memory, a vector database or your existing database.

The problem with keyword search

Our study-buddy startup has hundreds of short video lessons and notes. A student types "how do plants make their own food?". A classic keyword search looks for those exact words, and misses the best lesson, titled "Photosynthesis explained", because it never says "make their own food".

Semantic search finds results by meaning. It knows "plants make food" and "photosynthesis" are about the same thing, even with zero words in common. The technology behind it is embeddings.

What is an embedding?

An embedding is a list of numbers (a vector) that represents the meaning of a piece of text. An embedding model is trained so that texts with similar meanings get vectors that point in similar directions. Real embeddings have hundreds or thousands of dimensions. Below we squeeze them into 3D so you can see the idea.

Notice how the clusters form on their own: science terms in one region, sports in another, food and code in theirs. A question about breakfast lands near Masala dosa even though it never says "dosa". That's semantic search.

Measuring "closeness": cosine similarity

To compare two embeddings we usually measure the angle between them with cosine similarity:

  • 1.0: same direction, same meaning.
  • around 0: unrelated.
  • negative: pointing in opposite directions (rare with text embeddings).

The formula is short: the dot product of the two vectors divided by the product of their lengths. You'll write it yourself in Exercise 1.

How a semantic search app works

  1. Chunk your content into pieces of a few hundred tokens, for example one paragraph or one video-transcript minute. Small chunks give precise matches, and a little overlap between chunks keeps sentences from being cut in half.
  2. Embed every chunk with an embedding model, such as OpenAI's text-embedding-3-small, Azure OpenAI's embedding deployments, or open models from Hugging Face.
  3. Store the vectors together with the original text and metadata (title, link, class, subject).
  4. At search time, embed the query with the same model and find the closest stored vectors.
  5. Show the top results, or pass them to an LLM to write an answer. That last step is RAG, coming in Lesson 15.
# On your machine, with an API key (same setup as Lesson 6):
emb = client.embeddings.create(model="text-embedding-3-small", input="How do plants make food?")
vector = emb.data[0].embedding     # a list of 1,536 numbers

Always use the same embedding model for your documents and your queries. Vectors from different models live in different "spaces" and can't be compared.

Where to keep the vectors

  • In memory (a Python list or NumPy array): perfect for a few thousand chunks and for learning.
  • A vector database or search service: Azure AI Search, Pinecone, Weaviate, Qdrant, Milvus or Chroma. These are built for millions of vectors, fast approximate search and metadata filters.
  • Your existing database: PostgreSQL with the pgvector extension, and many others, now store vectors too. Often the simplest choice in production.

Hybrid search works best. Many real systems combine keyword search (great for exact terms like "Section 80C" or a chemical formula) with semantic search (great for meaning), then re-rank the combined results.

Hands-on

Your task: implement cosine(): the dot product of a and b, divided by (length of a × length of b). The tiny 4-number "embeddings" are hand-made for practice. Expected: Best match: Photosynthesis explained.

import math

# Hand-made toy embeddings. Dimensions roughly mean: [biology, sport, food, coding]
docs = {
    "IPL 2024 final highlights":     [0.0, 0.95, 0.1, 0.0],
    "Photosynthesis explained":      [0.9, 0.0, 0.3, 0.0],
    "Healthy breakfast recipes":     [0.2, 0.0, 0.9, 0.0],
    "Python loops for beginners":    [0.0, 0.0, 0.0, 1.0],
}
query = [0.85, 0.0, 0.45, 0.0]   # "How do plants make their own food?"

def cosine(a, b):
    # TODO: dot product / (length of a * length of b)
    # length = math.sqrt(sum(x * x for x in v))
    return 0.0

ranked = sorted(docs.items(), key=lambda item: cosine(query, item[1]), reverse=True)
for title, vec in ranked:
    print(f"{cosine(query, vec):.3f}  {title}")
print("Best match:", ranked[0][0])
Show solution
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)))

Your task: split the text into chunks of size words, where each new chunk starts size - overlap words after the previous one, so neighbouring chunks share a few words. Expected first line: Chunks: 5.

text = ("Photosynthesis is how green plants make food. They use sunlight, water and carbon dioxide. "
        "Chlorophyll in the leaves captures light energy. The plant turns this energy into glucose. "
        "Oxygen is released into the air as a by-product. Animals and humans breathe this oxygen.")

def chunk(text, size=12, overlap=3):
    words = text.split()
    chunks = []
    step = size - overlap
    # TODO: for start in range(0, len(words), step): take words[start:start + size]
    #       join them with spaces and append to chunks; stop once a chunk reaches the end
    return chunks

parts = chunk(text)
print("Chunks:", len(parts))
for i, part in enumerate(parts, 1):
    print(f"{i}: {part}")
Show solution
    for start in range(0, len(words), step):
        chunks.append(" ".join(words[start:start + size]))
        if start + size >= len(words):
            break

Check your understanding

Why does semantic search find "Photosynthesis explained" for the query "how do plants make food"?

  1. It searches for synonyms in a dictionary
  2. Their embeddings point in similar directions because their meanings are similar
  3. The titles share many words
  4. The model memorised the website

Embeddings capture meaning, so related texts get nearby vectors even with no words in common.

You embedded your notes with model A. Which model must embed the search queries?

  1. Model A, the same one
  2. Any newer model
  3. A chat model
  4. It doesn't matter

Vectors are only comparable inside the same model's space.

Why add a small overlap between chunks?

  1. To make the index bigger
  2. To speed up search
  3. So ideas that cross a chunk boundary aren't cut in half
  4. Because embedding models require it

Overlap keeps context together at the edges of chunks, which improves match quality.

Users search for exact codes like "Section 80C" and also ask vague questions. What's the best design?

  1. Keyword search only
  2. Semantic search only
  3. Ask users to rephrase
  4. Hybrid search: keywords plus embeddings, then re-rank

Hybrid search gets the best of both: exact matching and meaning.

Key takeaways

  • Embeddings turn text into vectors where similar meanings sit close together.
  • Cosine similarity measures that closeness. 1.0 means the same direction.
  • Pipeline: chunk → embed → store → embed the query → nearest neighbours.
  • Store vectors in memory, in a vector database, or in Postgres with pgvector. Consider hybrid search.

Next: from words to pictures. Building image generation applications.

Your progress is saved in this browser.

Adapted from Lesson 8 of Microsoft's "Generative AI for Beginners" (MIT License), rewritten and extended by Aiprojects4U. View source