search

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2026 License: Apache-2.0, MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Full-text search for Go and Fletch, built in the spirit of Laravel Scout. The root package depends only on the Go standard library (CGO_ENABLED=0), and engines plug in behind a small Engine / Index interface.

Install

go get github.com/fletchhq/search

In a Fletch app, adding github.com/fletchhq/search to go.mod lets fletch ax sync and fletch docs discover docs/search.md and skills/search/SKILL.md automatically.

Packages

Package Purpose
github.com/fletchhq/search Core types (Document, Query, Result, Manager, Searchable), generic typed search, highlighting, and validation helpers. Stdlib-only.
github.com/fletchhq/search/nock Database-backed engine over fletch/nock: SQLite FTS5 (bm25(), snippet(), json_each) and Postgres (tsvector, GIN, ts_rank, ts_headline, JSONB).
github.com/fletchhq/search/meilisearch Meilisearch HTTP client built on stdlib net/http with no third-party SDK.
github.com/fletchhq/search/quiver Async batch-indexing Quiver jobs and transactional ...Tx hooks.
github.com/fletchhq/search/searchtest Stdlib-only in-memory FakeEngine and RunEngineContract suite.

Quick start

Implement search.Searchable on a domain type:

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

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,
		},
	}
}

Open an engine, ensure the index exists, index records through Manager, and run typed queries with search.Search[T]:

engine, err := searchnock.New(db, searchnock.WithTextConfig("english"))
if err != nil {
	return err
}
defer engine.Close()

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

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

res, err := search.Search[Article](ctx, mgr, "articles", search.Query{
	Text:            "fts5 ranking",
	Filters:         map[string]any{"category": "guides", "tags": []string{"go", "sqlite"}},
	Facets:          []string{"category", "tags"},
	HighlightFields: []string{"text", "title"},
	PerPage:         20,
}, nil)
if err != nil {
	return err
}

Passing nil as the decoder uses search.DecodeFields[T] to populate res.Items from each hit's Fields.

Backends and async indexing

  • Use search/nock when your app already runs SQLite or Postgres and you do not want a separate search service. Call EnsureIndex at startup or DDL to emit SQL into your migrations.
  • Use search/meilisearch when you want a dedicated Meilisearch instance. Configure filterable and sortable attributes with WithFilterable and WithSortable, then call EnsureIndex.
  • Use search/quiver to move index writes off the request path. Register workers with RegisterWorkers and enqueue updates inside your database transaction using the ...Tx methods on AsyncIndexer.
  • Use search/searchtest for unit tests (NewFakeEngine) and to verify custom engines (RunEngineContract).

See docs/search.md for the full API reference and backend behavior.

Development

GOWORK=off CGO_ENABLED=0 go test -race -count=1 ./...
CGO_ENABLED=0 scripts/lint.sh

scripts/lint.sh runs golangci-lint v2.15.0.

Documentation

License

MIT or Apache-2.0, at your option. See LICENSE-MIT and LICENSE-APACHE.

Documentation

Overview

Package search is a full-text search abstraction: documents go into named indexes, and queries come back as ranked, filtered, faceted, paginated results. Engines in sibling packages implement it over SQL (search/nock) or Meilisearch (search/meilisearch); search/searchtest has an in-memory engine and a contract suite for any Engine. This package imports only the standard library.

Index

Constants

View Source
const (
	DefaultPerPage   = 20
	MaxPerPage       = 1000
	DefaultPreTag    = "<em>"
	DefaultPostTag   = "</em>"
	HighlightTextKey = "text"
)

Pagination and highlighting defaults.

View Source
const ScoreField = "_score"

ScoreField is the SortKey field that means relevance.

Variables

View Source
var (
	ErrInvalidIndexName = errors.New("search: invalid index name")
	ErrInvalidField     = errors.New("search: invalid field name")
	ErrEmptyID          = errors.New("search: document id is empty")
)

Errors returned by engines and the Manager.

Functions

func DecodeFields

func DecodeFields[T any](h Hit) (T, error)

DecodeFields unmarshals the Fields of h's document into T through JSON.

func FilterValues

func FilterValues(v any) ([]any, error)

FilterValues returns the scalar values a Query.Filters entry matches: v itself for a scalar, or the elements of a slice. Scalars are normalized to string, bool, int64 or float64. A nil value, a nested slice, a map, or any other type is an error.

func Highlight

func Highlight(text string, terms []string, pre, post string) string

Highlight returns text with every word that equals one of terms (case-insensitively) wrapped in pre and post. It returns "" when no word matched. terms are lower-case words, as Tokens returns them.

func Tokens

func Tokens(s string) []string

Tokens splits s into lower-cased words: maximal runs of letters and digits. Engines without their own analyzer use it so they agree on what a word is.

func ValidField

func ValidField(name string) error

ValidField reports whether name is a legal field name: dot-separated segments of letters, digits, '_' and '-', each starting with a letter or '_'. "text" is allowed here because it also names the body in highlights.

func ValidIndexName

func ValidIndexName(name string) error

ValidIndexName reports whether name is a legal index name: 1 to 64 letters, digits, '_' or '-', starting with a letter or digit.

Types

type Document

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"`
}

Document is one searchable record.

Text is the full-text body. String values in Fields (and string elements of slice values) are searched as well. Fields also drive filters, facets, and sorting. Metadata is stored and returned with hits, and is never searched or filtered.

