The user wants a full-text search engine with relevance ranking. This is a complex system that needs:
-
Core Components:
- Document storage/indexing
- Tokenization and text processing
- Inverted index for fast lookups
- TF-IDF or BM25 ranking algorithm
- Query parsing and execution
- Search results with relevance scores
-
UI Elements Needed:
- Search input field
- Results display with relevance scores
- Document viewer
- Index statistics/visualization
- Sample documents to search through
-
Features to implement:
- Text tokenization (splitting, lowercasing, stemming)
- Stop word removal
- Inverted index construction
- TF-IDF scoring
- BM25 ranking (better than basic TF-IDF)
- Phrase search support
- Boolean operators (AND, OR, NOT)
- Highlighting matched terms
- Real-time search as you type
-
Design approach:
- Technical/professional look (this is a developer tool)
- Dark theme with accent colors
- Clean data visualization
- Smooth animations
- Interactive elements showing how the engine works
Let me create a sophisticated single-page search engine demo with:
- Built-in sample documents
- Real inverted index
- BM25 relevance ranking
- Term highlighting
- Search statistics
- Visual index explorer
I'll use a professional dark theme with cyan/teal accents for that "technical" feel.
Full-Text Search Engine with Relevance Ranking
I'll create a sophisticated full-text search engine featuring:
- BM25 relevance ranking algorithm (industry standard)
- Inverted index for fast lookups
- Tokenization & stemming for better matching
- Term highlighting in results
- Real-time search with statistics
- Index visualization to understand how it works
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Full-Text Search Engine</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--bg-primary: #0a0e14;
--bg-secondary: #111820;
--bg-tertiary: #1a222d;
--accent: #00d4aa;
--accent-dim: rgba(0, 212, 170, 0.15);
--accent-glow: rgba(0, 212, 170, 0.4);
--text-primary: #e6edf3;
--text-secondary: #8b949e;
--text-muted: #484f58;
--border: #30363d;
--highlight: #ffd700;
--warning: #f0883e;
--info: #58a6ff;
}
body {
font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
min-height: 100vh;
overflow-x: hidden;
}
/* Animated background */
.bg-grid {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image:
linear-gradient(rgba(0, 212, 170, 0.03) 1px, transparent 1px),
linear-gradient(90deg, rgba(0, 212, 170, 0.03) 1px, transparent 1px);
background-size: 50px 50px;
pointer-events: none;
z-index: 0;
}
.container {
position: relative;
z-index: 1;
max-width: 1400px;
margin: 0 auto;
padding: 20px;
}
header {
text-align: center;
padding: 40px 0;
}
h1 {
font-size: 2.8rem;
font-weight: 700;
background: linear-gradient(135deg, var(--accent), #00ff88);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin-bottom: 10px;
letter-spacing: -1px;
}
.subtitle {
color: var(--text-secondary);
font-size: 1.1rem;
}
/* Search Section */
.search-section {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 16px;
padding: 30px;
margin-bottom: 30px;
position: relative;
overflow: hidden;
}
.search-section::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 2px;
background: linear-gradient(90deg, transparent, var(--accent), transparent);
}
.search-box {
display: flex;
gap: 15px;
margin-bottom: 20px;
}
.search-input-wrapper {
flex: 1;
position: relative;
}
.search-input {
width: 100%;
padding: 18px 20px 18px 50px;
font-size: 1.1rem;
background: var(--bg-tertiary);
border: 2px solid var(--border);
border-radius: 12px;
color: var(--text-primary);
transition: all 0.3s ease;
}
.search-input:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 20px var(--accent-glow);
}
.search-icon {
position: absolute;
left: 18px;
top: 50%;
transform: translateY(-50%);
color: var(--text-muted);
font-size: 1.2rem;
}
.search-btn {
padding: 18px 35px;
font-size: 1rem;
font-weight: 600;
background: linear-gradient(135deg, var(--accent), #00ff88);
color: var(--bg-primary);
border: none;
border-radius: 12px;
cursor: pointer;
transition: all 0.3s ease;
}
.search-btn:hover {
transform: translateY(-2px);
box-shadow: 0 10px 30px var(--accent-glow);
}
/* Search Options */
.search-options {
display: flex;
gap: 20px;
flex-wrap: wrap;
align-items: center;
}
.option-group {
display: flex;
align-items: center;
gap: 8px;
}
.option-label {
color: var(--text-secondary);
font-size: 0.9rem;
}
.option-select {
padding: 8px 15px;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text-primary);
cursor: pointer;
}
.checkbox-wrapper {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
}
.checkbox-wrapper input {
accent-color: var(--accent);
width: 16px;
height: 16px;
}
/* Stats Bar */
.stats-bar {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin-bottom: 30px;
}
.stat-card {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 12px;
padding: 20px;
text-align: center;
transition: all 0.3s ease;
}
.stat-card:hover {
border-color: var(--accent);
transform: translateY(-3px);
}
.stat-value {
font-size: 2rem;
font-weight: 700;
color: var(--accent);
margin-bottom: 5px;
}
.stat-label {
color: var(--text-secondary);
font-size: 0.85rem;
text-transform: uppercase;
letter-spacing: 1px;
}
/* Main Content */
.main-content {
display: grid;
grid-template-columns: 1fr 350px;
gap: 25px;
}
@media (max-width: 1100px) {
.main-content {
grid-template-columns: 1fr;
}
}
/* Results Section */
.results-section {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 16px;
overflow: hidden;
}
.results-header {
padding: 20px 25px;
border-bottom: 1px solid var(--border);
display: flex;
justify-content: space-between;
align-items: center;
}
.results-title {
font-size: 1.2rem;
font-weight: 600;
}
.results-count {
color: var(--text-secondary);
font-size: 0.9rem;
}
.results-list {
max-height: 600px;
overflow-y: auto;
}
.result-item {
padding: 20px 25px;
border-bottom: 1px solid var(--border);
cursor: pointer;
transition: all 0.2s ease;
animation: slideIn 0.3s ease;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateX(-20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
.result-item:hover {
background: var(--bg-tertiary);
}
.result-item:last-child {
border-bottom: none;
}
.result-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 10px;
}
.result-title {
font-size: 1.1rem;
font-weight: 600;
color: var(--info);
}
.result-score {
background: var(--accent-dim);
color: var(--accent);
padding: 4px 12px;
border-radius: 20px;
font-size: 0.8rem;
font-weight: 600;
white-space: nowrap;
}
.result-excerpt {
color: var(--text-secondary);
font-size: 0.95rem;
line-height: 1.6;
margin-bottom: 12px;
}
.result-excerpt mark {
background: rgba(255, 215, 0, 0.3);
color: var(--highlight);
padding: 1px 4px;
border-radius: 3px;
}
.result-meta {
display: flex;
gap: 15px;
font-size: 0.8rem;
color: var(--text-muted);
}
.result-meta span {
display: flex;
align-items: center;
gap: 5px;
}
/* Sidebar */
.sidebar {
display: flex;
flex-direction: column;
gap: 20px;
}
.panel {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 16px;
overflow: hidden;
}
.panel-header {
padding: 15px 20px;
border-bottom: 1px solid var(--border);
font-weight: 600;
display: flex;
align-items: center;
gap: 10px;
}
.panel-icon {
color: var(--accent);
}
.panel-content {
padding: 15px 20px;
}
/* Index Visualization */
.index-viz {
max-height: 300px;
overflow-y: auto;
}
.index-term {
margin-bottom: 12px;
animation: fadeIn 0.3s ease;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.index-term-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 6px;
}
.term-name {
font-family: 'Consolas', 'Monaco', monospace;
color: var(--accent);
font-size: 0.9rem;
}
.term-df {
color: var(--text-muted);
font-size: 0.75rem;
}
.term-bar {
height: 4px;
background: var(--bg-tertiary);
border-radius: 2px;
overflow: hidden;
}
.term-bar-fill {
height: 100%;
background: linear-gradient(90deg, var(--accent), #00ff88);
transition: width 0.5s ease;
}
/* Query Analysis */
.query-analysis {
font-family: 'Consolas', 'Monaco', monospace;
font-size: 0.85rem;
}
.analysis-item {
padding: 8px 0;
border-bottom: 1px solid var(--border);
}
.analysis-item:last-child {
border-bottom: none;
}
.analysis-label {
color: var(--text-muted);
font-size: 0.75rem;
text-transform: uppercase;
margin-bottom: 4px;
}
.analysis-value {
color: var(--text-primary);
}
.analysis-value .token {
display: inline-block;
background: var(--accent-dim);
color: var(--accent);
padding: 2px 8px;
border-radius: 4px;
margin: 2px;
}
/* Algorithm Explanation */
.algo-panel {
font-size: 0.9rem;
line-height: 1.6;
}
.algo-formula {
background: var(--bg-tertiary);
padding: 15px;
border-radius: 8px;
font-family: 'Consolas', 'Monaco', monospace;
font-size: 0.8rem;
color: var(--accent);
margin: 10px 0;
overflow-x: auto;
}
.algo-text {
color: var(--text-secondary);
}
/* No Results */
.no-results {
padding: 60px 20px;
text-align: center;
color: var(--text-secondary);
}
.no-results-icon {
font-size: 3rem;
margin-bottom: 15px;
opacity: 0.5;
}
/* Loading */
.loading {
padding: 40px;
text-align: center;
}
.spinner {
width: 40px;
height: 40px;
border: 3px solid var(--border);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 15px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* Document Modal */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
backdrop-filter: blur(5px);
z-index: 1000;
display: none;
justify-content: center;
align-items: center;
animation: fadeIn 0.2s ease;
}
.modal-overlay.active {
display: flex;
}
.modal {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 16px;
width: 90%;
max-width: 800px;
max-height: 80vh;
overflow: hidden;
animation: modalSlide 0.3s ease;
}
@keyframes modalSlide {
from {
opacity: 0;
transform: scale(0.9) translateY(20px);
}
to {
opacity: 1;
transform: scale(1) translateY(0);
}
}
.modal-header {
padding: 20px 25px;
border-bottom: 1px solid var(--border);
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-title {
font-size: 1.3rem;
font-weight: 600;
}
.modal-close {
background: none;
border: none;
color: var(--text-secondary);
font-size: 1.5rem;
cursor: pointer;
transition: color 0.2s;
}
.modal-close:hover {
color: var(--text-primary);
}
.modal-body {
padding: 25px;
overflow-y: auto;
max-height: calc(80vh - 80px);
line-height: 1.8;
color: var(--text-secondary);
}
.modal-body mark {
background: rgba(255, 215, 0, 0.3);
color: var(--highlight);
padding: 1px 4px;
border-radius: 3px;
}
.modal-meta {
margin-top: 20px;
padding-top: 20px;
border-top: 1px solid var(--border);
display: flex;
gap: 20px;
font-size: 0.85rem;
color: var(--text-muted);
}
/* Scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg-tertiary);
}
::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-muted);
}
/* Help Tips */
.help-tip {
font-size: 0.8rem;
color: var(--text-muted);
margin-top: 10px;
}
.help-tip code {
background: var(--bg-tertiary);
padding: 2px 6px;
border-radius: 4px;
font-family: 'Consolas', monospace;
color: var(--info);
}
</style>
</head>
<body>
<div class="bg-grid"></div>
<div class="container">
<header>
<h1>Full-Text Search Engine</h1>
<p class="subtitle">BM25 Relevance Ranking with Inverted Index</p>
</header>
<section class="search-section">
<div class="search-box">
<div class="search-input-wrapper">
<span class="search-icon">🔍</span>
<input type="text" class="search-input" id="searchInput"
placeholder="Enter your search query..." autocomplete="off">
</div>
<button class="search-btn" id="searchBtn">Search</button>
</div>
<div class="search-options">
<div class="option-group">
<span class="option-label">Results:</span>
<select class="option-select" id="limitSelect">
<option value="5">5</option>
<option value="10" selected>10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
</div>
<div class="option-group">
<label class="checkbox-wrapper">
<input type="checkbox" id="highlightCheck" checked>
<span class="option-label">Highlight terms</span>
</label>
</div>
<div class="option-group">
<label class="checkbox-wrapper">
<input type="checkbox" id="realtimeCheck" checked>
<span class="option-label">Real-time search</span>
</label>
</div>
</div>
<div class="help-tip">
<strong>Tips:</strong> Use <code>"exact phrase"</code> for phrase search,
<code>-term</code> to exclude, <code>term1 OR term2</code> for boolean OR
</div>
</section>
<div class="stats-bar" id="statsBar">
<div class="stat-card">
<div class="stat-value" id="statDocs">0</div>
<div class="stat-label">Documents</div>
</div>
<div class="stat-card">
<div class="stat-value" id="statTerms">0</div>
<div class="stat-label">Unique Terms</div>
</div>
<div class="stat-card">
<div class="stat-value" id="statAvgLen">0</div>
<div class="stat-label">Avg Doc Length</div>
</div>
<div class="stat-card">
<div class="stat-value" id="statSearchTime">0ms</div>
<div class="stat-label">Search Time</div>
</div>
</div>
<div class="main-content">
<div class="results-section">
<div class="results-header">
<span class="results-title">Search Results</span>
<span class="results-count" id="resultsCount">Enter a query to search</span>
</div>
<div class="results-list" id="resultsList">
<div class="no-results">
<div class="no-results-icon">🔎</div>
<p>Start typing to search through documents</p>
</div>
</div>
</div>
<div class="sidebar">
<div class="panel">
<div class="panel-header">
<span class="panel-icon">📊</span>
Query Analysis
</div>
<div class="panel-content query-analysis" id="queryAnalysis">
<div class="analysis-item">
<div class="analysis-label">Query</div>
<div class="analysis-value">-</div>
</div>
</div>
</div>
<div class="panel">
<div class="panel-header">
<span class="panel-icon">🗂️</span>
Index Browser
</div>
<div class="panel-content index-viz" id="indexViz">
<p style="color: var(--text-muted); font-size: 0.9rem;">
Search to see matching index terms
</p>
</div>
</div>
<div class="panel">
<div class="panel-header">
<span class="panel-icon">📐</span>
BM25 Algorithm
</div>
<div class="panel-content algo-panel">
<div class="algo-formula">
score(D,Q) = Σ IDF(qi) × (f(qi,D) × (k1+1)) / (f(qi,D) + k1 × (1-b+b×|D|/avgdl))
</div>
<p class="algo-text">
BM25 ranks documents by term frequency (TF) and inverse document frequency (IDF),
with saturation to prevent term spam. Parameters: k1=1.2, b=0.75
</p>
</div>
</div>
</div>
</div>
</div>
<!-- Document Modal -->
<div class="modal-overlay" id="modalOverlay">
<div class="modal">
<div class="modal-header">
<span class="modal-title" id="modalTitle">Document</span>
<button class="modal-close" id="modalClose">×</button>
</div>
<div class="modal-body" id="modalBody"></div>
</div>
</div>
<script>
// Sample documents corpus
const documents = [
{
id: 1,
title: "Introduction to Machine Learning",
category: "Technology",
author: "Dr. Sarah Chen",
date: "2024-01-15",
content: `Machine learning is a subset of artificial intelligence that enables systems to learn and improve from experience without being explicitly programmed. It focuses on developing computer programs that can access data and use it to learn for themselves. The process begins with observations or data, such as examples, direct experience, or instruction, to look for patterns in data and make better decisions in the future based on the examples provided. The primary aim is to allow computers to learn automatically without human intervention or assistance and adjust actions accordingly. Machine learning algorithms are often categorized into supervised learning, unsupervised learning, and reinforcement learning approaches.`
},
{
id: 2,
title: "Deep Learning Neural Networks Explained",
category: "Technology",
author: "Prof. James Liu",
date: "2024-02-20",
content: `Deep learning is a subset of machine learning that uses neural networks with many layers to analyze various factors of data. A neural network is a series of algorithms that endeavors to recognize underlying relationships in a set of data through a process that mimics the way the human brain operates. Neural networks consist of input layers, hidden layers, and output layers. Each node in the network processes input data and passes its output to subsequent layers. Deep learning has revolutionized image recognition, natural language processing, and speech recognition. Popular deep learning frameworks include TensorFlow, PyTorch, and Keras.`
},
{
id: 3,
title: "Natural Language Processing Fundamentals",
category: "AI",
author: "Dr. Emily Watson",
date: "2024-01-28",
content: `Natural Language Processing (NLP) is a branch of artificial intelligence that helps computers understand, interpret, and manipulate human language. NLP draws from many disciplines, including computer science and computational linguistics, in its pursuit to fill the gap between human communication and computer understanding. Key NLP tasks include tokenization, part-of-speech tagging, named entity recognition, sentiment analysis, and machine translation. Modern NLP heavily relies on deep learning models like transformers, BERT, and GPT. These models have achieved remarkable results in text classification, question answering, and text generation tasks.`
},
{
id: 4,
title: "Data Science and Analytics Guide",
category: "Data",
author: "Michael Roberts",
date: "2024-03-05",
content: `Data science combines statistics, mathematics, and computer science to extract insights from structured and unstructured data. Data scientists use various techniques including data mining, machine learning, and big data analytics. The data science process involves data collection, cleaning, exploration, modeling, and interpretation. Key tools in data science include Python, R, SQL, and various visualization libraries. Data analytics focuses on processing and analyzing datasets to find patterns and trends. Business intelligence relies heavily on data analytics for decision making and strategic planning.`
},
{
id: 5,
title: "Search Engine Architecture Design",
category: "Technology",
author: "Alex Thompson",
date: "2024-02-10",
content: `Search engines use complex algorithms to retrieve and rank information from massive datasets. The core components include crawling, indexing, and query processing. An inverted index maps terms to documents, enabling fast full-text search. Ranking algorithms like BM25 and TF-IDF determine relevance scores for search results. Modern search engines incorporate machine learning for query understanding and result personalization. Elasticsearch and Apache Solr are popular open-source search platforms. They provide distributed search, real-time indexing, and advanced text analysis capabilities.`
},
{
id: 6,
title: "Understanding Database Indexing",
category: "Database",
author: "Lisa Chen",
date: "2024-03-12",
content: `Database indexing is a data structure technique to improve query performance. Indexes create additional references to table data, allowing faster retrieval without scanning entire tables. Common index types include B-tree indexes, hash indexes, and full-text indexes. B-tree indexes are ideal for range queries and sorted data access. Full-text indexes enable efficient text search within large document collections. Over-indexing can slow down write operations, so index design requires careful balance between read and write performance. Database query optimizers use statistics to choose optimal index strategies.`
},
{
id: 7,
title: "Information Retrieval Theory",
category: "Theory",
author: "Dr. Robert Kim",
date: "2024-01-20",
content: `Information retrieval is the science of searching for documents, information within documents, and metadata about documents. The vector space model represents documents and queries as vectors in high-dimensional space. Cosine similarity measures the angle between query and document vectors. Probabilistic models estimate the probability of relevance given a query and document. Evaluation metrics like precision, recall, and F1-score measure retrieval effectiveness. Mean Average Precision (MAP) and Normalized Discounted Cumulative Gain (NDCG) are standard evaluation measures for ranking quality in information retrieval systems.`
},
{
id: 8,
title: "Text Mining and Analysis Techniques",
category: "Analytics",
author: "Jennifer Park",
date: "2024-02-28",
content: `Text mining extracts meaningful information from unstructured text data. Common techniques include text classification, clustering, and entity extraction. Text preprocessing involves tokenization, stemming, lemmatization, and stop word removal. Term frequency analysis identifies important terms within documents. Topic modeling algorithms like LDA discover hidden thematic structures in document collections. Sentiment analysis determines emotional tone in text data. Named entity recognition identifies people, organizations, and locations mentioned in text. These techniques power applications from customer feedback analysis to news categorization.`
},
{
id: 9,
title: "Web Search and SEO Fundamentals",
category: "Web",
author: "David Miller",
date: "2024-03-18",
content: `Web search engines like Google use sophisticated algorithms to rank web pages. PageRank algorithm measures page importance based on link structure. Search engine optimization improves website visibility in organic search results. Key SEO factors include content relevance, page speed, mobile-friendliness, and backlink quality. Semantic search understands query intent beyond keyword matching. Featured snippets and knowledge panels provide direct answers in search results. Voice search and mobile-first indexing have changed SEO strategies significantly. Modern SEO requires technical optimization, quality content, and user experience focus.`
},
{
id: 10,
title: "Artificial Intelligence Applications",
category: "AI",
author: "Dr. Amanda Foster",
date: "2024-01-05",
content: `Artificial intelligence applications span numerous industries and use cases. Computer vision enables image recognition, object detection, and video analysis. Speech recognition powers virtual assistants and voice-controlled devices. Recommendation systems suggest products, content, and connections based on user behavior. Autonomous vehicles combine computer vision, sensor fusion, and decision-making algorithms. Healthcare AI assists in diagnosis, drug discovery, and patient monitoring. Financial AI enables fraud detection, algorithmic trading, and credit scoring. Game-playing AI has defeated human champions in chess, Go, and complex video games.`
},
{
id: 11,
title: "Big Data Processing with MapReduce",
category: "Big Data",
author: "Chris Anderson",
date: "2024-02-15",
content: `MapReduce is a programming model for processing large datasets in parallel across distributed clusters. The map function transforms input data into intermediate key-value pairs. The reduce function merges intermediate values associated with the same key. Hadoop implements MapReduce for scalable data processing on commodity hardware. Apache Spark provides faster in-memory processing for big data analytics. Data processing pipelines often combine batch processing with streaming for real-time insights. Large-scale text processing uses MapReduce for building inverted indexes and computing term statistics across massive document collections.`
},
{
id: 12,
title: "Cloud Computing and Distributed Systems",
category: "Cloud",
author: "Rachel Green",
date: "2024-03-22",
content: `Cloud computing provides on-demand computing resources over the internet. Infrastructure as a Service offers virtual machines, storage, and networking. Platform as a Service provides development and deployment environments. Software as a Service delivers applications through web browsers. Distributed systems coordinate multiple computers to achieve common goals. Consistency, availability, and partition tolerance present fundamental trade-offs in distributed systems. Load balancing distributes traffic across multiple servers for scalability. Microservices architecture decomposes applications into small, independent services.`
},
{
id: 13,
title: "Python Programming for Data Analysis",
category: "Programming",
author: "Kevin Zhang",
date: "2024-01-25",
content: `Python is the leading programming language for data analysis and machine learning. NumPy provides efficient numerical computing with multi-dimensional arrays. Pandas offers data structures and tools for data manipulation and analysis. Matplotlib and Seaborn create publication-quality visualizations. Scikit-learn implements machine learning algorithms with consistent APIs. Jupyter notebooks enable interactive data exploration and visualization. Python libraries for NLP include NLTK, spaCy, and Hugging Face transformers. The Python ecosystem supports end-to-end data science workflows from data collection to model deployment.`
},
{
id: 14,
title: "Elasticsearch in Production",
category: "Technology",
author: "Thomas Wright",
date: "2024-02-05",
content: `Elasticsearch is a distributed search and analytics engine built on Apache Lucene. It provides full-text search, analytics, and visualization capabilities. Documents are stored in indices as JSON objects and are searchable in near real-time. Elasticsearch uses inverted indices for fast full-text search performance. Cluster architecture supports horizontal scaling and high availability. Sharding distributes data across multiple nodes for parallel processing. Replication provides data redundancy and failover protection. The Query DSL enables complex searches combining filters, full-text queries, and aggregations.`
},
{
id: 15,
title: "Computer Vision and Image Recognition",
category: "AI",
author: "Dr. Maria Santos",
date: "2024-03-08",
content: `Computer vision enables machines to interpret and understand visual information. Convolutional neural networks revolutionized image classification and object detection. Image recognition identifies objects, people, and scenes in images. Object detection locates and classifies multiple objects within images. Semantic segmentation assigns class labels to each pixel in an image. Pre-trained models like ResNet, VGG, and YOLO enable transfer learning for vision tasks. Applications include facial recognition, medical imaging, autonomous vehicles, and augmented reality. Image augmentation techniques improve model generalization on limited training data.`
}
];
// Stop words for filtering
const STOP_WORDS = new Set([
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from',
'has', 'he', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the',
'to', 'was', 'were', 'will', 'with', 'the', 'this', 'but', 'they',
'have', 'had', 'what', 'when', 'where', 'who', 'which', 'why', 'how',
'all', 'each', 'every', 'both', 'few', 'more', 'most', 'other', 'some',
'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too',
'very', 'can', 'just', 'should', 'now', 'or', 'their', 'them', 'then',
'there', 'these', 'those', 'through', 'also', 'into', 'over', 'after',
'before', 'between', 'under', 'again', 'further', 'once', 'here', 'any'
]);
// Simple stemmer (Porter-like rules simplified)
function stem(word) {
if (word.length < 3) return word;
// Common suffix removal
const suffixes = [
['ational', 'ate'], ['tional', 'tion'], ['enci', 'ence'],
['anci', 'ance'], ['izer', 'ize'], ['isation', 'ize'],
['ization', 'ize'], ['ation', 'ate'], ['ator', 'ate'],
['alism', 'al'], ['iveness', 'ive'], ['fulness', 'ful'],
['ousness', 'ous'], ['aliti', 'al'], ['iviti', 'ive'],
['biliti', 'ble'], ['alli', 'al'], ['entli', 'ent'],
['eli', 'e'], ['ousli', 'ous'], ['ling', 'l'],
['ies', 'y'], ['ied', 'y'], ['ing', ''], ['ed', ''],
['ness', ''], ['ment', ''], ['able', ''], ['ible', ''],
['ly', ''], ['er', ''], ['est', ''], ['s', '']
];
for (const [suffix, replacement] of suffixes) {
if (word.endsWith(suffix) && word.length - suffix.length >= 2) {
return word.slice(0, -suffix.length) + replacement;
}
}
return word;
}
// Tokenizer
function tokenize(text) {
return text.toLowerCase()
.replace(/[^\w\s]/g, ' ')
.split(/\s+/)
.filter(token => token.length > 1 && !STOP_WORDS.has(token));
}
// Process tokens with stemming
function processTokens(tokens) {
return tokens.map(stem);
}
// Search Engine Class
class SearchEngine {
constructor() {
this.documents = new Map();
this.invertedIndex = new Map();
this.documentLengths = new Map();
this.avgDocLength = 0;
this.totalDocs = 0;
this.k1 = 1.2; // BM25 parameter
this.b = 0.75; // BM25 parameter
}
// Add document to index
addDocument(doc) {
this.documents.set(doc.id, doc);
// Get all text content
const fullText = `${doc.title} ${doc.category} ${doc.content}`;
const tokens = processTokens(tokenize(fullText));
// Store document length
this.documentLengths.set(doc.id, tokens.length);
// Build term frequency map for this document
const termFreq = new Map();
for (const token of tokens) {
termFreq.set(token, (termFreq.get(token) || 0) + 1);
}
// Update inverted index
for (const [term, freq] of termFreq) {
if (!this.invertedIndex.has(term)) {
this.invertedIndex.set(term, new Map());
}
this.invertedIndex.get(term).set(doc.id, freq);
}
this.totalDocs++;
}
// Finalize index (calculate avg doc length)
finalize() {
let totalLength = 0;
for (const length of this.documentLengths.values()) {
totalLength += length;
}
this.avgDocLength = totalLength / this.totalDocs;
}
// Calculate IDF (Inverse Document Frequency)
calculateIDF(term) {
const postings = this.invertedIndex.get(term);
if (!postings) return 0;
const df = postings.size;
// BM25 IDF formula
return Math.log((this.totalDocs - df + 0.5) / (df + 0.5) + 1);
}
// Calculate BM25 score
calculateBM25(queryTerms, docId) {
let score = 0;
const docLength = this.documentLengths.get(docId) || 0;
for (const term of queryTerms) {
const postings = this.invertedIndex.get(term);
if (!postings || !postings.has(docId)) continue;
const tf = postings.get(docId);
const idf = this.calculateIDF(term);
// BM25 term frequency saturation
const tfComponent = (tf * (this.k1 + 1)) /
(tf + this.k1 * (1 - this.b + this.b * (docLength / this.avgDocLength)));
score += idf * tfComponent;
}
return score;
}
// Parse query for advanced search
parseQuery(query) {
const result = {
terms: [],
phrases: [],
excluded: [],
operators: []
};
// Extract phrases
const phraseRegex = /"([^"]+)"/g;
let match;
while ((match = phraseRegex.exec(query)) !== null) {
result.phrases.push(processTokens(tokenize(match[1])));
}
query = query.replace(phraseRegex, ' ');
// Extract excluded terms
const excludeRegex = /-(\w+)/g;
while ((match = excludeRegex.exec(query)) !== null) {
result.excluded.push(stem(match[1].toLowerCase()));
}
query = query.replace(excludeRegex, ' ');
// Extract OR groups
const orRegex = /(\w+)\s+OR\s+(\w+)/gi;
while ((match = orRegex.exec(query)) !== null) {
result.operators.push({
type: 'OR',
terms: [stem(match[1].toLowerCase()), stem(match[2].toLowerCase())]
});
}
query = query.replace(orRegex, ' ');
// Remaining terms
result.terms = processTokens(tokenize(query));
return result;
}
// Search function
search(query, limit = 10) {
const startTime = performance.now();
const parsedQuery = this.parseQuery(query);
// Get all unique terms to search
const allTerms = [...parsedQuery.terms];
for (const phrase of parsedQuery.phrases) {
allTerms.push(...phrase);
}
for (const op of parsedQuery.operators) {
allTerms.push(...op.terms);
}
// Find candidate documents
const candidates = new Set();
for (const term of allTerms) {
const postings = this.invertedIndex.get(term);
if (postings) {
for (const docId of postings.keys()) {
candidates.add(docId);
}
}
}
// Score candidates
const results = [];
for (const docId of candidates) {
// Check exclusions
let excluded = false;
for (const excTerm of parsedQuery.excluded) {
if (this.invertedIndex.get(excTerm)?.has(docId)) {
excluded = true;
break;
}
}
if (excluded) continue;
// Calculate score
const score = this.calculateBM25(allTerms, docId);
if (score > 0) {
results.push({
document: this.documents.get(docId),
score: score
});
}
}
// Sort by score
results.sort((a, b) => b.score - a.score);
const endTime = performance.now();
return {
results: results.slice(0, limit),
totalFound: results.length,
searchTime: endTime - startTime,
queryTerms: allTerms,
parsedQuery: parsedQuery
};
}
// Get index statistics
getStats() {
return {
totalDocs: this.totalDocs,
totalTerms: this.invertedIndex.size,
avgDocLength: Math.round(this.avgDocLength * 10) / 10
};
}
// Get term info for visualization
getTermInfo(term) {
const postings = this.invertedIndex.get(term);
if (!postings) return null;
return {
term: term,
documentFrequency: postings.size,
idf: this.calculateIDF(term)
};
}
}
// Initialize search engine
const searchEngine = new SearchEngine();
documents.forEach(doc => searchEngine.addDocument(doc));
searchEngine.finalize();
// Update stats display
function updateStats(searchTime = 0) {
const stats = searchEngine.getStats();
document.getElementById('statDocs').textContent = stats.totalDocs;
document.getElementById('statTerms').textContent = stats.totalTerms;
document.getElementById('statAvgLen').textContent = stats.avgDocLength;
document.getElementById('statSearchTime').textContent = searchTime.toFixed(1) + 'ms';
}
updateStats();
// Highlight terms in text
function highlightText(text, terms) {
if (!terms || terms.length === 0) return text;
// Create regex pattern for all terms and their variants
const termPatterns = terms.map(term => {
// Match the stem and common variations
return `\\b${term}[a-z]*\\b`;
});
const pattern = new RegExp(`(${termPatterns.join('|')})`, 'gi');
return text.replace(pattern, '<mark>$1</mark>');
}
// Generate excerpt with context
function generateExcerpt(content, terms, maxLength = 200) {
if (!terms || terms.length === 0) {
return content.substring(0, maxLength) + '...';
}
// Find first occurrence of any term
const lowerContent = content.toLowerCase();
let bestPos = 0;
for (const term of terms) {
const pos = lowerContent.search(new RegExp(`\\b${term}[a-z]*\\b`, 'i'));
if (pos !== -1 && (bestPos === 0 || pos < bestPos)) {
bestPos = pos;
}
}
// Calculate start position with context
const contextStart = Math.max(0, bestPos - 50);
let start = contextStart;
// Adjust to word boundary
if (start > 0) {
while (start > contextStart && content[start - 1] !== ' ') {
start--;
}
}
// Calculate end position
let end = Math.min(content.length, start + maxLength);
while (end < content.length && content[end] !== ' ') {
end++;
}
let excerpt = content.substring(start, end);
if (start > 0) excerpt = '...' + excerpt;
if (end < content.length) excerpt = excerpt + '...';
return excerpt;
}
// Render search results
function renderResults(searchResult) {
const resultsList = document.getElementById('resultsList');
const resultsCount = document.getElementById('resultsCount');
const highlightEnabled = document.getElementById('highlightCheck').checked;
if (searchResult.results.length === 0) {
resultsList.innerHTML = `
<div class="no-results">
<div class="no-results-icon">🔍</div>
<p>No documents found matching your query</p>
</div>
`;
resultsCount.textContent = 'No results found';
return;
}
resultsCount.textContent = `Found ${searchResult.totalFound} document${searchResult.totalFound !== 1 ? 's' : ''} in ${searchResult.searchTime.toFixed(1)}ms`;
resultsList.innerHTML = searchResult.results.map((result, index) => {
const doc = result.document;
const excerpt = generateExcerpt(doc.content, searchResult.queryTerms);
const highlightedExcerpt = highlightEnabled ?
highlightText(excerpt, searchResult.queryTerms) : excerpt;
return `
<div class="result-item" data-doc-id="${doc.id}" style="animation-delay: ${index * 50}ms">
<div class="result-header">
<span class="result-title">${highlightEnabled ? highlightText(doc.title, searchResult.queryTerms) : doc.title}</span>
<span class="result-score">Score: ${result.score.toFixed(3)}</span>
</div>
<div class="result-excerpt">${highlightedExcerpt}</div>
<div class="result-meta">
<span>📁 ${doc.category}</span>
<span>👤 ${doc.author}</span>
<span>📅 ${doc.date}</span>
</div>
</div>
`;
}).join('');
// Add click handlers
document.querySelectorAll('.result-item').forEach(item => {
item.addEventListener('click', () => {
const docId = parseInt(item.dataset.docId);
showDocument(docId, searchResult.queryTerms);
});
});
}
// Update query analysis panel
function updateQueryAnalysis(searchResult) {
const analysis = document.getElementById('queryAnalysis');
const parsed = searchResult.parsedQuery;
let html = `
<div class="analysis-item">
<div class="analysis-label">Tokens</div>
<div class="analysis-value">
${searchResult.queryTerms.map(t => `<span class="token">${t}</span>`).join('')}
</div>
</div>
<div class="analysis-item">
<div class="analysis-label">Documents Found</div>
<div class="analysis-value">${searchResult.totalFound}</div>
</div>
<div class="analysis-item">
<div class="analysis-label">Search Time</div>
<div class="analysis-value">${searchResult.searchTime.toFixed(2)}ms</div>
</div>
`;
if (parsed.phrases.length > 0) {
html += `
<div class="analysis-item">
<div class="analysis-label">Phrase Search</div>
<div class="analysis-value">${parsed.phrases.map(p => `"${p.join(' ')}"`).join(', ')}</div>
</div>
`;
}
if (parsed.excluded.length > 0) {
html += `
<div class="analysis-item">
<div class="analysis-label">Excluded Terms</div>
<div class="analysis-value">${parsed.excluded.join(', ')}</div>
</div>
`;
}
analysis.innerHTML = html;
}
// Update index visualization
function updateIndexViz(searchResult) {
const viz = document.getElementById('indexViz');
const terms = [...new Set(searchResult.queryTerms)].slice(0, 10);
const maxDF = Math.max(...terms.map(t => searchEngine.invertedIndex.get(t)?.size || 0));
if (terms.length === 0) {
viz.innerHTML = '<p style="color: var(--text-muted); font-size: 0.9rem;">No matching terms</p>';
return;
}
viz.innerHTML = terms.map(term => {
const info = searchEngine.getTermInfo(term);
if (!info) return '';
const barWidth = (info.documentFrequency / maxDF) * 100;
return `
<div class="index-term">
<div class="index-term-header">
<span class="term-name">${term}</span>
<span class="term-df">df: ${info.documentFrequency} | IDF: ${info.idf.toFixed(2)}</span>
</div>
<div class="term-bar">
<div class="term-bar-fill" style="width: ${barWidth}%"></div>
</div>
</div>
`;
}).join('');
}
// Perform search
function performSearch() {
const query = document.getElementById('searchInput').value.trim();
const limit = parseInt(document.getElementById('limitSelect').value);
if (!query) {
document.getElementById('resultsList').innerHTML = `
<div class="no-results">
<div class="no-results-icon">🔎</div>
<p>Start typing to search through documents</p>
</div>
`;
document.getElementById('resultsCount').textContent = 'Enter a query to search';
updateStats();
return;
}
const searchResult = searchEngine.search(query, limit);
renderResults(searchResult);
updateQueryAnalysis(searchResult);
updateIndexViz(searchResult);
updateStats(searchResult.searchTime);
}
// Show document modal
function showDocument(docId, queryTerms) {
const doc = documents.find(d => d.id === docId);
if (!doc) return;
const highlightEnabled = document.getElementById('highlightCheck').checked;
const content = highlightEnabled ? highlightText(doc.content, queryTerms) : doc.content;
document.getElementById('modalTitle').textContent = doc.title;
document.getElementById('modalBody').innerHTML = `
<p>${content}</p>
<div class="modal-meta">
<span>📁 Category: ${doc.category}</span>
<span>👤 Author: ${doc.author}</span>
<span>📅 Date: ${doc.date}</span>
</div>
`;
document.getElementById('modalOverlay').classList.add('active');
}
// Close modal
function closeModal() {
document.getElementById('modalOverlay').classList.remove('active');
}
// Event listeners
document.getElementById('searchBtn').addEventListener('click', performSearch);
document.getElementById('searchInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') performSearch();
});
document.getElementById('searchInput').addEventListener('input', (e) => {
if (document.getElementById('realtimeCheck').checked) {
performSearch();
}
});
document.getElementById('modalClose').addEventListener('click', closeModal);
document.getElementById('modalOverlay').addEventListener('click', (e) => {
if (e.target === document.getElementById('modalOverlay')) {
closeModal();
}
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') closeModal();
});
// Initial demo search
setTimeout(() => {
document.getElementById('searchInput').value = 'machine learning';
performSearch();
}, 500);
</script>
</body>
</html>
Key Features Implemented
Search Engine Core
- Inverted Index - Maps terms to documents for O(1) lookups
- BM25 Ranking Algorithm - Industry-standard relevance scoring with:
- Term Frequency (TF) saturation
- Inverse Document Frequency (IDF)
- Document length normalization
- Tokenization & Stemming - Processes text into searchable tokens
- Stop Word Removal - Filters common words for efficiency
Query Features
- Phrase Search: Use
"exact phrase" for exact matching
- Exclusion: Use
-term to exclude documents
- Boolean OR: Use
term1 OR term2 for alternatives
- Real-time search as you type
Visualization
- Query Analysis Panel - Shows tokenized query and stats
- Index Browser - Visualizes matching terms with document frequencies
- BM25 Formula - Displays the ranking algorithm
UI Features
- Term highlighting in results
- Document preview modal
- Search statistics (time, document count, etc.)
- Responsive design
- Animated transitions