High Performance Parallel Search Engine
Project Demo Link
Table of Contents
Core Components
1. Main (main.c)
- The entry point that handles command-line arguments and coordinates program flow
- Supports multiple operation modes:
-u URL: Download and index content from a single URL
-c URL: Crawl website starting from URL (follows links)
-m USER: Crawl Medium profile for a specific user
-d NUM: Maximum crawl depth (default: 2)
-p NUM: Maximum pages to crawl (default: 10)
- Once content is downloaded/crawled, it builds an index and accepts search queries
2. Crawler (crawler.c)
- Handles website crawling and content extraction using libcurl
- Uses breadth-first search to navigate web pages up to a specified depth
- Key functionalities:
crawl_website(): Main crawling function that manages the BFS queue
download_url(): Downloads content from a URL
normalize_url(): Cleans URLs to avoid duplicates
extract_links(): Parses HTML to find linked pages
- HTML content extraction with special handling for Medium.com articles
3. Parser (parser.c)
- Processes downloaded documents and prepares them for indexing
- Functions include:
parse_file(): Reads file content and initiates tokenization
tokenize(): Splits text into individual words/tokens
to_lowercase(): Converts tokens to lowercase for case-insensitive search
- Removes stopwords using the
is_stopword() function
- Performs stemming with the
stem() function to normalize word variations
4. Index (index.c)
- Manages the inverted index data structure
- Key components:
InvertedIndex struct: Stores terms and their document postings
Document struct: Stores document information
build_index(): Processes all files in the dataset directory
add_token(): Adds a token to the inverted index
get_doc_length(), get_doc_count(), get_doc_filename(): Utility functions
5. Ranking (ranking.c)
- Implements the BM25 algorithm for relevance-based ranking
- Key components:
rank_bm25(): Performs query processing using BM25 formula
- BM25 parameters (k1=1.5, b=0.75) for term frequency normalization
- Uses an inverted index to efficiently find matching documents
6. Metrics (metrics.c)
- Collects and reports performance metrics:
- Execution time (crawling, parsing, tokenizing, indexing, etc.)
- Memory usage
- Document statistics
- Query latency
- Provides functions to save metrics to CSV files for benchmarking
7. Benchmark & Evaluation (benchmark.c, evaluate.c)
- evaluate.c: Tests search quality with sample queries
- benchmark.c: Tools for performance measurement and comparison
Data Flow & Processing Logic
Web Crawling Process:
- Starts with a seed URL and performs breadth-first traversal
- For each URL:
- Checks if already visited using
has_visited()
- Downloads content with libcurl
- Extracts clean text from HTML
- Extracts links for further crawling
- Saves content to the dataset directory with meaningful filenames
Indexing Process:
- Reads all files in the dataset directory
- For each file:
- Parses content into tokens
- Removes stopwords
- Applies stemming
- Adds tokens to inverted index with document frequencies
Search Process:
- Tokenizes the search query
- Removes stopwords and applies stemming
- For each token:
- Finds matching documents in the inverted index
- Calculates BM25 scores based on term frequency and document length
- Sorts documents by their accumulated scores
- Returns the top-k results
BM25 Ranking:
- Score = IDF × ((tf × (k1 + 1)) / (tf + k1 × (1 - b + b × dl / avgdl)))
- Where:
- IDF: Inverse document frequency
- tf: Term frequency in document
- dl: Document length
- avgdl: Average document length
- k1=1.5, b=0.75: Tuning parameters
Special Features
Medium.com Optimization:
- Custom URL handling for Medium profiles
- Better article extraction with special handling for Medium markup
- Rate-limiting between requests to prevent being blocked
URL Normalization:
- Removes tracking parameters (utm_, fbclid, etc.)
- Handles relative URLs properly
- Prevents duplicate crawling of the same content
HTML Content Extraction:
- Removes HTML tags, scripts, styles
- Preserves meaningful headings and paragraphs
- Converts HTML entities to proper characters
- Outputs in a clean text format suitable for searching
Performance Considerations
The serial implementation has several performance bottlenecks:
- Sequential web crawling - can't download pages in parallel
- Sequential document parsing and indexing
- No parallel query processing
- In-memory index with size limitations
Parallelized Components
1. Index Building (index.c)
- Building the index from multiple files
Why parallelized:
- File processing is an embarrassingly parallel task - each file can be processed independently
- Document parsing is I/O and CPU intensive
- No dependencies between documents during initial parsing
Critical sections:
- This section protects the shared
documents array from race conditions when multiple threads update it concurrently
2. Term Indexing and Document Length Updates
- Adding a token to the index (called during parsing)
Why parallelized:
- Uses OpenMP locks instead of critical sections for finer-grained control
- Two separate locks for different shared resources (index and document lengths)
Critical points:
- The inverted index structure is a shared resource - requires synchronization
- Document length tracking needs protection from concurrent updates
3. Web Crawling (crawler.c)
- URL extraction and processing
Why parallelized:
- HTML parsing is computationally expensive
- Extracting links from different sections of HTML can be done in parallel
- Link extraction doesn't modify the original HTML content
Critical sections:
- URL queue management needs protection to prevent corruption of the queue data structure
4. BM25 Ranking (ranking.c)
- Score calculation for search results
Why parallelized:
- BM25 score calculation for each document is independent
- Query processing is often a bottleneck in search engines
- Score calculations involve floating-point operations that benefit from parallel execution
Critical section:
- Score accumulation in the results array needs protection to prevent race conditions
5. Term Search (index.c)
- Parallel search for terms in the index Process results...
Why parallelized:
- Term matching across a large index is computationally expensive
- First-match semantics are preserved with the critical section
- Multiple threads can search different parts of the index simultaneously
Critical point:
- Updating the
found variable needs synchronization to ensure only the first match is recorded
6. Index Clearing and Initialization
- Clear the index for rebuilding
Why parallelized:
- Different memory areas can be initialized independently
- Memory operations benefit from parallel execution
- Parallel sections allow different threads to handle different initialization tasks
Non-Parallelized Components and Rationale
1. Index Structure Management
The core index structure manipulation is protected by locks but not fully parallelized because:
- The inverted index has complex dependencies between terms
- The structure has inherent sequential nature for insertion and lookup
- It's more efficient to use fine-grained locks than to attempt full parallelization
2. Parser Initialization
This function is not parallelized internally because:
- File operations are primarily I/O bound
- The parallelism happens at a higher level (multiple files processed in parallel)
- The overhead of parallelizing small operations would outweigh benefits
3. URL Normalization
URL normalization remains sequential because:
- It's a relatively lightweight string manipulation operation
- Has internal dependencies within a single URL
- Parallelizing would introduce overhead for minimal benefit
Critical Points in OpenMP Implementation
1. OpenMP Lock Initialization
These functions properly initialize and clean up OpenMP locks, which is critical for correct program behavior.
2. Thread Count Management
These settings are critical for:
- Allowing user control over parallelism
- Ensuring consistent thread allocation
- Supporting nested parallel regions
3. Load Balancing
The choice of dynamic scheduling is critical for:
- Balancing workloads across threads
- Adapting to varying processing times for different files/URLs
- Improving overall parallel efficiency
4. Thread-Safe Metrics Collection
This ensures that metrics collection doesn't interfere with the parallel execution and provides accurate performance data.
5. Data Structure Protection
Various OpenMP critical sections and locks protect shared data structures:
- Inverted index structure
- Document length arrays
- URL queue for crawling
- Search results accumulation
Performance Considerations
Granularity of Parallelism:
- File-level parallelism is coarse-grained (good for reducing overhead)
- Term processing parallelism is medium-grained
- HTML chunk processing is fine-grained with dynamic scheduling
Synchronization Overhead:
- Locks and critical sections introduce overhead
- The implementation balances parallelism with synchronization costs
- Uses separate locks for different resources to reduce contention
Load Balancing:
- Dynamic scheduling helps with varying document sizes
- Thread status reporting shows distribution of work
- Thread activation tracking prevents idle threads
Memory Considerations:
- Each thread has private variables to avoid false sharing
- Shared memory structures are protected with appropriate synchronization
- Memory operations like memset are parallelized where beneficial
Summary of Key Parallelization Strategies
- Document-Level Parallelism: Multiple documents processed concurrently
- Token-Level Synchronization: Fine-grained locks for index updates
- URL Processing Parallelism: Concurrent extraction of links from HTML
- Query Processing Parallelism: Parallel BM25 score calculation
- Critical Section Management: Targeted protection of shared resources
- Load Balancing: Dynamic scheduling for varying workloads
The inverted index maps terms to documents containing those terms, with frequency information. For each term, there's an IndexEntry containing:
- The term itself
- A list of
Posting structures (documents containing that term)
- Each posting includes the document ID and the term's frequency in that document
Serial vs. Parallel Indexing Process
Serial Version
In the serial version, indexing happens sequentially:
- Process one document at a time