The user wants a search engine indexing and ranking system.
This is a broad request. A full-blown search engine (like Google) is massive. I need to provide a conceptual framework or a simplified functional implementation to be useful.
Indexing: Storing data for fast retrieval (Inverted Index).
Ranking: Scoring documents based on relevance (TF-IDF, BM25, PageRank).
Querying: Handling user input and returning results.
Scope of the Solution:
I cannot build a web-scale crawler here.
I should focus on the core logic of indexing and ranking within a single Python script or a small set of classes.
I'll use Python because it has great libraries for NLP (NLTK, spaCy, Scikit-learn), though for a "from scratch" educational view, I might stick to standard libraries + maybe numpy or just pure Python for clarity.
Let's aim for a mini-system that indexes a list of provided text documents.
Architecture:
Document Class: To hold the raw text and ID.
Indexer Class:
Needs a tokenizer (split text, lowercase, remove punctuation).
Needs a stop-word remover (optional but good for quality).
Data Structure: An Inverted Index. Map<Word, List<DocumentID, Frequency>>.
Ranker Class:
TF-IDF (Term Frequency-Inverse Document Frequency): The standard basic ranking algo.
TF: How often does the word appear in this doc?
IDF: How rare is the word across all docs? (Penalizes "the", "is", etc.).
Vector Space Model: Represent docs and queries as vectors, calculate Cosine Similarity. This is a robust way to handle "indexing and ranking" together.
Step-by-Step Implementation Plan:
Step 1: Setup/Imports. Math functions for logs and square roots.
Step 2: Preprocessing. A function to clean text (lower, split).
Step 3: Indexing (The Inverted Index).
Build a dictionary where keys are terms and values are lists of doc IDs.
Also need to store Term Frequencies (TF) per doc.
Step 4: Ranking (TF-IDF & Cosine Similarity).
Calculate IDF for all terms.
Build TF-IDF vectors for documents.
Build TF-IDF vector for the query.
Compute dot product / (magnitude product) to get similarity score.
Step 5: The Search Interface. A class that ties it all together.
Refining the Code Structure:
Class SearchEngine
__init__: Initialize index, document store, term frequencies, document frequencies.
index_document(doc): Add to corpus, update structures.
search(query): Return sorted list of docs.
Let's write the code mentally:
Tokenizer:re.findall(r'\w+', text.lower())
Index:self.index = {term: {doc_id: count, ...}, ...}. Actually, easier to just calculate TF on the fly during indexing. Let's store self.docs as a map id -> text (or tokens) to calculate TF later, or pre-calculate.
Pre-calculating TF is better for speed.
self.doc_vectors: stores the TF-IDF vector for every doc.
Wait, TF-IDF vectors are sparse and high dimensional. Storing them as dictionaries is better (feature -> weight).
Revised Architecture (Vector Space Model):
Corpus: A list of strings.
Vocabulary: A set of all unique words in the corpus.
Document Vectors: For each doc, create a vector size of vocab. Value = TF * IDF.
Query Vector: For the query, create vector size of vocab. Value = TF * IDF (using corpus IDF).
Similarity: Dot product of Query Vector and Doc Vector.
Critique of Vector Space Model for a demo: It's great for ranking but computationally heavy if the vocab is huge. For a demo, it's perfect because it's mathematically rigorous and easy to understand.
Alternative: BM25? It's better than TF-IDF but slightly more complex to implement from scratch without libraries. Let's stick to TF-IDF/Cosine Similarity as it's the "Hello World" of search ranking.
Drafting the Code:
python
import math
import re
from collections import defaultdict
class SearchIndex:
def __init__(self):
self.documents = {} # id -> text
self.term_freqs = {} # id -> {term -> count}
self.doc_freqs = defaultdict(int) # term -> how many docs have it
self.doc_count = 0
def clean(self, text):
return re.findall(r'\w+', text.lower())
def add(self, doc_id, text):
self.doc_count += 1
self.documents[doc_id] = text
tokens = self.clean(text)
# local TF
tf = defaultdict(int)
for t in tokens:
tf[t] += 1
self.term_freqs[doc_id] = tf
# Global DF
for t in set(tokens):
self.doc_freqs[t] += 1
def search(self, query):
# 1. Process query
# 2. Calculate IDF for query terms
# 3. Compare query vector against doc vectors using TF-IDF scores
pass
Let's make it robust.
I will structure the response into three parts:
Conceptual Overview: Explain the pipeline (Crawl -> Index -> Rank).
Python Implementation: A clean, from-scratch class using TF-IDF and Cosine Similarity.
Extensions: How to make it production-ready (Lucene, PageRank, BERT).
Ranking Logic Details (Cosine Similarity):
Score = ∑(Qi⋅Di)/(∥Q∥⋅
Where is TF-IDF of term in query, is TF-IDF of term in doc.
Actually, since doc magnitude is constant, we can pre-calculate doc vectors.
However, for a simple script, calculating on the fly during search is fine for small datasets. Let's pre-calculate doc vectors for better code structure.
Wait, strict TF-IDF vectors are large.
Optimization: Only iterate over terms present in the Query.
When searching for "Apple Pie":
For every document containing "apple" or "pie":
a. Get doc's TF for "apple" and "pie".
b. Calculate dot product and magnitudes (only for these dimensions).
c. Cosine Sim = Dot / (MagQ * MagD).
Note: This is an approximation of Cosine Sim if we ignore other dimensions in Magnitude, but since other dimensions are 0 in the query, the dot product is correct. However, the denominator ∣D∣ must include all terms in the document, not just the query terms.
Correction: To do Cosine Similarity correctly, we need the full magnitude of the Document vector (∣D∣). We should pre-calculate ∣D∣ (the normalization factor) for every document at index time.
Algorithm update:
Indexing:
Tokenize.
Store TFs.
Update DFs.
After all docs added, compute IDF for all terms.
Pre-compute doc_magnitudes∑(TF⋅IDF)2 for every doc.
This is efficient and mathematically sound.
Let's write the actual code.
I'll provide a complete Python script. I'll add comments explaining the math.
Additional feature: Highlighting? Maybe too complex for a basic snippet. Just returning the ID and Score is enough.
Formatting the Output:
Start with the high-level concepts.
Then the code block.
Then an explanation of the code.
Finally, a brief note on how Google does it differently (Link analysis, LLMs).
Self-Correction during drafting:
Should I use a library like scikit-learn? It makes it 3 lines of code (TfidfVectorizer, cosine_similarity).
Decision: No, the user asked to "create" a system, implying they want to understand the mechanics. Using a black-box library defeats the purpose. I will write it in pure Python to show exactly how the Inverted Index and TF-IDF logic works.
Code Structure:
python
import math
import re
from collections import Counter
class SearchEngine:
def __init__(self):
# Index structures
pass
def tokenize(self, text):
# standardization
pass
def index(self, documents):
# Build inverted index and stats
pass
def rank(self, query):
# TF-IDF calculation
pass
I will refine the index method to accept a list of (id, text) tuples.
I will include __main__ block to demonstrate usage.
Final check of the request: "Create a search engine indexing and ranking system."
The plan covers both indexing (storage) and ranking (retrieval logic).
One detail: TF calculation.
Raw count is okay.
Log normalization is better: 1+log(tf). I'll stick to raw count for simplicity unless it ruins results (it won't for a demo). Actually, let's use basic raw count for TF, and log for IDF.
IDF formula: log(ntN) or often to avoid division by zero (though is never 0 if we look it up). I'll use .
Let's double check the vector math.
Sim(D,Q)=∥D∥∥Q∥D⋅Q
Since is 0 for non-query terms, this is just summing over query terms.
Denominator: We need which is for terms .
So we must precompute for every document.
Okay, ready to generate.
Creating a search engine involves three main stages:
Crawling/Parsing: Gathering data.
Indexing: organizing data for fast retrieval (using an Inverted Index).
Ranking: Sorting the results by relevance (using TF-IDF and Cosine Similarity).
Below is a complete, functional implementation in Python. It is written from scratch without using external search libraries (like Elasticsearch or Whoosh) so you can see exactly how the algorithms work.
The Python Implementation
You can save this code to a file (e.g., search_engine.py) and run it.
python
How It Works
1. Tokenization & Preprocessing
Before indexing, text must be cleaned. In the _tokenize function, we convert "Hello World!" to ["hello", "world"]. This ensures that searching for "hello" finds "Hello".
2. The Inverted Index
The core data structure is the inverted_index.
Instead of scanning every document for the word "cat", we build a dictionary where the word "cat" points directly to a list of documents containing it.
Format:{'cat': {1: 2, 3: 1, 4: 1}}
This allows us to retrieve documents in O(1) time complexity relative to the number of documents.
3. The Ranking Algorithm (TF-IDF & Cosine Similarity)
We don't just want to know if a document contains the word; we want to know how relevant it is.
TF (Term Frequency): How often does the word appear in this document? (e.g., if "cat" appears 5 times, it's likely more relevant than a doc where it appears once).
IDF (Inverse Document Frequency): Is the word rare? The word "the" appears in almost every document, so it has a low weight (low discrimination power). The word "mathematics" is rare, so it has a high weight.
Cosine Similarity:
We treat every document and the search query as vectors in multi-dimensional space.
Convert the document into a vector of TF-IDF weights.
Convert the query into a vector of TF-IDF weights.
Calculate the angle between them (Cosine Similarity).
If the vectors point in the same direction (angle ≈0), the documents are highly relevant.
If they are perpendicular (angle 90∘), there is no match.
Moving from Prototype to Production
While the code above demonstrates the logic, a production search engine (like Elasticsearch or Apache Solr) adds several complex layers:
Persistence: The index is saved to disk, not held in RAM.
Compression: Inverted indices are highly compressed (using bit-packing) to save space.
Distributed Sharding: The index is split across hundreds of machines to handle billions of documents.
PageRank: Google's famous algorithm, which measures the authority of a page based on how many other pages link to it.
BM25: The standard ranking algorithm used today is Okapi BM25, which is a refinement of the TF-IDF logic used above (it saturates term frequency so a word appearing 100 times isn't 10x better than appearing 10 times).
∥
D
∥
)
Qi
i
Di
i
Searching:
Tokenize query.
Compute query vector components (TF*IDF).
Compute query magnitude.
Identify candidate docs (those containing at least one query term).
Compute Dot Product (Sum of TF_query * IDF * TF_doc * IDF for matching terms).
Score = Dot / (QueryMag * DocMag).
Sort.
log
(
ntN
+
1)
nt
log(ntN)
D⋅Q=∑(wd,i⋅wq,i)
wq,i
∥D∥
∑wd,k2
all
k
∥D∥
import math
import re
from collections import defaultdict, Counter
class SearchEngine:
def __init__(self):
# Inverted Index: maps words to documents containing them
# Structure: {'word': {'doc_id': count}}
self.inverted_index = defaultdict(dict)
# Document Store: maps ID to original text
self.documents = {}
# Term Frequencies: maps doc_id to its total word count
self.doc_lengths = {}
# IDF Cache: maps word to its IDF score
self.idf_cache = {}
def _tokenize(self, text):
"""
Converts text to lowercase and removes punctuation.
"""
text = text.lower()
# Regex to keep only alphanumeric characters and spaces
text = re.sub(r'[^\w\s]', '', text)
return text.split()
def index(self, doc_id, text):
"""
Processes a document and adds it to the index.
"""
self.documents[doc_id] = text
tokens = self._tokenize(text)
# Count term frequencies in this specific document
term_freqs = Counter(tokens)
self.doc_lengths[doc_id] = len(tokens)
# Update inverted index
for term, count in term_freqs.items():
self.inverted_index[term][doc_id] = count
# Clear IDF cache because corpus size changed
self.idf_cache = {}
def _calculate_idf(self, term):
"""
Calculates Inverse Document Frequency.
IDF(t) = log(Total Documents / Documents containing term t)
"""
if term in self.idf_cache:
return self.idf_cache[term]
if term not in self.inverted_index:
return 0
total_docs = len(self.documents)
docs_with_term = len(self.inverted_index[term])
# Using log10, adding 1 to denominator to avoid division by zero (smooth IDF)
idf = math.log10(total_docs / (docs_with_term))
self.idf_cache[term] = idf
return idf
def _get_doc_vector_magnitude(self, doc_id):
"""
Calculates the magnitude of a document vector for normalization.
||D|| = sqrt(sum(tf * idf)^2)
"""
# In a real production system, we would pre-calculate this during indexing.
# Here we calculate on the fly for simplicity.
# We need to find all terms in this doc.
# This is inefficient for large data but clear for demonstration.
sum_sq = 0
# Iterate over the index to find terms belonging to this doc
# (In a real engine, we'd have a forward index or stored vector)
for term, postings in self.inverted_index.items():
if doc_id in postings:
tf = postings[doc_id]
idf = self._calculate_idf(term)
weight = tf * idf
sum_sq += weight ** 2
return math.sqrt(sum_sq) if sum_sq > 0 else 0
def search(self, query, top_n=3):
"""
Searches the index using TF-IDF and Cosine Similarity.
"""
query_tokens = self._tokenize(query)
if not query_tokens:
return []
# 1. Calculate Query Vector weights (TF-IDF)
query_tf = Counter(query_tokens)
query_weights = {}
for term, tf in query_tf.items():
idf = self._calculate_idf(term)
query_weights[term] = tf * idf
# Calculate Query Magnitude
query_mag = math.sqrt(sum(w**2 for w in query_weights.values()))
if query_mag == 0:
return []
# 2. Identify Candidate Documents
# Only documents that contain at least one query term are relevant
candidate_docs = set()
for term in query_tokens:
if term in self.inverted_index:
candidate_docs.update(self.inverted_index[term].keys())
# 3. Calculate Cosine Similarity
scores = []
for doc_id in candidate_docs:
dot_product = 0
# Calculate Dot Product
for term, q_weight in query_weights.items():
if term in self.inverted_index and doc_id in self.inverted_index[term]:
d_tf = self.inverted_index[term][doc_id]
d_idf = self._calculate_idf(term) # Same as query IDF
d_weight = d_tf * d_idf
dot_product += q_weight * d_weight
# Calculate Document Magnitude
doc_mag = self._get_doc_vector_magnitude(doc_id)
# Cosine Similarity
if doc_mag > 0:
cosine_score = dot_product / (query_mag * doc_mag)
scores.append((doc_id, cosine_score))
# 4. Rank and Return
scores.sort(key=lambda x: x[1], reverse=True)
# Return top N results with text snippet
results = []
for doc_id, score in scores[:top_n]:
results.append({
"id": doc_id,
"score": round(score, 4),
"text": self.documents[doc_id][:100] + "..." # snippet
})
return results
# --- Usage Example ---
if __name__ == "__main__":
engine = SearchEngine()
# 1. Indexing Phase
print("Indexing documents...")
engine.index(1, "The cat sat on the mat.")
engine.index(2, "The dog played in the park.")
engine.index(3, "Cats and dogs are great pets.")
engine.index(4, "My cat is black and the dog is brown.")
engine.index(5, "Python programming is fun.") # Irrelevant doc
# 2. Search Phase
print("\nSearch Results for 'cat dog':")
results = engine.search("cat dog")
for res in results:
print(f"ID: {res['id']} | Score: {res['score']} | Text: {res['text']}")