Docs/Ecosystem/Search: Full-Text Search for Go

Search: Full-Text Search for Go

Full-text search for Go behind an Engine and Index interface with SQLite FTS5, Postgres tsvector, pure-Go Meilisearch, and transactional Quiver jobs.

github.com/fletchhq/search

searchpkg.go.dev

Updated 2026-12-06 fletch docs show search/search 9 min read

On this page

Search puts full-text indexing, structured filtering, faceting, sorting, pagination, and highlighting behind a small Engine and Index interface in Go. Start with your existing SQLite or Postgres database via search/nock, switch to a Meilisearch server via search/meilisearch without changing query code, and move index writes off the request path with search/quiver.

Introduction

Most applications need ranked full-text search well before they need a dedicated search cluster, yet writing raw FTS5 or tsvector queries directly inside handlers makes switching backends painful later.

github.com/fletchhq/search separates your domain models and query code from the underlying search engine. Your handlers talk to search.Manager and typed search.Search[T] calls against a stdlib-only root package. Backends live in sibling packages inside the same module: SQLite FTS5 and Postgres tsvector/GIN (search/nock), pure-Go HTTP Meilisearch (search/meilisearch), background batch indexing (search/quiver), and an in-memory fake plus contract suite (search/searchtest).

Installation

Add the module to your project:

go get github.com/fletchhq/search@v0.1.0

github.com/fletchhq/search, search/meilisearch, and search/searchtest depend only on the Go standard library (CGO_ENABLED=0). search/nock and search/quiver live as sub-packages in the same module, so Go compiles Nock or Quiver support only when you import them.

Package Dependencies Role
github.com/fletchhq/search Go stdlib Document, Searchable, Query, Result, Engine, Index, Manager, Search[T], validation, highlighting
github.com/fletchhq/search/nock fletch/nock SQLite FTS5 and Postgres tsvector/GIN engine
github.com/fletchhq/search/meilisearch Go stdlib (net/http) Meilisearch HTTP engine with no third-party SDK
github.com/fletchhq/search/quiver fletch/quiver Chunked background indexing jobs and transactional enqueue helpers
github.com/fletchhq/search/searchtest Go stdlib In-memory FakeEngine, fixture Corpus, and RunEngineContract suite

When github.com/fletchhq/search is in your go.mod, fletch ax sync and fletch docs discover its embedded documentation and skill automatically.

Core concepts

Documents and Searchable

A search.Document separates searchable content from display metadata:

