The user wants a full-text search engine with relevance ranking.
This is a system design problem, but usually, when users ask for this in a coding context, they want a functional implementation or a guide on how to build one from scratch (or using libraries).
I should provide a high-level overview of the components (Indexer, Searcher, Ranker) and then provide a Python implementation using basic data structures to illustrate the concepts (TF-IDF, Inverted Index) without relying on heavy external tools like Elasticsearch or Solr initially, to show how it works. Then, I can briefly mention production-grade tools.
Plan:
Conceptual Overview: Explain Inverted Index and TF-IDF (Term Frequency-Inverse Document Frequency).
Implementation (Python):
Data Structures: need a way to store documents and the index.
Tokenization: Splitting text into words, lowercasing, removing punctuation.
Indexing: Building the inverted index (Word -> [DocID, Position/Frequency]).
Ranking (TF-IDF): Calculating the relevance score.
Querying: Processing a query, retrieving docs, sorting by score.
Refinement: Add BM25 or Cosine Similarity for better ranking? Let's stick to a simplified TF-IDF or Cosine Similarity for clarity, as it's easier to code from scratch in a single script.
Code Structure:
Class SearchEngine.
Methods: index_document, search.
Helper functions for text processing.
Drafting the Code:
Preprocessing:re module for splitting text. Convert to lowercase.
TF (Term Frequency): How often does the term appear in this doc?
IDF (Inverse Document Frequency): How rare is the term across all docs? log(N / df).
Score = TF * IDF.
Step-by-Step Implementation Details:
Tokenization:re.findall(r'\w+', text.lower())
Indexing:
Loop through documents.
Tokenize.
Update inverted_index[term][doc_id].
Keep track of document lengths (for normalization, though simple TF doesn't always need it, it's better for relevance).
Searching:
Tokenize query.
Find matching documents (intersection or union of sets). Let's do union for "OR" logic, but rank higher if more terms match.
Calculate TF-IDF for query terms against documents.
Rank.
Let's write the actual Python code mentally:
python
import math
import re
from collections import defaultdict
class SimpleSearch:
def __init__(self):
self.idx = defaultdict(list) # term -> [(doc_id, freq)]
self.docs = {} # id -> content
self.N = 0 # total docs
self.avg_len = 0
def add(self, doc_id, text):
# ... tokenize ...
# ... update idx ...
Refining the Ranking Model:
TF-IDF is the classic choice.
Score(D, Q) = ∑(tft,d×idft)
Where is count in doc, .
= total docs.
= number of docs containing the term.
Alternative: BM25?
It's the standard for "relevance ranking" in modern search (Elasticsearch uses it by default). It might be slightly more complex to explain, but I can provide a simplified version. Let's stick to Cosine Similarity or simple TF-IDF for the "from scratch" part because it's more intuitive, then mention BM25.
Actually, let's do TF-IDF with Cosine Similarity. It handles the vector space model well.
Components to include in the answer:
The "Why" and "How": Explanation of Inverted Indices.
The Code: A complete, runnable Python script.
The Ranking Logic: Explain TF-IDF clearly.
Next Steps/Production: Mention Lucene/Elasticsearch/Solr/Meilisearch.
Revising the Python Code for the Output:
Use collections.Counter for term frequencies.
Use defaultdict for the index.
Implement a search method that returns sorted results.
Self-Correction during thought process:
Should I use an external library like whoosh? No, the prompt implies "Create", which usually means understanding the underlying mechanism. A from-scratch implementation is more educational.
Final Code Structure:
clean_text: helper.
index: adds docs.
_calculate_idf: helper.
search: computes scores.
For every query term:
If term in index:
For every doc containing term:
Add TF-IDF score.
Let's add a small touch: handling basic phrase matching or at least prioritizing documents with all terms? The vector space model (Sum TF-IDF) naturally handles this because docs with more query terms will have higher sums.
Output Format:
Introduction.
Key Concepts (Inverted Index, TF-IDF).
Python Implementation.
Example Usage.
Limitations and Production Advice.
Let's write the code.
python
import math
import re
from collections import Counter, defaultdict
class SearchEngine:
def __init__(self):
self.documents = {} # id -> text
self.inverted_index = defaultdict(list) # term -> [(doc_id, term_freq)]
self.doc_lengths = {} # for normalization
self.avg_doc_length = 0
self.N = 0 # total docs
Wait, for pure TF-IDF vector space, we usually normalize by document length to prevent long documents from unfairly dominating. Or I can use Okapi BM25 which handles length normalization elegantly. BM25 is actually easier to implement "state of the art" relevance than pure vector cosine from scratch because you don't need to compute the full vector magnitude of the query/document, just the summation formula.
Let's stick to a robust TF-IDF implementation.
Score=∑i=1nTF(t
Actually, let's keep it simple: Simple TF-IDF summation.
Term Frequency: count (to dampen the effect of repeated words) or just raw count.
IDF: 1+.
I will implement a clean, object-oriented Search Engine in Python.
Outline:
Class SearchEngine
__init__: Initialize storage.
tokenize: Clean and split text.
add_document: Update doc store and index.
search: Query the index, rank results.
Refining the search method:
Get query tokens.
Initialize a scores dictionary (key: doc_id, value: score).
For each token:
Calculate IDF.
Get Postings List (docs containing token).
For each doc in list:
Calculate TF.
Add TF * IDF to scores[doc_id].
Sort scores descending.
Return top N results.
This is a solid plan. I will present this clearly.
Building a full-text search engine from scratch involves three main components:
Tokenization: Breaking text into individual words (tokens).
Indexing: Creating an Inverted Index (a map from words to the documents containing them).
Ranking: Calculating which documents are most relevant to the query (using TF-IDF).
Below is a complete, functional implementation in Python. It does not require any external libraries.
The Implementation
python
How it Works
1. The Inverted Index
This is the backbone of any search engine. Instead of reading every document character-by-character when a user searches (which is slow), we pre-process the data.
Input: "The cat sat"
Index:{'the': [Doc1], 'cat': [Doc1], 'sat': [Doc1]}
If you search for "cat", the engine jumps immediately to the key 'cat' in a hash map, finding the document instantly.
2. Relevance Ranking (TF-IDF)
Not all matches are equal. We use TF-IDF (Term Frequency-Inverse Document Frequency) to mathematically determine importance.
TF (Term Frequency): If the search term appears 10 times in Document A and 1 time in Document B, A is likely more relevant.
IDF (Inverse Document Frequency): If the search term is "the", it appears in almost every document. It provides no value. We penalize common words and reward rare words (like "asynchronous" or "microscope").
3. Tokenization
Raw text is messy. The _tokenize method converts "Hello, World!" into ['hello', 'world']. This ensures that searching for "hello" matches "Hello" and punctuation doesn't break the index.
How to Scale This
The code above is a memory-based search engine. If you need to handle millions of documents, you would need to modify the architecture to:
Persistency: Write the index to disk (using a structure like an LSM tree) instead of keeping it in a Python dictionary.
Sharding: Split the index across multiple servers (e.g., A-M on Server 1, N-Z on Server 2).
Compression: Use compression algorithms (like Delta Encoding) on the posting lists to save space.
tf
idf=log(N/df)
N
df
i
,
d
)
×
IDF(ti)
log
(
Docs with termTotal Docs
)
import math
import re
from collections import defaultdict, Counter
import json
class FullTextSearchEngine:
def __init__(self):
# Inverted Index: maps 'word' -> {doc_id: frequency}
self.index = defaultdict(Counter)
# Document Store: maps doc_id -> original text
self.documents = {}
# Term Frequencies for global stats: maps 'word' -> number of docs containing word
self.doc_freq = defaultdict(int)
# Total number of documents
self.total_docs = 0
def _tokenize(self, text):
"""
Cleans text, converts to lowercase, removes punctuation,
and splits into a list of words.
"""
text = text.lower()
# Remove punctuation and split by whitespace
tokens = re.findall(r'\b\w+\b', text)
return tokens
def add_document(self, doc_id, text):
"""
Adds a document to the index.
"""
if doc_id in self.documents:
print(f"Error: Document ID {doc_id} already exists.")
return
self.documents[doc_id] = text
self.total_docs += 1
tokens = self._tokenize(text)
term_counts = Counter(tokens)
# Update Inverted Index and Document Frequencies
for term, count in term_counts.items():
self.index[term][doc_id] = count
self.doc_freq[term] += 1
def _calculate_tf_idf(self, term, doc_id):
"""
Calculates the TF-IDF score for a specific term in a specific document.
TF (Term Frequency): How often the term appears in the doc.
IDF (Inverse Document Frequency): How rare the term is across all docs.
"""
# 1. Term Frequency (TF)
# Raw count or log-normalized. We will use log-normalization to prevent
# bias towards long documents.
tf = self.index[term][doc_id]
if tf == 0: return 0
tf_weight = 1 + math.log10(tf)
# 2. Inverse Document Frequency (IDF)
# Formula: log(Total Docs / Docs containing term)
df = self.doc_freq[term]
idf_weight = math.log10(self.total_docs / df)
return tf_weight * idf_weight
def search(self, query, top_k=5):
"""
Searches the index for the query and returns ranked results.
"""
query_tokens = self._tokenize(query)
if not query_tokens:
return []
# Scores accumulator: {doc_id: total_score}
scores = defaultdict(float)
# 1. Identify candidate documents (documents containing at least one query term)
candidate_docs = set()
for token in query_tokens:
if token in self.index:
candidate_docs.update(self.index[token].keys())
# 2. Score candidates using Vector Space Model (Cosine Similarity simplified)
# We compute the dot product of Query Vector and Document Vector
for doc_id in candidate_docs:
score = 0
for token in query_tokens:
if token in self.index and doc_id in self.index[token]:
# Note: For a strictly accurate Cosine Similarity, we should
# divide by the vector magnitude (length) of the document.
# However, for simple ranking, TF-IDF sum is often sufficient.
score += self._calculate_tf_idf(token, doc_id)
scores[doc_id] = score
# 3. Sort results by score descending
ranked_results = sorted(scores.items(), key=lambda item: item[1], reverse=True)
# 4. Format Output
results = []
for doc_id, score in ranked_results[:top_k]:
results.append({
"id": doc_id,
"score": round(score, 4),
"text": self.documents[doc_id][:100] + "..." # Preview
})
return results
# --- Usage Example ---
if __name__ == "__main__":
engine = FullTextSearchEngine()
# 1. Ingest Data
data = {
1: "The quick brown fox jumps over the lazy dog.",
2: "Never jump over a lazy dog quickly.",
3: "The dog is brown and the fox is red.",
4: "Search engines use inverted indices to find text quickly.",
5: "Python is a popular programming language for data science."
}
print("Indexing documents...")
for doc_id, text in data.items():
engine.add_document(doc_id, text)
# 2. Search
queries = ["quick fox", "lazy dog", "programming language"]
for q in queries:
print(f"\nSearching for: '{q}'")
results = engine.search(q)
for res in results:
print(f" -> [Score: {res['score']}] Doc {res['id']}: {res['text']}")