func (Document) FieldStrings

func (d Document) FieldStrings() []string

FieldStrings returns the string values of d.Fields (and string elements of slice values), in sorted field order.

func (Document) SearchableStrings

func (d Document) SearchableStrings() []string

SearchableStrings returns the text an engine without field-level indexing should search for d: Text plus the string values of Fields, with slice elements included, in sorted field order.

func (Document) Validate

func (d Document) Validate() error

Validate reports a document an engine must refuse: an empty ID or an invalid field name.

type Engine

type Engine interface {
	// Index returns the index called name. It does not contact the backend;
	// an invalid name makes the Index's methods fail with ErrInvalidIndexName.
	Index(name string) Index
	// DeleteIndex removes the index and all its documents.
	DeleteIndex(ctx context.Context, name string) error
	Close() error
}

Engine is a search backend holding named indexes.

type FacetCount

type FacetCount struct {
	Value string
	Count int64
}

FacetCount is one value of a facet and the number of matching documents that have it. Values are formatted with fmt.Sprint.

type Hit

type Hit struct {
	ID         string
	Score      float64
	Document   Document
	Highlights map[string]string
}

Hit is one matching document.

type Index

type Index interface {
	// Upsert inserts docs, replacing documents with the same ID.
	Upsert(ctx context.Context, docs ...Document) error
	// Delete removes the documents with ids; unknown ids are ignored.
	Delete(ctx context.Context, ids ...string) error
	// Flush removes every document and keeps the index.
	Flush(ctx context.Context) error
	Search(ctx context.Context, q Query) (Result, error)
}

Index is one named collection of documents.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager indexes and searches Searchable records through an Engine.

func NewManager

func NewManager(engine Engine) *Manager

NewManager returns a Manager over engine.

func (*Manager) DeleteRecord

func (m *Manager) DeleteRecord(ctx context.Context, r Searchable) error

DeleteRecord removes the document of r from its index.

func (*Manager) Engine

func (m *Manager) Engine() Engine

Engine returns the Manager's engine.

func (*Manager) IndexBatch

func (m *Manager) IndexBatch(ctx context.Context, records ...Searchable) error

IndexBatch upserts records, one Upsert per index.

func (*Manager) IndexRecord

func (m *Manager) IndexRecord(ctx context.Context, r Searchable) error

IndexRecord upserts the document of r into its index.

func (*Manager) Search

func (m *Manager) Search(ctx context.Context, name string, q Query) (Result, error)

Search runs q on the index called name.

type Query

type Query struct {
	Text             string
	Filters          map[string]any
	Facets           []string
	Sort             []SortKey
	Page             int
	PerPage          int
	HighlightFields  []string
	HighlightPreTag  string
	HighlightPostTag string
}

Query describes a search.

Text is matched as a set of words that must all occur; empty Text matches every document. Each Filters entry restricts a field: a scalar value matches documents whose field equals it (or, for a slice field, contains it), and a slice value matches any of its elements. Entries are ANDed. Facets names the fields to count over the whole filtered result set, not only the requested page.

Page is 1-based. Zero Page and PerPage mean page 1 and DefaultPerPage. HighlightFields names the fields to highlight ("text" is Document.Text); the tags default to <em> and </em>.

func (Query) Normalize

func (q Query) Normalize() Query

Normalize returns q with defaults applied and bounds enforced.

func (Query) Offset

func (q Query) Offset() int

Offset returns the number of hits before the page of a normalized query.

func (Query) Validate

func (q Query) Validate() error

Validate reports an invalid field name in the filters, facets, sort keys, or highlight fields.

type Result

type Result struct {
	Hits       []Hit
	Total      int64
	Page       int
	PerPage    int
	TotalPages int
	Facets     map[string][]FacetCount
	Took       time.Duration
}

Result is one page of search results.

type Searchable

type Searchable interface {
	SearchIndex() string
	ToSearchDocument() Document
}

Searchable is a record that knows its index and how to become a Document.

type SortKey

type SortKey struct {
	Field string
	Desc  bool
}

SortKey orders results by a document field. The field "_score" sorts by relevance.

type TypedResult

type TypedResult[T any] struct {
	Result
	Items []T
}

TypedResult is a Result with each hit decoded into T. Items[i] belongs to Result.Hits[i].

func Search[T any](ctx context.Context, m *Manager, name string, q Query, decode func(Hit) (T, error)) (TypedResult[T], error)

Search runs q on the index called name and decodes every hit with decode. A nil decode unmarshals Document.Fields into T through JSON, with the ID available under the field "id" only if the Fields hold it.

Directories

Path Synopsis
Package meilisearch is a search.Engine on a Meilisearch server, spoken to with net/http and encoding/json only.
Package meilisearch is a search.Engine on a Meilisearch server, spoken to with net/http and encoding/json only.
Package nock is a search.Engine on a SQL database reached through github.com/fletchhq/fletch/nock.
Package nock is a search.Engine on a SQL database reached through github.com/fletchhq/fletch/nock.
Package quiver indexes search documents in the background through a github.com/fletchhq/fletch/quiver queue.
Package quiver indexes search documents in the background through a github.com/fletchhq/fletch/quiver queue.
Package searchtest has an in-memory search.Engine and a contract suite that every search.Engine must pass.
Package searchtest has an in-memory search.Engine and a contract suite that every search.Engine must pass.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL