惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
Check Point Blog
Hacker News: Ask HN
Hacker News: Ask HN
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
WordPress大学
WordPress大学
P
Proofpoint News Feed
V
Visual Studio Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
N
Netflix TechBlog - Medium
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 叶小钗
Cisco Talos Blog
Cisco Talos Blog
S
Schneier on Security
T
Threat Research - Cisco Blogs
腾讯CDC
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The Hacker News
The Hacker News
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
GbyAI
GbyAI
N
News | PayPal Newsroom
L
LINUX DO - 最新话题
酷 壳 – CoolShell
酷 壳 – CoolShell
P
Palo Alto Networks Blog
T
Tenable Blog
S
Secure Thoughts
T
Threatpost
V2EX - 技术
V2EX - 技术
大猫的无限游戏
大猫的无限游戏
Martin Fowler
Martin Fowler
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Vercel News
Vercel News
罗磊的独立博客
P
Privacy & Cybersecurity Law Blog
Engineering at Meta
Engineering at Meta
小众软件
小众软件
Google DeepMind News
Google DeepMind News
N
News and Events Feed by Topic
Y
Y Combinator Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Cybersecurity and Infrastructure Security Agency CISA
P
Proofpoint News Feed
L
Lohrmann on Cybersecurity
P
Privacy International News Feed
H
Heimdal Security Blog
量子位
B
Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a semantic search API in Go with Meilisearch
Ayi NEDJIMI · 2026-05-23 · via DEV Community

Ayi NEDJIMI

Full-text search is one of those features that looks simple until you have to ship it. Typos fail silently. Category filters conflict with relevance ranking. The database LIKE query that worked at 10,000 rows grinds to a halt at 100,000. This tutorial walks through building a real search API in Go using Fiber and Meilisearch, complete with filter support, typo tolerance configuration, and a MySQL LIKE fallback for resilience.

This is roughly the architecture running search across 1,600+ cybersecurity articles at AYI NEDJIMI Consultants.

Setup

go mod init search-api
go get github.com/gofiber/fiber/v2
go get github.com/meilisearch/meilisearch-go
go get github.com/go-sql-driver/mysql

Enter fullscreen mode Exit fullscreen mode

Run Meilisearch:

docker run -d -p 7700:7700 \
  -e MEILI_MASTER_KEY=your_master_key \
  getmeili/meilisearch:latest

Enter fullscreen mode Exit fullscreen mode

Project structure

search-api/
├── main.go
├── config/
│   └── config.go
├── search/
│   ├── meili.go
│   └── fallback.go
└── handlers/
    └── search.go

Enter fullscreen mode Exit fullscreen mode

Data model

// search/meili.go
package search

// Article is the document type stored in Meilisearch and MySQL.
type Article struct {
    ID         string   `json:"id"`
    Title      string   `json:"title"`
    Slug       string   `json:"slug"`
    Content    string   `json:"content"`    // plain text, stripped of HTML
    Category   string   `json:"category"`   // news, guide, analyse, blog, checklist
    Difficulty string   `json:"difficulty"` // beginner, intermediate, advanced
    DocType    string   `json:"doc_type"`   // article, checklist, glossary
    Tags       []string `json:"tags"`
    PublishedAt int64   `json:"published_at"` // Unix timestamp for sort
}

// SearchResult wraps hits with metadata.
type SearchResult struct {
    Hits             []Article `json:"hits"`
    TotalHits        int64     `json:"total_hits"`
    ProcessingTimeMs int64     `json:"processing_time_ms"`
    Query            string    `json:"query"`
    Source           string    `json:"source"` // "meilisearch" or "mysql_fallback"
}

Enter fullscreen mode Exit fullscreen mode

Meilisearch client initialization

// search/meili.go (continued)
package search

import (
    "fmt"
    "log"

    "github.com/meilisearch/meilisearch-go"
)

const IndexName = "articles"

type MeiliSearcher struct {
    client meilisearch.ServiceManager
    index  meilisearch.IndexManager
}

