Semantic search finds documents by meaning instead of matching exact words. A query about saving money for a rainy day returns a document about emergency funds even though the two share almost no words. We build that in this tutorial with Sentence Transformers for embeddings and FAISS for fast lookup, all running locally on a CPU with no API key.
Key takeaways
- Semantic search turns text into vectors and ranks documents by cosine similarity, so meaning matters more than shared words.
- all-MiniLM-L6-v2 produces 384 dimensional embeddings, runs on CPU, and needs no API key.
- Normalising embeddings turns FAISS inner product search into cosine similarity search.
- IndexFlatIP is exact search and stays fast up to roughly a million vectors.
- Our test corpus of 24 documents returned the right top result for every query we tried, while keyword search missed the money query completely.
What we build
We build a small search engine over 24 short documents in six topics: Python, cooking, travel, health, money and space. The engine has three parts. First, a Sentence Transformers model turns each document into a 384 number vector called an embedding. Second, a FAISS index stores those vectors for fast nearest neighbour lookup. Third, a search function turns a query into a vector the same way and returns the closest documents with a similarity score. We also save the index to disk and compare the results with a plain keyword search so the difference is visible, not just claimed.
Prerequisites
We need Python 3.12 and pip. The tutorial runs on a CPU. The first run downloads the all-MiniLM-L6-v2 model, about 90 MB, from Hugging Face, and later runs reuse the cached copy. We used Python 3.12.3 with sentence-transformers 6.3.0, faiss-cpu 1.16.0, NumPy 2.5.5 and torch 2.15.0. Create a folder for the project and a virtual environment inside it:
mkdir semantic-search && cd semantic-search python3 -m venv venv venv/bin/pip install sentence-transformers faiss-cpu numpy If pip fails with "No space left on device" while the disk looks fine, the cause is usually a small /tmp partition. Point pip at a bigger temp folder with TMPDIR=~/workspace/.tmp venv/bin/pip install .... We hit exactly that in our own run.
Step 1: Prepare the document corpus
Search quality starts with the documents. Each document should be one idea in one or two sentences, because a single embedding has to stand for the whole text. Long pages need splitting into passages first, a step we keep for the "what to try next" section. Our corpus lives in the script as a list of 24 strings. Here are the first four:
DOCUMENTS = [ # Python "Python lists store ordered collections of items and support indexing, slicing and appending.", "A Python dictionary maps unique keys to values and looks up entries in constant time.", "List comprehensions build a new list from an iterable in a single readable line of Python.", "Python virtual environments isolate project dependencies so packages never clash.", # Cooking, travel, health, money and space follow the same pattern. # 24 documents in total, four per topic. ] Four documents per topic keeps the corpus small enough to run in seconds and varied enough that a wrong answer is easy to spot.
Step 2: Turn documents into embeddings
An embedding is a list of numbers that places a piece of text on a map of meaning. Texts with similar meanings land close together on that map. We use all-MiniLM-L6-v2, a small model with about 23 million parameters that produces 384 dimensional vectors. The Sentence Transformers library wraps the model behind one encode call:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") embeddings = model.encode( DOCUMENTS, convert_to_numpy=True, normalize_embeddings=True ) The normalize_embeddings=True flag matters. It scales every vector to length one. With vectors of length one, the dot product between two vectors equals their cosine similarity, which is the score we rank by. A score near 1 means very similar meanings, near 0 means unrelated, and a negative score means opposite directions.
Step 3: Build the FAISS index
Comparing a query vector with every document vector one by one works at 24 documents, but it gets slow as the corpus grows. FAISS, short for Facebook AI Similarity Search, is Meta's open source library for nearest neighbour search over vectors. We build an IndexFlatIP index, where IP stands for inner product. Because our vectors are normalised, inner product is cosine similarity, so the index returns exactly the ranking we want:
import faiss dimension = embeddings.shape[1] # 384 index = faiss.IndexFlatIP(dimension) index.add(embeddings.astype("float32")) IndexFlatIP is exact search: it checks every vector and returns the true nearest neighbours. That is the right choice up to roughly a million vectors. Beyond that, FAISS offers approximate indexes such as IVF and PQ that trade a little accuracy for much faster search, and we name them again in the final section. FAISS stores the vectors as float32, so we cast the embeddings before adding them.
Step 4: Search with a natural language query
Searching repeats the same two moves: encode the query with the same model and the same normalisation, then ask the index for the nearest neighbours. The search function returns score and document pairs:
def search(query, model, index, documents, top_k=3): query_vec = model.encode( [query], convert_to_numpy=True, normalize_embeddings=True ).astype("float32") scores, indices = index.search(query_vec, top_k) return [(float(scores[0][i]), documents[int(indices[0][i])]) for i in range(top_k)] Notice the query goes through the exact same encoding as the documents. If the query used a different model or skipped normalisation, the vectors would live in different spaces and the scores would be meaningless. That is the most common silent bug in a first semantic search build.
Step 5: Run it and read the real output
We ran the full script, including model load, in 38 seconds on this machine. The model load takes most of that time; encoding 24 documents takes about a second. Here is the real output for three queries:
Query: 'how do I save money for a rainy day' 0.322 An emergency fund covering three months of expenses protects you from sudden job loss. 0.265 Compound interest grows savings faster when returns are reinvested instead of withdrawn. 0.263 Paying off high interest credit card debt first saves more money than any savings account pays. Query: 'what is the best way to keep fit as I age' 0.440 Strength training twice a week protects bone density as you get older. 0.303 Regular brisk walking for 30 minutes a day lowers resting heart rate and improves sleep. 0.263 Drinking water before meals helps some people eat less and stay hydrated through the day. Query: 'cheap flights and packing tips for a holiday' 0.551 Budget airlines charge extra for cabin bags, so weigh your luggage before you reach the airport. 0.317 Pack light for a hiking trip: a 40 litre backpack forces you to carry only what you need. 0.159 A low cost index fund spreads your money across hundreds of companies in one purchase. The money query is the best proof the engine works. It shares almost no words with the emergency fund document, yet that document ranks first at 0.322. The fitness query ranks strength training first because "as you get older" matches "as I age" in meaning. The holiday query shows an honest limit: the third result, about index funds, is a miss. It scored only 0.159, far below the top two, which is why we read the scores instead of trusting the ranking blindly.
How does semantic search compare with keyword search?
Keyword search counts shared words, and that is exactly why it fails here. The top keyword hit is a walking document. It wins on small shared words such as "for", "a" and "day", while the emergency fund document shares almost nothing with the query and never appears. The two approaches answer different questions: keyword search asks "which document uses these words", semantic search asks "which document means this". Independent testing agrees with the gap. A measured comparison on 38 labelled questions found all-MiniLM-L6-v2 put the right passage first for 79 percent of questions written to avoid the document's words, while BM25 keyword scoring managed 21 percent on the same set.
Keyword search for 'how do I save money for a rainy day': 3 shared words Regular brisk walking for 30 minutes a day lowers resting heart rate and improves sleep. 2 shared words To make a good tomato sauce, simmer crushed tomatoes with garlic, olive oil and basil for 30 minutes. 2 shared words Pack light for a hiking trip: a 40 litre backpack forces you to carry only what you need. The keyword output proves the point. The right document never appears in the top three, while semantic search put it first at 0.322.
Step 6: Save the index and search it later
Encoding documents on every run wastes time, so we save the index and the document list to disk. FAISS has its own save and load calls, and the documents go to a JSON file in the same order as the vectors:
faiss.write_index(index, "semantic_index.faiss") with open("documents.json", "w", encoding="utf-8") as f: json.dump(DOCUMENTS, f, indent=2) A second script loads both files and answers one query from the command line. Our saved index file is 36,909 bytes for 24 vectors, and a reload test confirmed it returns byte identical results to the fresh index. Running python search_saved.py "which planet has the biggest volcano" gives:
Loaded index with 24 vectors 0.762 Mars has the largest volcano in the solar system, Olympus Mons, nearly three times the height of Everest. 0.398 Jupiter's Great Red Spot is a storm wider than Earth that has raged for centuries. 0.245 A year on Neptune lasts almost 165 Earth years because it orbits so far from the Sun. The volcano query scores 0.762, the highest score in the whole tutorial, because the query and the Mars document describe the same fact in different words. We also wrote eight automated checks that run the whole pipeline: index shape, normalised vectors, correct top result for four queries, decreasing scores, keyword search missing the money query, and identical results after a save and reload. All eight pass.
What should we try next?
First, index our own notes. Point the script at a folder of .txt or .md files, split each file into passages of 100 to 300 words, and search them the same way. Second, swap IndexFlatIP for an approximate index such as IndexIVFFlat and measure how much faster search gets on a larger corpus, and how much accuracy it costs. Third, try a multilingual model such as paraphrase-multilingual-MiniLM-L12-v2 and test queries in another language against the same documents. Each of these is one small change to the code we already ran.
Originally published on LogicStack. Run the code examples right in your browser with our free interactive Python and SQL playgrounds — no setup, no sign-up.

