Part 16 / Topic 2 of 5
Similarity search
Index: embed every document once. Query: embed the question, take the top-k by cosine. This course's offline stand-in uses TF-IDF vectors (word-count based — section 3), so you can watch the mechanics with real output:
# examples/01_vector_search_over_the_help_centre.py (abridged)
vectorizer = TfidfVectorizer(stop_words="english")
doc_vectors = vectorizer.fit_transform(texts) # 8 docs, 87 dims
scores = cosine_similarity(vectorizer.transform([query]), doc_vectors)[0]
# query: "how many days to return an item"
# 0.365 returns
# 0.271 cancel
# 0.165 shipping
Right answer, ranked first, with honest scores attached. At production scale (millions of vectors) exact scoring gives way to approximate nearest-neighbour indexes (HNSW and friends) in a vector store or Postgres's pgvector — same idea, faster lookup.
🧪 Quick quiz
- Why compare embeddings with cosine similarity?
Show the answer
It measures how similar the directions (meanings) are regardless of vector length — measured above: the returns policy topped the ranking at 0.365 for a returns question.
Done here? The practice set for Part 16 — 4 exercises with solutions — is on the part page.