Velamuvi AIAcademy
Embeddings

Lesson 8 of 8 · Using Embeddings

Project: Semantic Search Engine

Build a semantic search engine for a help centre: index documents with embeddings, search by meaning, filter weak matches, evaluate and add a vector database.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Build a complete semantic search engine, from documents to results
  • Combine titles and text when indexing
  • Filter weak matches and handle “no result” gracefully
  • Evaluate the engine with test queries, and plan the upgrade to real tools

The goal

A help centre for a travel app has articles about flights, hotels, weather, accounts and health. Users type questions in their own words. The search engine must return the right article, even when the words differ, and admit when nothing fits.

You will use the see-inside model from earlier lessons as the embedding model. At the end, you will see exactly which lines change to use a real model.

The complete engine

Try it yourselfPython
import math

# A tiny, hand-made "embedding model". Each dimension is a topic.
# A real model learns thousands of dimensions from data; ours uses a word list
# so you can see exactly where the numbers come from.
TOPICS = ["travel", "food", "money", "tech", "health", "weather"]
LEXICON = {
    "flight": {"travel": 1}, "flights": {"travel": 1}, "airline": {"travel": 1},
    "plane": {"travel": 1}, "airport": {"travel": 1}, "trip": {"travel": 1},
    "holiday": {"travel": 1}, "hotel": {"travel": 1, "money": 0.3},
    "train": {"travel": 1}, "tickets": {"travel": 0.8, "money": 0.5},
    "recipe": {"food": 1}, "cook": {"food": 1}, "dinner": {"food": 1},
    "pasta": {"food": 1}, "rice": {"food": 1}, "curry": {"food": 1},
    "vegetarian": {"food": 1, "health": 0.3}, "restaurant": {"food": 1, "travel": 0.3},
    "cheap": {"money": 1}, "budget": {"money": 1}, "low-cost": {"money": 1},
    "price": {"money": 1}, "save": {"money": 1}, "salary": {"money": 1},
    "bank": {"money": 1}, "loan": {"money": 1}, "expensive": {"money": 1},
    "laptop": {"tech": 1}, "phone": {"tech": 1}, "app": {"tech": 1},
    "battery": {"tech": 1}, "wifi": {"tech": 1}, "password": {"tech": 1},
    "python": {"tech": 1}, "doctor": {"health": 1}, "sleep": {"health": 1},
    "exercise": {"health": 1}, "fever": {"health": 1}, "headache": {"health": 1},
    "diet": {"health": 1, "food": 0.5}, "rain": {"weather": 1},
    "sunny": {"weather": 1}, "forecast": {"weather": 1}, "storm": {"weather": 1},
    "umbrella": {"weather": 1}, "snow": {"weather": 1, "travel": 0.2},
}

def embed(text):
    vector = [0.0] * len(TOPICS)
    for word in text.lower().replace(",", " ").replace(".", " ").replace("?", " ").split():
        for topic, weight in LEXICON.get(word, {}).items():
            vector[TOPICS.index(topic)] += weight
    length = math.sqrt(sum(v * v for v in vector))
    if length == 0:
        return vector
    return [v / length for v in vector]          # unit length, so dot product = cosine

def cosine(a, b):
    return sum(x * y for x, y in zip(a, b))

# ---------- 1. The documents: a small help centre ----------
articles = {
    "Booking flights": "Find low-cost airline tickets and book flights from any airport.",
    "Hotel deals": "Find a hotel for your holiday, from city stays to beach resorts.",
    "Weather updates": "Check the rain and storm forecast before your trip.",
    "Account security": "Change your password and keep your app account safe.",
    "Healthy travel": "Tips on sleep, diet and exercise while on holiday.",
}

# ---------- 2. Indexing: embed each article once ----------
index = []
for title in articles:
    index.append({"title": title, "vector": embed(title + ". " + articles[title])})

# ---------- 3. Searching ----------
def search(query, k=2, min_score=0.5):
    q = embed(query)
    scored = []
    for item in index:
        scored.append((cosine(q, item["vector"]), item["title"]))
    scored.sort(reverse=True)
    results = []
    for score, title in scored[:k]:
        if score >= min_score:
            results.append((score, title))
    return results

# ---------- 4. Try it ----------
for query in ["cheap plane tickets", "is it going to snow?", "I forgot my password", "best pizza in town"]:
    print("Search:", query)
    results = search(query)
    if not results:
        print("   No good match. Try other words, or contact support.")
    for score, title in results:
        print(f"   {score:.2f}  {title}")

Walk through the four parts:

  1. Documents. Each article has a title and text.
  2. Indexing. Each article is embedded once, with its title and text together, because titles often carry the key words. The vectors are stored with the titles.
  3. Searching. The query is embedded with the same model, compared with every stored vector, sorted, cut to the top k, and filtered by a minimum score.
  4. Results. "cheap plane tickets" finds "Booking flights" without sharing the word "flights"; "is it going to snow?" finds the weather article; "best pizza in town" honestly returns nothing.

Things to try

  • Add an article, such as "Food on board" about meals on flights, then search for "vegetarian meal on my flight".
  • Raise min_score to 0.95. Which results disappear? Lower it to 0.1. Which unhelpful results appear?
  • Change k to 3 and see whether extra results help or just add noise.

Evaluate before you ship

Like a prompt, a search engine needs a test set: real queries with the article that should come first. Measure how often it does, change one thing (the model, the chunking, the threshold), and measure again.

Upgrading to real tools

To turn this into a real search engine, three parts change; the structure stays the same:

PartIn this lessonIn a real system
Embedding modelA word list with 6 topicsAn embedding API or open model with hundreds of dimensions
IndexA Python listA vector database or vector search library
Documents5 short articlesThousands of articles, split into chunks

With a real model, the embed function becomes a call such as:

def embed(texts):
    response = client.embeddings.create(model="EMBEDDING_MODEL", input=texts)
    return [item.embedding for item in response.data]

and the list of vectors becomes a collection in a vector database, which handles fast similarity search, filtering by metadata (such as language or product) and updates when articles change.

Common mistakes

Practice exercise

Evaluate the search engine on a small test set, the way you would before shipping it.

Your solutionPython
# Test queries with the article that SHOULD come first
tests = [
    ("cheap plane tickets", "Booking flights"),
    ("is it going to snow?", "Weather updates"),
    ("I forgot my password", "Account security"),
    ("staying fit on holiday", "Healthy travel"),
]
# What the search engine actually returned first for each query
top_result = {
    "cheap plane tickets": "Booking flights",
    "is it going to snow?": "Weather updates",
    "I forgot my password": "Account security",
    "staying fit on holiday": "Hotel deals",
}

# Print each query that went wrong, like: WRONG: staying fit on holiday -> Hotel deals
# Then print the score, like: 3 of 4 correct
Knowledge check

In a semantic search engine, what happens at search time?

Summary

  • A semantic search engine has four parts: documents, indexing (embed once), searching (embed the query, compare, rank) and results (top k above a minimum score).
  • Index titles with text, and always use the same model for documents and queries.
  • Evaluate with real test queries; read the misses to find content gaps and model weaknesses.
  • To go to production, swap in a real embedding model, a vector database and chunking; the structure stays the same.

Course complete

You now know what embeddings are, how to measure similarity, how embeddings are created and chosen, and how to use them for search, clustering, classification and visualisation. Next: Vector Databases to search millions of vectors quickly, and Retrieval-Augmented Generation to connect search to an LLM.

Finished reading? Tick it off to track your progress.