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

推荐订阅源

aimingoo的专栏
aimingoo的专栏
Jina AI
Jina AI
WordPress大学
WordPress大学
Recent Announcements
Recent Announcements
G
Google Developers Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
MyScale Blog
MyScale Blog
M
MIT News - Artificial intelligence
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
Check Point Blog
J
Java Code Geeks
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Security Blog
Microsoft Security Blog
MongoDB | Blog
MongoDB | Blog
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理
量子位
A
About on SuperTechFans
D
DataBreaches.Net
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

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
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.