type Document struct {
	ID       string         `json:"id"`
	Fields   map[string]any `json:"fields,omitempty"`
	Text     string         `json:"text,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}
  • ID uniquely identifies the document inside an index and must be non-empty (ErrEmptyID).
  • Text holds the primary full-text body.
  • Fields holds structured attributes used for filtering, facets, sorting, and DecodeFields[T]. String values and string slices inside Fields are also indexed for full-text search.
  • Metadata is stored and returned on every Hit.Document, but never searched or filtered. Put URLs, image paths, or display-only data here so it does not skew relevance.

Domain types implement search.Searchable so Manager and AsyncIndexer can index or delete records directly:

type Article struct {
	ID       string   `json:"id"`
	Title    string   `json:"title"`
	Category string   `json:"category"`
	Tags     []string `json:"tags"`
	Body     string   `json:"-"`
	Slug     string   `json:"-"`
}

func (a Article) SearchIndex() string { return "articles" }

func (a Article) ToSearchDocument() search.Document {
	return search.Document{
		ID:   a.ID,
		Text: a.Title + "\n" + a.Body,
		Fields: map[string]any{
			"title":    a.Title,
			"category": a.Category,
			"tags":     a.Tags,
		},
		Metadata: map[string]any{"slug": a.Slug},
	}
}

Document also exposes three helper methods used by engines and validators:

  • d.Validate() returns ErrEmptyID when d.ID is empty or ErrInvalidField when any key in d.Fields fails ValidField.
  • d.FieldStrings() returns string values (and string slice elements) from d.Fields in sorted key order.
  • d.SearchableStrings() returns d.Text followed by d.FieldStrings().

Validation rules

Every engine validates index and field names before executing SQL or HTTP requests:

  • search.ValidIndexName(name) requires 1 to 64 letters, digits, _, or -, starting with a letter or digit (ErrInvalidIndexName).
  • search.ValidField(name) requires dot-separated segments of letters, digits, _, or -, each starting with a letter or _ (ErrInvalidField).
  • search.FilterValues(v) normalizes a filter scalar or slice into string, bool, int64, or float64 values, rejecting nil, maps, and nested slices.

Queries, filters, facets, and highlighting

A search.Query expresses full-text terms, exact or array filters, facet aggregations, multi-key sorting, 1-based pagination, and snippet highlighting:

q := search.Query{
	Text: "postgres tsvector",
	Filters: map[string]any{
		"category": "articles",
		"tags":     []string{"sql", "search"},
	},
	Facets: []string{"category", "tags"},
	Sort: []search.SortKey{
		{Field: search.ScoreField, Desc: true},
		{Field: "title"},
	},
	Page:            1,
	PerPage:         20,
	HighlightFields: []string{search.HighlightTextKey, "title"},
}

Every word in Text must occur in the document; an empty Text matches all documents (ordered by ID unless Sort is specified). Filter entries are ANDed together: a scalar matches equality or array-contains, while a slice matches any element in the slice. Facets are counted across the full filtered result set, not just the current page.

Query provides three methods:

  • q.Normalize() clamps Page to at least 1, PerPage to [1, MaxPerPage] (default DefaultPerPage = 20, max MaxPerPage = 1000), and fills empty highlight tags with DefaultPreTag ("<em>") and DefaultPostTag ("</em>").
  • q.Offset() returns (q.Page - 1) * q.PerPage for a normalized query.
  • q.Validate() verifies every field name in Filters, Facets, Sort (skipping ScoreField), and HighlightFields.

When highlighting Document.Text (HighlightTextKey = "text"), SQL engines use snippet() on SQLite and ts_headline on Postgres. Other string fields (and engines without a built-in highlighter) use search.Tokens(s) and search.Highlight(text, terms, pre, post).

Common tasks

Configuring a search engine

Choose search/nock to run full-text search inside your existing SQLite or Postgres database, or search/meilisearch to connect to a Meilisearch server:

import (
	"github.com/fletchhq/search"
	searchnock "github.com/fletchhq/search/nock"
)

engine, err := searchnock.New(
	db,
	searchnock.WithTablePrefix("search_"),
	searchnock.WithTextConfig("english"), // Postgres regconfig; ignored by SQLite
)
if err != nil {
	return err
}
defer engine.Close()

if err := engine.EnsureIndex(ctx, "articles"); err != nil {
	return err
}

mgr := search.NewManager(engine)
import (
	"time"

	"github.com/fletchhq/search"
	"github.com/fletchhq/search/meilisearch"
)

engine, err := meilisearch.New(
	"http://127.0.0.1:7700",
	meilisearch.WithAPIKey(apiKey),
	meilisearch.WithFilterable("category", "tags"),
	meilisearch.WithSortable("title", "created_at"),
	meilisearch.WithWaitForTasks(5*time.Second),
)
if err != nil {
	return err
}
defer engine.Close()

if err := engine.EnsureIndex(ctx, "articles"); err != nil {
	return err
}

mgr := search.NewManager(engine)

With search/nock, each index creates a <prefix><name> table automatically on first use or ahead of time via EnsureIndex. If your app manages schema changes in migration files, call engine.DDL("articles") to print the exact SQL statements. Note that engine.Close() leaves the underlying Nock database open.

  • SQLite: creates a companion FTS5 virtual table, ranks with bm25(), highlights "text" with snippet(), and evaluates filters and facets using json_each.
  • Postgres: stores weighted tsvector columns (body weighted A, string fields weighted B) backed by a GIN index, parses queries with websearch_to_tsquery, ranks with ts_rank, highlights "text" with ts_headline, and evaluates filters with JSONB containment.

With search/meilisearch, the client talks to Meilisearch over stdlib net/http and encodes document IDs in unpadded base64url so arbitrary Go IDs up to 383 bytes fit Meilisearch's 511-byte ID rules. Always declare every filtered, faceted, or sorted field with WithFilterable and WithSortable before calling EnsureIndex.

Indexing records and running typed searches

Use Manager to index, batch-upsert, or delete Searchable records, and call the generic search.Search[T] helper to decode hits into domain structs alongside pagination and facets:

if err := mgr.IndexRecord(ctx, article); err != nil {
	return err
}

res, err := search.Search[Article](ctx, mgr, "articles", search.Query{
	Text:            "concurrency",
	Filters:         map[string]any{"category": "articles"},
	Facets:          []string{"tags"},
	HighlightFields: []string{search.HighlightTextKey, "title"},
}, nil)
if err != nil {
	return err
}

Passing a nil decoder uses search.DecodeFields[T], which JSON-unmarshals Hit.Document.Fields into T. If you also need Hit.ID, Hit.Document.Text, Hit.Document.Metadata, or Hit.Highlights, pass a custom func(search.Hit) (T, error) decoder instead. TypedResult[T] embeds search.Result (Hits, Total, Page, PerPage, TotalPages, Facets, Took) and adds Items []T aligned index-for-index with Hits.

Async indexing with search/quiver

Move search writes off HTTP handlers and keep your search index consistent with database commits using github.com/fletchhq/search/quiver. First, register the three batch workers when your Quiver worker starts:

import searchquiver "github.com/fletchhq/search/quiver"

searchquiver.RegisterWorkers(queue, engine)

Then create an *searchquiver.AsyncIndexer and enqueue updates inside your database transaction using the ...Tx methods:

indexer := searchquiver.NewAsyncIndexer(
	queue,
	searchquiver.WithChunkSize(500),
)

err := db.Transaction(ctx, func(tx *nock.Transaction) error {
	if err := saveArticle(ctx, tx, article); err != nil {
		return err
	}
	_, err := indexer.IndexRecordsTx(ctx, tx, article)
	return err
})

AsyncIndexer splits large batches into chunks of DefaultChunkSize (500) and schedules IndexBatchJob, DeleteBatchJob, or FlushIndexJob. All three implement Kind() and Defaults(), targeting queue DefaultQueue ("search"), 8 max attempts, and a 2m timeout. Pass searchquiver.WithEnqueueOptions(...) to override queue or priority defaults. Workers automatically discard permanent validation errors (ErrInvalidIndexName, ErrEmptyID, ErrInvalidField) via quiver.Discard so bad payloads do not retry.

Advanced usage

Handling Meilisearch errors and async tasks

Because Meilisearch processes document writes asynchronously, writes return once queued unless meilisearch.WithWaitForTasks(timeout) is configured (using meilisearch.WithPollInterval, default 50ms). Waiting on tasks is useful in tests and CLI scripts that need immediate read-after-write visibility.

Inspect API and task failures with typed errors, and translate a search.Query to its wire JSON payload with meilisearch.SearchRequest(q) when debugging queries:

var apiErr *meilisearch.Error
var taskErr *meilisearch.TaskError

switch {
case meilisearch.IndexNotFound(err):
	// Index has not been created yet
case errors.As(err, &taskErr):
	log.Printf("meilisearch task %d failed: %s", taskErr.UID, taskErr.Err.Message)
case errors.As(err, &apiErr):
	log.Printf("meilisearch HTTP %d (%s): %s", apiErr.Status, apiErr.Code, apiErr.Message)
}

Testing with search/searchtest

github.com/fletchhq/search/searchtest ships an in-memory *searchtest.FakeEngine that supports word matching (search.Tokens), filters, facets, multi-key sorting, pagination, and highlighting for fast unit tests:

func TestArticleSearch(t *testing.T) {
	engine := searchtest.NewFakeEngine()
	mgr := search.NewManager(engine)

	if err := mgr.IndexBatch(t.Context(), seedArticles...); err != nil {
		t.Fatal(err)
	}

	res, err := search.Search[Article](t.Context(), mgr, "articles", search.Query{Text: "go"}, nil)
	if err != nil {
		t.Fatal(err)
	}
	if res.Total != 2 {
		t.Fatalf("got %d hits, want 2", res.Total)
	}
}

If you build a custom search.Engine, verify it against the full contract test suite (RunEngineContract) using the searchtest.Factory signature. searchtest.Corpus() returns the fixture documents used by the suite, and searchtest.Normalize(doc) runs a JSON round-trip on a document for assertions:

func TestMyEngineContract(t *testing.T) {
	searchtest.RunEngineContract(t, func(t *testing.T) search.Engine {
		return newMyTestEngine(t)
	})
}

Reference

Core search types, helpers, and constants

Symbol Role
Engine / Index Backend interfaces (Index, DeleteIndex, Close; Upsert, Delete, Flush, Search)
Manager Record-level wrapper (NewManager, Engine, IndexRecord, IndexBatch, DeleteRecord, Search)
Search[T] / TypedResult[T] / DecodeFields[T] Generic search execution and JSON field decoding
Document / Searchable Record types (Document.Validate, Document.FieldStrings, Document.SearchableStrings)
Query / SortKey / ScoreField Query definition (Query.Normalize, Query.Offset, Query.Validate; ScoreField = "_score")
Result / Hit / FacetCount Paginated search output
Tokens / Highlight / FilterValues Analyzer, highlighting, and filter normalization helpers
ValidIndexName / ValidField Name validation helpers
DefaultPerPage / MaxPerPage 20 / 1000
DefaultPreTag / DefaultPostTag / HighlightTextKey "<em>" / "</em>" / "text"
ErrInvalidIndexName / ErrInvalidField / ErrEmptyID Validation sentinel errors

search/quiver job kinds and indexer methods

Operation Transactional twin Job type & Kind()
Upsert(ctx, index, docs...) UpsertTx(ctx, tx, index, docs...) IndexBatchJob (KindIndexBatch = "search.index_batch")
Delete(ctx, index, ids...) DeleteTx(ctx, tx, index, ids...) DeleteBatchJob (KindDeleteBatch = "search.delete_batch")
Flush(ctx, index) FlushTx(ctx, tx, index) FlushIndexJob (KindFlushIndex = "search.flush_index")
IndexRecords(ctx, records...) IndexRecordsTx(ctx, tx, records...) IndexBatchJob (grouped by SearchIndex())
DeleteRecords(ctx, records...) DeleteRecordsTx(ctx, tx, records...) DeleteBatchJob (grouped by SearchIndex())

Backend options

Package Option Default / purpose
search/nock WithTablePrefix(prefix) "search_" prefix for index tables
search/nock WithTextConfig(config) "english" Postgres regconfig (ignored on SQLite)
search/meilisearch WithAPIKey(key) Bearer API key for Meilisearch requests
search/meilisearch WithHTTPClient(c) Custom *http.Client (default 30s timeout)
search/meilisearch WithWaitForTasks(timeout) Waits for asynchronous write tasks to finish
search/meilisearch WithPollInterval(d) 50ms task polling interval when waiting
search/meilisearch WithFilterable(fields...) Declares filterable and facetable Document.Fields keys
search/meilisearch WithSortable(fields...) Declares sortable Document.Fields keys
search/quiver WithChunkSize(n) 500 (DefaultChunkSize) documents or IDs per job
search/quiver WithEnqueueOptions(opts...) Extra quiver.EnqueueOption values applied to every job