Semantic Search
Semantic search finds information by meaning instead of by matching words. Every document is turned into an embedding ahead of time; when a question arrives, it is embedded too, and the documents whose vectors are closest are returned. It is used when people describe what they want in their own words, which rarely match the words in your documents.
This lesson builds the chapter's checkpoint: search 50 school FAQ answers and return the three closest to a question.
Keyword vs Semantic vs Hybrid Search
| Method | How it matches | Strong at | Weak at |
|---|---|---|---|
| Keyword search | Shared words | Exact names, codes, IDs | Different wording; common words like "the" |
| Semantic search | Similar embeddings | Questions in people's own words | Exact codes, rare names, numbers |
| Hybrid search | Both scores, combined | Most real systems | Needs tuning of the mix |
Creating the FAQ
This program saves 50 short, made-up answers for Campus Helper's school, each with a category:
import json
FAQ = [
("fees", "The science lab fee is $45 a year and is due by September 30."),
("fees", "The field trip fee is $30 per trip, payable two weeks before the trip."),
("fees", "The library fee is $15 a year and covers book loans and printing."),
("fees", "Tuition is $250 a month, due on the first school day of each month."),
("fees", "You can pay fees online by card or bank transfer through the parent portal."),
("fees", "Cash payments are accepted at the school office from 8 a.m. to 3 p.m."),
("fees", "A late fee of $10 is added when a payment is more than 14 days overdue."),
("fees", "Families with financial need can apply for a fee waiver at the school office."),
("fees", "Siblings get a 10% discount on tuition from the second child onward."),
("fees", "Receipts are emailed automatically after every online payment."),
("fees", "Refunds for cancelled trips are returned to the original payment method within 10 days."),
("fees", "The sports program costs $60 a season, including the uniform."),
("fees", "Graduation costs $40, which covers the cap, gown and ceremony."),
("admission", "Admission forms for next year are due by March 1."),
("admission", "To apply, submit the online form, a birth certificate and the last school report."),
("admission", "Admission interviews take place in March, and each one lasts about 20 minutes."),
("admission", "Decisions are sent by email in the second week of April."),
("admission", "Students moving from another state can join mid-year if a place is free."),
("admission", "There is no admission test for grades 9 and 10."),
("admission", "Grade 11 applicants take a short math and English placement test."),
("admission", "Proof of address, such as a utility bill, is needed to complete enrollment."),
("admission", "Vaccination records must be submitted before the first day of school."),
("admission", "Families can book a campus tour on Tuesdays and Thursdays."),
("admission", "The waiting list is reviewed every month, and families are contacted by phone."),
("admission", "International students need a valid student visa before enrollment."),
("timetable", "Spring term starts on January 12 and ends on May 29."),
("timetable", "Fall term begins on August 18."),
("timetable", "School starts at 8:15 a.m. and ends at 3:05 p.m."),
("timetable", "On Wednesdays, students leave early at 1:30 p.m. for staff training."),
("timetable", "Final exams run from May 18 to May 22."),
("timetable", "Midterm exams are held in the first week of March."),
("timetable", "Winter break runs from December 21 to January 4."),
("timetable", "Spring break is the week of March 23."),
("timetable", "Parent-teacher conferences are held on October 16 and February 12."),
("timetable", "The school is closed on Thanksgiving Day and the day after."),
("timetable", "Class schedules for each student are posted in the parent portal."),
("timetable", "Lunch is from 11:50 a.m. to 12:30 p.m. for all grades."),
("other", "The school bus picks students up between 7:20 and 7:45 a.m."),
("other", "Lost items are kept at the front office for 30 days."),
("other", "Students must wear their school ID badge on campus at all times."),
("other", "Phones must stay in lockers during class time."),
("other", "The cafeteria offers vegetarian and gluten-free meals every day."),
("other", "Report an absence by calling the attendance line before 9 a.m."),
("other", "After-school tutoring is free on Mondays and Thursdays in the library."),
("other", "The counselor is available for students every school day in room 104."),
("other", "Bikes can be parked in the covered rack next to the gym."),
("other", "The parent portal password can be reset from the login page."),
("other", "Clubs include robotics, debate, chess, art and the school newspaper."),
("other", "The school nurse is in the health office from 8 a.m. to 3:30 p.m."),
("other", "Visitors must sign in at the front office and wear a visitor badge."),
]
json.dump([{"id": i + 1, "category": c, "text": t} for i, (c, t) in enumerate(FAQ)], open("faq.json", "w"), indent=1)
print("Saved", len(FAQ), "answers")Saved 50 answersExample: Keyword vs Semantic Search
import json
import re
from sentence_transformers import SentenceTransformer
texts = [item["text"] for item in json.load(open("faq.json"))]
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
answer_vectors = model.encode(texts, normalize_embeddings=True) # done once, ahead of time
def words(text):
return set(re.findall(r"[a-z]+", text.lower()))
def keyword_search(question, k=3):
scores = [len(words(question) & words(t)) for t in texts]
best = sorted(range(len(texts)), key=lambda i: -scores[i])[:k]
return [texts[i] for i in best if scores[i] > 0]
def semantic_search(question, k=3):
scores = answer_vectors @ model.encode(question, normalize_embeddings=True)
best = scores.argsort()[::-1][:k]
return [(round(float(scores[i]), 2), texts[i]) for i in best]
for question in ["How much do chemistry experiments cost?", "When do the holidays start in December?"]:
print(question)
print(" Keyword search:", keyword_search(question) or "no matches")
for score, text in semantic_search(question):
print(f" {score:.2f} {text}")How much do chemistry experiments cost?
Keyword search: no matches
0.58 The science lab fee is $45 a year and is due by September 30.
0.25 Graduation costs $40, which covers the cap, gown and ceremony.
0.25 The library fee is $15 a year and covers book loans and printing.
When do the holidays start in December?
Keyword search: ['Decisions are sent by email in the second week of April.', 'Midterm exams are held in the first week of March.', 'Class schedules for each student are posted in the parent portal.']
0.66 Winter break runs from December 21 to January 4.
0.50 Spring term starts on January 12 and ends on May 29.
0.44 Fall term begins on August 18.Explanation: All 50 answers are embedded once, ahead of time. For each question, one more embedding is made, and answer_vectors @ ... scores every answer in a single step. For the chemistry question, keyword search finds nothing, while semantic search puts the lab fee first, well ahead of the rest. For the holiday question, keyword search matches common words such as "the" and "in" and returns three wrong answers; semantic search finds winter break.
Semantic Search Isn't Perfect
Searching "My kid is sick today, what should I do?" with this model returns the vaccination-records answer first (0.32), with the attendance line, the answer a parent needs, third (0.25). All three scores are low, a sign that no answer fits well.
Common Mistakes
Re-embedding all documents for every question. Embed them once and reuse the vectors.
Dropping keyword search entirely. Exact names and codes still need it; hybrid search combines both.
Trusting the top result when every score is low. Low scores mean nothing matches well.
Interview Corner
How does semantic search work?
Documents are embedded ahead of time; at query time the question is embedded and the documents with the most similar vectors are returned, usually the top few by cosine similarity.
When is keyword search better than semantic search?
For exact identifiers, product codes, rare names and numbers, where the precise word matters more than the meaning. Hybrid search combines both for the best of each.
Practice
Exercise: the 50-answer checkpoint. Run both programs, then try five questions of your own, including one in Spanish. For each, note whether the top answer is right and what its score was. What score seems to separate good matches from poor ones for this model?
Check your understanding:
- Why are the answers embedded only once?
- Why did keyword search fail on the chemistry question?
- What do low top scores suggest?
Key Takeaways
Quick reference
| Step | Code |
|---|---|
| Embed answers once | answer_vectors = model.encode(texts, normalize_embeddings=True) |
| Embed a question | model.encode(question, normalize_embeddings=True) |
| Score all answers | answer_vectors @ question_vector |
| Top 3 | scores.argsort()[::-1][:3] |
Was this tutorial helpful?