Search Indexing ⚡

calculating....


  1. php
  2. javascript

When a flat-file blog scales, linear searching becomes a performance bottleneck. To maintain a Zero-Latency UX, we implement a pre-compiled search index. PHP acts as a build tool that transforms raw Markdown into a lightweight search.json file, which the frontend consumes for instant results. ⌨️

PHP: Building the JSON Index 🧪

This script scans the /blog folder, strips HTML tags, and keeps only the core text and metadata. This minimizes the index size for faster client-side downloads.

<?php
$posts = glob("content/*.md");
$index = [];

foreach ($posts as $file) {
    $raw = file_get_contents($file);
                    
    // Parse Markdown to plain text
    $body = strip_tags(parse_markdown($raw));
                    
    $index[] = [
        "t" => get_title($raw), // Minified keys save bytes
        "s" => basename($file, ".md"),
        "c" => substr($body, 0, 200) . "..." // Preview excerpt
    ];
}

// Write to a static file for the frontend
file_put_contents('search.json', json_encode($index)); 🚀
?>

JavaScript: High-Speed Retrieval 📡

Once the search.json is loaded, we use the Filter API to perform sub-millisecond lookups directly in the user's memory. 🛠️

// Fetch the index once on page load
const index = await fetch('/search.json').then(r => r.json());

function search(query) {
    const term = query.toLowerCase();
                    
    // Sub-millisecond filtering logic
    return index.filter(post =>
        post.t.toLowerCase().includes(term) ||
        post.c.toLowerCase().includes(term)
    );
}

Technical Efficiency Comparison 📊

Metric Standard Loop Indexed Search
Complexity O(n) - Slows with content O(1) - Constant lookup speed ⚡
Server Requests 1 per search 1 per session (Cached) 🟢
Bandwidth High (Full HTML) Minimal (Minified JSON) 📉

By moving from a reactive to a proactive indexing strategy, you ensure that dervic.blog remains performant regardless of how large the archive becomes. This is a standard practice in enterprise-level static site generators (SSGs) and a core skill for professional web engineers.

If you liked this post, please LIKE or COMMENT below! 💬✨


Comments (0)

Thank you!