func NewMeiliSearcher(host, apiKey string) (*MeiliSearcher, error) {
    client := meilisearch.New(host, meilisearch.WithAPIKey(apiKey))

    // Verify connectivity
    if _, err := client.Health(); err != nil {
        return nil, fmt.Errorf("meilisearch unreachable at %s: %w", host, err)
    }

    s := &MeiliSearcher{client: client}
    if err := s.ensureIndex(); err != nil {
        return nil, err
    }
    return s, nil
}

func (s *MeiliSearcher) ensureIndex() error {
    // Get or create index
    idx, err := s.client.GetIndex(IndexName)
    if err != nil {
        task, err := s.client.CreateIndex(&meilisearch.IndexConfig{
            Uid:        IndexName,
            PrimaryKey: "id",
        })
        if err != nil {
            return fmt.Errorf("create index: %w", err)
        }
        s.client.WaitForTask(task.TaskUID, nil)
        idx, err = s.client.GetIndex(IndexName)
        if err != nil {
            return fmt.Errorf("get index after create: %w", err)
        }
    }
    s.index = idx
    return s.configureIndex()
}

func (s *MeiliSearcher) configureIndex() error {
    task, err := s.index.UpdateSettings(&meilisearch.Settings{
        SearchableAttributes: []string{
            "title",      // highest weight
            "tags",
            "content",    // lowest weight
        },
        FilterableAttributes: []string{
            "category",
            "difficulty",
            "doc_type",
        },
        SortableAttributes: []string{
            "published_at",
        },
        RankingRules: []string{
            "words",
            "typo",
            "proximity",
            "attribute",   // respects SearchableAttributes order
            "sort",
            "exactness",
        },
        TypoTolerance: &meilisearch.TypoTolerance{
            Enabled: func() *bool { b := true; return &b }(),
            MinWordSizeForTypos: meilisearch.MinWordSizeForTypos{
                OneTypo:  4,
                TwoTypos: 8,
            },
        },
        Pagination: &meilisearch.Pagination{
            MaxTotalHits: 10000,
        },
    })
    if err != nil {
        return fmt.Errorf("update settings: %w", err)
    }
    s.client.WaitForTask(task.TaskUID, nil)
    log.Println("Meilisearch index configured.")
    return nil
}

Enter fullscreen mode Exit fullscreen mode

Index sync function

Call this on startup and hook it to your CRUD operations.

// search/meili.go (continued)

func (s *MeiliSearcher) IndexDocuments(articles []Article) error {
    if len(articles) == 0 {
        return nil
    }
    task, err := s.index.AddDocuments(articles, "id")
    if err != nil {
        return fmt.Errorf("add documents: %w", err)
    }
    s.client.WaitForTask(task.TaskUID, nil)
    log.Printf("Indexed %d documents.", len(articles))
    return nil
}

func (s *MeiliSearcher) DeleteDocument(id string) error {
    task, err := s.index.DeleteDocument(id)
    if err != nil {
        return fmt.Errorf("delete document %s: %w", id, err)
    }
    s.client.WaitForTask(task.TaskUID, nil)
    return nil
}

Enter fullscreen mode Exit fullscreen mode

Search with filters

// search/meili.go (continued)

type SearchParams struct {
    Query      string
    Category   string
    Difficulty string
    DocType    string
    Limit      int64
    Offset     int64
}

