If you’ve ever typed “something to keep my tea warm on the train” into a store’s search bar and got a travel mug back, even though no product says “tea” or “train”, you’ve used semantic search.
Semantic search finds documents by meaning instead of by shared words. A machine learning model turns every piece of text into an embedding, a vector of numbers, and texts with similar meanings get embeddings that sit close together. Keyword search matches the words themselves. Hybrid search runs both and merges the two rankings into one list.
In this guide, we’ll build keyword, semantic and hybrid search in about 15 lines of Python each, run the same four queries through all three to see where each one wins and where it fails, and then look at how a purpose-built search engine handles the same job.
Note: The examples use Python 3.15, bm25s 0.3.17, sentence-transformers 6.3.0 with the all-MiniLM-L12-v2 model, and Typesense 30.2.
What Is Semantic Search?
Semantic search ranks documents by how close their meaning is to the query. To do that, it needs a way to measure meaning, and that’s the job of an embedding. An embedding is an array of floating point numbers that a model produces from a piece of text, and the model is trained so that texts with similar meanings get similar arrays.
You can think of embeddings much like coordinates on a map. Two cafés on the same street have close coordinates even when their names share no letters. In the same way, the query “keep my tea warm on the train” lands nearest to a mug that “holds heat for 6 hours”, even though the two share no words.
The model we’ll use, all-MiniLM-L12-v2, maps each text to a 384-dimensional vector. A search then has two steps:
- Embed every document once, when you index it.
- Embed the query, and return the documents whose vectors are nearest to it.
“Nearest” is usually measured with cosine distance, which compares the direction of two vectors. It runs from 0 (identical direction) to 2 (opposite), so lower is closer.
A Small Catalog to Search
Every example in this guide searches the same eight products from a kitchen and home store. Save them as products.jsonl:
{"id": "1", "name": "Insulated Travel Mug", "description": "Double-wall stainless steel tumbler with a leakproof lid. Holds heat for 6 hours."}
{"id": "2", "name": "Burr Coffee Grinder", "description": "Grinds whole beans evenly for espresso, pour-over or French press coffee."}
{"id": "3", "name": "KX-200 Water Filter Cartridge", "description": "Replacement cartridge for KX-200 pitchers. Lasts about 2 months."}
{"id": "4", "name": "KX-220 Water Filter Cartridge", "description": "Replacement cartridge for KX-220 countertop dispensers. Lasts about 6 months."}
{"id": "5", "name": "KX-300 Shower Filter", "description": "Reduces chlorine. Fits KX-300 shower heads."}
{"id": "6", "name": "Electric Kettle", "description": "Boils 1.7 litres of water in under 4 minutes, with auto shut-off."}
{"id": "7", "name": "Chef's Knife", "description": "8-inch stainless steel blade for chopping vegetables and slicing meat."}
{"id": "8", "name": "Cooler Bag", "description": "Soft cooler that chills food and drinks for 12 hours. Fits 24 cans."}
We’ll use two libraries, bm25s for keyword search and sentence-transformers for embeddings. On Linux, pip pulls in the CUDA build of torch, so if you don’t need a GPU, you want to install the CPU-only build first:
pip install torch==2.15.0 --index-url https://download.pytorch.org/whl/cpu
Then install the two libraries:
pip install bm25s==0.3.17 sentence-transformers==6.3.0
We’ll run four queries against this catalog, and each one is picked to show one behavior:
| Query | What it tests |
|---|---|
keep my tea warm on the train | The right product shares no words with the query |
KX-220 | The query is a part number |
lawn mower | Nothing in the catalog is relevant |
keep my coffee hot | One query word matches the wrong product |
How Keyword Search Works
Keyword search, also called lexical search, finds documents that contain the words in the query. It’s built on an inverted index, which works much like the index at the back of a book. For every word, the index lists the documents that contain it, so a search looks up each query word and collects the matches.
Matching documents are then ranked with BM25, the ranking function behind many keyword search engines (it’s the default similarity in Elasticsearch, for example). BM25 scores a document higher when it contains the query words often, and when those words are rare across the collection.
Save this as keyword_search.py in the same directory as products.jsonl:
import json
import sys
import bm25s
docs = [json.loads(line) for line in open("products.jsonl")]
texts = [f"{d['name']} {d['description']}" for d in docs]
retriever = bm25s.BM25()
retriever.index(bm25s.tokenize(texts, stopwords="en", show_progress=False), show_progress=False)
def keyword_search(query, k=3):
tokens = bm25s.tokenize(query, stopwords="en", show_progress=False)
ids, scores = retriever.retrieve(tokens, k=k, show_progress=False)
return [(docs[i]["name"], float(s)) for i, s in zip(ids[0], scores[0]) if s > 0]
if __name__ == "__main__":
for name, score in keyword_search(sys.argv[1]):
print(f"{score:.2f} {name}")
The script joins each product’s name and description, lowercases the text and splits it into words (KX-220 becomes kx and 220), and drops English stopwords such as “on” and “the”. bm25s uses Lucene’s BM25 variant by default. The score > 0 filter is there because bm25s pads the result with zero-score documents when fewer than k documents match.
Let’s search for a part number:
python keyword_search.py "KX-220"
1.48 KX-220 Water Filter Cartridge
0.55 KX-300 Shower Filter
0.53 KX-200 Water Filter Cartridge
This is where keyword search shines. The word 220 appears in one product only, so BM25 gives that product almost three times the score of the next one. The other two KX products match only on kx.
Now try keep my tea warm on the train. It returns nothing, since no product contains “tea”, “warm” or “train”. That’s the core weakness of keyword search, called vocabulary mismatch. The user’s words and the document’s words describe the same thing, but they’re different words. lawn mower also returns nothing, which is the right answer here, since we don’t sell one.
Keyword search is also literal about spelling. A search for insulatd returns no matches, so real keyword engines add typo tolerance on top, which we cover in our guide to fuzzy search. And keep my coffee hot returns only the Burr Coffee Grinder, because “coffee” is the only query word in the catalog.
If your data already lives in a database, you can get keyword search there too, with full-text search in MySQL or MongoDB text indexes.
How Semantic Search Works
Semantic search embeds the query and every document with the same model, then returns the documents whose embeddings are nearest to the query’s. We’ll use sentence-transformers, the Python library that grew out of the Sentence-BERT paper, to run the all-MiniLM-L12-v2 model locally.
Save this as semantic_search.py:
import sys
from sentence_transformers import SentenceTransformer
from keyword_search import docs, texts
model = SentenceTransformer("sentence-transformers/all-MiniLM-L12-v2")
doc_vectors = model.encode(texts, normalize_embeddings=True)
def semantic_search(query, k=3):
query_vector = model.encode(query, normalize_embeddings=True)
distances = 1 - doc_vectors @ query_vector # cosine distance, 0 is identical
return [(docs[i]["name"], float(distances[i])) for i in distances.argsort()[:k]]
if __name__ == "__main__":
for name, distance in semantic_search(sys.argv[1]):
print(f"{distance:.4f} {name}")
The first run downloads the model from Hugging Face. normalize_embeddings=True scales every vector to length 1, so one minus the dot product of two vectors is their cosine distance.
Let’s run the query that keyword search couldn’t answer:
python semantic_search.py "keep my tea warm on the train"
0.6488 Insulated Travel Mug
0.7740 Cooler Bag
0.7770 Electric Kettle
The mug comes first, even though it shares no words with the query. keep my coffee hot also puts the mug first (0.5989), ahead of the grinder (0.7107), and the mug is the product a shopper typing that query actually wants.
Semantic search has three weak points that you want to know about before you ship it:
- It always returns something. Semantic search returns the nearest documents, relevant or not.
lawn mowerreturns the Chef’s Knife at a distance of 0.7392. You need a distance cutoff to say “no results”, and the right cutoff depends on the model and the data. - Exact terms win by a narrow margin. For
KX-220, the right cartridge comes first at 0.5254, but the KX-200 cartridge is right behind it at 0.5422. BM25 separated them by 1.48 against 0.53. Research agrees in general. BM25 is a robust baseline on data the model wasn’t trained on, and dense retrievers drastically underperform on questions about specific named entities. - It costs more and explains less. You run a model for every document and every query, and when a result looks wrong, there’s no matched word to point at.
Semantic Search vs Vector Search
Semantic search is the goal, matching by meaning. Vector search is the mechanism, a nearest-neighbor search over vectors, and the same mechanism also powers recommendations and image search. That’s why the two terms often get used as synonyms, even though they’re not quite the same thing. Our script compares the query with every vector, which is fine for eight products. Real engines use an approximate index such as HNSW to avoid scanning millions of vectors per query.
How Hybrid Search Works
Hybrid search runs a keyword search and a semantic search for the same query, then merges the two result lists. You can’t just add the scores, since a BM25 score of 1.48 and a cosine distance of 0.5254 are on different scales. So hybrid systems often merge by rank instead, with Reciprocal Rank Fusion (RRF). Each document scores 1 / (k + rank) in every list it appears in, and the scores are added up. The paper uses k = 60, which is also Elasticsearch’s default.
Save this as hybrid_search.py:
import sys
from keyword_search import keyword_search
from semantic_search import semantic_search
def hybrid_search(query, k=3, rrf_k=60):
scores = {}
for results in (keyword_search(query, k=8), semantic_search(query, k=8)):
for rank, (name, _) in enumerate(results, start=1):
scores[name] = scores.get(name, 0) + 1 / (rrf_k + rank)
return sorted(scores.items(), key=lambda item: -item[1])[:k]
if __name__ == "__main__":
for name, score in hybrid_search(sys.argv[1]):
print(f"{score:.4f} {name}")
Let’s run the part number again:
python hybrid_search.py "KX-220"
0.0328 KX-220 Water Filter Cartridge
0.0320 KX-300 Shower Filter
0.0320 KX-200 Water Filter Cartridge
The KX-220 cartridge is first in both lists, so it wins. The other two tie, because each one is second in one list and third in the other. For keep my tea warm on the train, the keyword list is empty, so hybrid search returns the semantic ranking with the mug first.
Hybrid search inherits a weak point from each side, though:
- It still returns something for
lawn mower. The keyword side is empty, so the Chef’s Knife comes through from the semantic side. - A stray keyword match can win. For
keep my coffee hot, the grinder is first in the keyword list and second in the semantic list, so it scores1/61 + 1/62 = 0.0325. The mug is first in the semantic list only, so it scores1/61 = 0.0164. Plain RRF puts the wrong product first.
Search engines usually give you two controls for both weak points, a weight for each side and a distance cutoff for the semantic side.
Semantic Search vs Keyword Search vs Hybrid Search
Here’s the top result for each query from the three scripts:
| Query | Keyword search | Semantic search | Hybrid search (RRF) |
|---|---|---|---|
keep my tea warm on the train | No results | Insulated Travel Mug | Insulated Travel Mug |
KX-220 | KX-220 cartridge (1.48 vs 0.55) | KX-220 cartridge (0.5254 vs 0.5422) | KX-220 cartridge |
lawn mower | No results (correct) | Chef’s Knife | Chef’s Knife |
keep my coffee hot | Burr Coffee Grinder | Insulated Travel Mug | Burr Coffee Grinder |
And here’s when you’d pick each one:
| Approach | Best for | Trade-off |
|---|---|---|
| Keyword search | Names, part numbers, exact terms | Misses results phrased in other words |
| Semantic search | Natural-language questions, descriptions, RAG retrieval | Always returns something, weak on exact terms, needs a model |
| Hybrid search | User-facing search with both kinds of queries | Needs tuning, and inherits a failure from each side |
In short, start with keyword search when your users type names and codes, add semantic search when they describe what they want, and use hybrid search when you can’t predict which one they’ll do.
Semantic and Hybrid Search with Typesense
In Typesense, you don’t run the model yourself. You name a model in the schema, and Typesense embeds every document and every query for you. Listing the embedding field next to the text fields in query_by makes the search hybrid.
The requests below assume a Typesense server on localhost:8108 with its API key in the TYPESENSE_API_KEY environment variable, and you run them from the directory that holds products.jsonl.
Create a collection with an auto-embedding field. ts/all-MiniLM-L12-v2 is the same model we used in Python, from Typesense’s built-in models:
curl "http://localhost:8108/collections" \
-X POST \
-H "Content-Type: application/json" \
-H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
-d '{
"name": "products",
"fields": [
{"name": "name", "type": "string"},
{"name": "description", "type": "string"},
{
"name": "embedding",
"type": "float[]",
"embed": {
"from": ["name", "description"],
"model_config": {"model_name": "ts/all-MiniLM-L12-v2"}
}
}
]
}'
The first collection that uses a built-in model waits while Typesense downloads the model. Then import the same products.jsonl:
curl "http://localhost:8108/collections/products/documents/import?action=create" \
-X POST \
-H "Content-Type: text/plain" \
-H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
--data-binary @products.jsonl
Each of the eight lines comes back as {"success":true}. Now a semantic search is a regular search with only the embedding field in query_by:
curl -G "http://localhost:8108/collections/products/documents/search" \
-H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
--data-urlencode "q=keep my tea warm on the train" \
--data-urlencode "query_by=embedding" \
--data-urlencode "exclude_fields=embedding" \
--data-urlencode "per_page=1"
{
"found": 1,
"hits": [
{
"document": {
"id": "1",
"name": "Insulated Travel Mug",
"description": "Double-wall stainless steel tumbler with a leakproof lid. Holds heat for 6 hours."
},
"vector_distance": 0.6487656831741333
}
]
}
That’s the same distance as our Python script, to four decimal places, and the other three queries agree too, since it’s the same model on the same text.
For a hybrid search, add the text fields to query_by:
curl -G "http://localhost:8108/collections/products/documents/search" \
-H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
--data-urlencode "q=KX-220" \
--data-urlencode "query_by=name,description,embedding" \
--data-urlencode "exclude_fields=embedding" \
--data-urlencode "per_page=2"
{
"found": 8,
"hits": [
{
"document": {"id": "4", "name": "KX-220 Water Filter Cartridge", "description": "..."},
"hybrid_search_info": {"rank_fusion_score": 1.0},
"text_match": 578730123365189754,
"vector_distance": 0.5253547430038452
},
{
"document": {"id": "3", "name": "KX-200 Water Filter Cartridge", "description": "..."},
"hybrid_search_info": {"rank_fusion_score": 0.15000000596046448},
"text_match": 0,
"vector_distance": 0.5421918630599976
}
]
}
Typesense also merges by rank, but it weights the keyword rank at 0.7 and the semantic rank at 0.3 by default, and you can change that with the alpha option of vector_query. Each list adds weight / rank, with no k. The KX-220 cartridge is first in both lists, so it scores 1.0, and the KX-200 cartridge is second in the semantic list only, so it scores 0.15.
Notice that only one document has a nonzero text_match. Typesense’s keyword side wants every query word in one document, and when nothing matches, it drops words from the ends of the query one at a time. In keep my coffee hot, the word coffee sits in the middle, so it’s never searched on its own. That’s why this query finds no keyword match here (keep my coffee does find the grinder), and the hybrid result is the mug, not the grinder.
Without a cutoff, all eight products match the KX-220 hybrid search, so found is 8. A distance_threshold fixes the lawn mower problem:
curl -G "http://localhost:8108/collections/products/documents/search" \
-H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
--data-urlencode "q=lawn mower" \
--data-urlencode "query_by=name,description,embedding" \
--data-urlencode "vector_query=embedding:([], distance_threshold: 0.7)" \
--data-urlencode "exclude_fields=embedding"
{
"found": 0,
"hits": []
}
The same cutoff keeps one result for the tea query and three for KX-220. The value 0.7 fits this model and these eight products, so you want to pick yours from real queries on your own data.
Typesense has its own trade-offs. It keeps the whole index in memory, and it isn’t a primary data store, so you keep it in sync with your database. Built-in models run on the CPU unless you set up a GPU, and the vector index is HNSW, which is approximate.
Conclusion
Building search yourself with BM25 and an embedding library, as we did above, is the right call for a prototype, an offline job, or a RAG pipeline where you want to control every step. And if your users mostly search for names, codes and exact terms, keyword search alone, with typo tolerance, is often all you need.
Typesense fits user-facing search that needs keyword matching, typo tolerance and semantic ranking in one request, at the cost of an in-memory index that you keep in sync with your primary database. For more on the keyword side, see our guides to fuzzy search and Elasticsearch bool queries.