func (s *MeiliSearcher) Search(params SearchParams) (*SearchResult, error) {
    if params.Limit <= 0 {
        params.Limit = 10
    }
    if params.Limit > 100 {
        params.Limit = 100
    }

    // Build filter expression
    var filters []string
    if params.Category != "" {
        filters = append(filters, fmt.Sprintf("category = %q", params.Category))
    }
    if params.Difficulty != "" {
        filters = append(filters, fmt.Sprintf("difficulty = %q", params.Difficulty))
    }
    if params.DocType != "" {
        filters = append(filters, fmt.Sprintf("doc_type = %q", params.DocType))
    }

    filterStr := ""
    for i, f := range filters {
        if i == 0 {
            filterStr = f
        } else {
            filterStr += " AND " + f
        }
    }

    req := &meilisearch.SearchRequest{
        Limit:  params.Limit,
        Offset: params.Offset,
        AttributesToRetrieve: []string{
            "id", "title", "slug", "category",
            "difficulty", "doc_type", "tags", "published_at",
        },
        // Don't return full content in search results
    }
    if filterStr != "" {
        req.Filter = filterStr
    }

    resp, err := s.index.Search(params.Query, req)
    if err != nil {
        return nil, err
    }

    hits := make([]Article, 0, len(resp.Hits))
    for _, h := range resp.Hits {
        // Meilisearch returns hits as map[string]interface{}
        b, _ := json.Marshal(h)
        var a Article
        if err := json.Unmarshal(b, &a); err == nil {
            hits = append(hits, a)
        }
    }

    return &SearchResult{
        Hits:             hits,
        TotalHits:        resp.TotalHits,
        ProcessingTimeMs: resp.ProcessingTimeMs,
        Query:            params.Query,
        Source:           "meilisearch",
    }, nil
}

Enter fullscreen mode Exit fullscreen mode

MySQL fallback

When Meilisearch is down (restart, OOM, maintenance), fall back to MySQL LIKE. It's slower and has no typo tolerance, but it keeps the API responding.

// search/fallback.go
package search

import (
    "database/sql"
    "fmt"
    "strings"
    "time"

    _ "github.com/go-sql-driver/mysql"
)

type MySQLFallback struct {
    db *sql.DB
}

func NewMySQLFallback(dsn string) (*MySQLFallback, error) {
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        return nil, err
    }
    db.SetMaxOpenConns(10)
    db.SetConnMaxLifetime(5 * time.Minute)
    return &MySQLFallback{db: db}, nil
}

func (m *MySQLFallback) Search(params SearchParams) (*SearchResult, error) {
    query := "%" + strings.ReplaceAll(params.Query, "%", "\\%") + "%"

    args := []interface{}{query, query}
    where := "WHERE (title LIKE ? OR content LIKE ?)"

    if params.Category != "" {
        where += " AND category = ?"
        args = append(args, params.Category)
    }
    if params.Difficulty != "" {
        where += " AND difficulty = ?"
        args = append(args, params.Difficulty)
    }
    if params.DocType != "" {
        where += " AND doc_type = ?"
        args = append(args, params.DocType)
    }

    // Count total
    var total int64
    countSQL := fmt.Sprintf("SELECT COUNT(*) FROM articles %s", where)
    _ = m.db.QueryRow(countSQL, args...).Scan(&total)

    // Fetch page
    args = append(args, params.Limit, params.Offset)
    rows, err := m.db.Query(
        fmt.Sprintf(`SELECT id, title, slug, category, difficulty, doc_type, published_at
                     FROM articles %s ORDER BY published_at DESC LIMIT ? OFFSET ?`, where),
        args...,
    )
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    var hits []Article
    for rows.Next() {
        var a Article
        if err := rows.Scan(&a.ID, &a.Title, &a.Slug,
            &a.Category, &a.Difficulty, &a.DocType, &a.PublishedAt); err != nil {
            continue
        }
        hits = append(hits, a)
    }

    return &SearchResult{
        Hits:      hits,
        TotalHits: total,
        Query:     params.Query,
        Source:    "mysql_fallback",
    }, nil
}

Enter fullscreen mode Exit fullscreen mode

HTTP handler

// handlers/search.go
package handlers

import (
    "encoding/json"
    "log"

    "github.com/gofiber/fiber/v2"
    "search-api/search"
)

type SearchHandler struct {
    meili    *search.MeiliSearcher
    fallback *search.MySQLFallback
}

func NewSearchHandler(meili *search.MeiliSearcher, fallback *search.MySQLFallback) *SearchHandler {
    return &SearchHandler{meili: meili, fallback: fallback}
}

func (h *SearchHandler) Handle(c *fiber.Ctx) error {
    params := search.SearchParams{
        Query:      c.Query("q", ""),
        Category:   c.Query("cat", ""),
        Difficulty: c.Query("diff", ""),
        DocType:    c.Query("type", ""),
        Limit:      int64(c.QueryInt("limit", 10)),
        Offset:     int64(c.QueryInt("offset", 0)),
    }

    if len([]rune(params.Query)) > 200 {
        return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
            "error": "query too long",
        })
    }

    result, err := h.meili.Search(params)
    if err != nil {
        log.Printf("Meilisearch error: %v — falling back to MySQL", err)
        result, err = h.fallback.Search(params)
        if err != nil {
            return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
                "error": "search unavailable",
            })
        }
    }

    return c.JSON(result)
}

Enter fullscreen mode Exit fullscreen mode

Wiring it up in main.go

// main.go
package main

import (
    "log"
    "os"

    "github.com/gofiber/fiber/v2"
    "search-api/handlers"
    "search-api/search"
)

func main() {
    meiliHost := os.Getenv("MEILI_HOST")       // e.g. "http://127.0.0.1:7700"
    meiliKey  := os.Getenv("MEILI_MASTER_KEY")
    mysqlDSN  := os.Getenv("MYSQL_DSN")        // e.g. "user:pass@tcp(127.0.0.1:3306)/dbname"

    meili, err := search.NewMeiliSearcher(meiliHost, meiliKey)
    if err != nil {
        log.Fatalf("Failed to connect to Meilisearch: %v", err)
    }

    fallback, err := search.NewMySQLFallback(mysqlDSN)
    if err != nil {
        log.Fatalf("Failed to connect to MySQL: %v", err)
    }

    app := fiber.New(fiber.Config{
        ErrorHandler: func(c *fiber.Ctx, err error) error {
            return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
                "error": err.Error(),
            })
        },
    })

    searchHandler := handlers.NewSearchHandler(meili, fallback)
    app.Get("/api/search", searchHandler.Handle)

    // Reindex endpoint (protect with auth middleware in production)
    app.Post("/admin/search/reindex", func(c *fiber.Ctx) error {
        var articles []search.Article
        if err := c.BodyParser(&articles); err != nil {
            return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
        }
        if err := meili.IndexDocuments(articles); err != nil {
            return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
        }
        return c.JSON(fiber.Map{"indexed": len(articles)})
    })

    log.Fatal(app.Listen(":4001"))
}

Enter fullscreen mode Exit fullscreen mode

Test it

# Basic search
curl "http://localhost:4001/api/search?q=pentest"

# With filters
curl "http://localhost:4001/api/search?q=NIS+2&cat=guide&diff=intermediate&limit=5"

# Typo tolerance in action
curl "http://localhost:4001/api/search?q=penetartion+tesitng"

Enter fullscreen mode Exit fullscreen mode

Key tuning decisions

SearchableAttributes order matters. Meilisearch's attribute ranking rule rewards matches in earlier attributes. Putting title first means a title match outranks a content match, which is almost always what you want.

Pagination cap. The MaxTotalHits: 10000 setting prevents Meilisearch from doing expensive full-index scans for pagination deep into results. If users never go past page 20 at 10 results/page, set this to 200.

Fallback opacity. The source field in SearchResult tells the frontend (and your monitoring) when it's getting degraded results. Log every fallback occurrence — if Meilisearch is down and you're not paged, you won't know until users complain.

On-startup sync. Pull all published articles from MySQL on startup and call IndexDocuments. For 10,000+ documents this takes 2–5 seconds; for 100,000+ batch in chunks of 5,000. This ensures your index is always consistent even after a Meilisearch restart.

This pattern — Meilisearch primary, MySQL LIKE fallback — gives you production-grade search with no single point of failure and a codebase any Go developer can reason about.