Help us shape the future of Go! Take the 2026 Go Developer Survey

search

package
v1.11.9 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package search defines schemas, normalized search requests, resource indexing, facets, and memory, PostgreSQL, and Elasticsearch backends. Applications own index lifecycle, capacity, relevance, and recovery policy.

Index

Constants

View Source
const (
	// DefaultLimit is the page size used when a request omits a limit.
	DefaultLimit = 20
	// MaxLimit is the largest accepted search page size.
	MaxLimit = 100
	// MaxFilters is the maximum number of filters in one request.
	MaxFilters = 20
	// MaxFacets is the maximum number of facet requests in one search.
	MaxFacets = 10
	// MaxFacetBuckets is the upper bound for buckets returned by one facet.
	MaxFacetBuckets = 100
	// MaxQueryLength is the maximum keyword-query length in bytes.
	MaxQueryLength = 512
	// DefaultFacetLimit is the bucket count used when a facet omits a limit.
	DefaultFacetLimit = 20
)

Variables

View Source
var ErrElasticsearchNotConfigured = errors.New("search: Elasticsearch provider is not configured")

ErrElasticsearchNotConfigured is returned when a zero-value client is used.

Functions

This section is empty.

Types

type AttributeDefinition

type AttributeDefinition struct {
	Key        string        `json:"key"`
	Type       AttributeType `json:"type"`
	MultiValue bool          `json:"multi_value,omitempty"`
	Filterable bool          `json:"filterable,omitempty"`
	Facetable  bool          `json:"facetable,omitempty"`
	Searchable bool          `json:"searchable,omitempty"`
	Sortable   bool          `json:"sortable,omitempty"`
	EnumValues []string      `json:"enum_values,omitempty"`
}

AttributeDefinition declares validation and search capabilities for one attribute.

type AttributeType

type AttributeType string

AttributeType identifies the scalar representation of a searchable attribute.

const (
	// AttributeString represents textual values.
	AttributeString AttributeType = "string"
	// AttributeInteger represents integral numeric values.
	AttributeInteger AttributeType = "integer"
	// AttributeDecimal represents numeric values that may have a fractional part.
	AttributeDecimal AttributeType = "decimal"
	// AttributeBoolean represents boolean values.
	AttributeBoolean AttributeType = "boolean"
	// AttributeDate represents date or time values.
	AttributeDate AttributeType = "date"
	// AttributeEnum represents a value drawn from a declared set.
	AttributeEnum AttributeType = "enum"
)

type Backend

type Backend interface {
	Name() string
	Index(ctx context.Context, resource string, schema Schema, document Document) error
	Delete(ctx context.Context, resource, documentID string) error
	Search(ctx context.Context, resource string, schema Schema, request SearchRequest) (SearchResult, error)
}

Backend stores, deletes, and queries documents for named resources.

type Client

type Client = InMemSearchEngine

Client is the legacy in-memory engine name retained for source compatibility.

func New

func New() *Client

New returns an empty legacy Client.

type DatabaseBackend

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

DatabaseBackend implements Backend with PostgreSQL JSONB and full-text search.

func NewDatabaseBackend

func NewDatabaseBackend(db SQLDatabase, config DatabaseConfig) (*DatabaseBackend, error)

NewDatabaseBackend validates the database and table configuration.

func (*DatabaseBackend) Compile

func (b *DatabaseBackend) Compile(resource string, schema Schema, request SearchRequest) (DatabaseQueryPlan, error)

Compile produces parameterized PostgreSQL queries without executing them.

func (*DatabaseBackend) Delete

func (b *DatabaseBackend) Delete(ctx context.Context, resource, documentID string) error

Delete removes one resource document by ID.

func (*DatabaseBackend) Index

func (b *DatabaseBackend) Index(ctx context.Context, resource string, schema Schema, document Document) error

Index inserts or replaces one resource document.

func (*DatabaseBackend) Name

func (b *DatabaseBackend) Name() string

Name identifies this backend as database.

func (*DatabaseBackend) Search

func (b *DatabaseBackend) Search(ctx context.Context, resource string, schema Schema, request SearchRequest) (SearchResult, error)

Search executes the compiled count, hit, and facet queries.

func (*DatabaseBackend) Setup

func (b *DatabaseBackend) Setup(ctx context.Context) error

Setup creates the backing table and indexes if they do not exist.

type DatabaseConfig

type DatabaseConfig struct {
	Table string
}

DatabaseConfig configures the PostgreSQL search document table.

type DatabaseQueryPlan

type DatabaseQueryPlan struct {
	Count  SQLQuery
	Hits   SQLQuery
	Facets map[string]SQLQuery
}

DatabaseQueryPlan contains the SQL generated for one normalized search request.

type Document

type Document struct {
	ID         string         `json:"id"`
	Attributes map[string]any `json:"attributes"`
}

Document is a resource record stored by a search backend.

type ESClient

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

ESClient manages Elasticsearch indexing and full-text keyword queries.

func NewElasticsearchClient

func NewElasticsearchClient(ctx context.Context, config ESConfig) (*ESClient, error)

NewElasticsearchClient validates the configuration and verifies cluster connectivity. It never returns a client that will silently accept operations.

func (*ESClient) IndexDocument

func (client *ESClient) IndexDocument(ctx context.Context, indexName, docID string, payload any) error

IndexDocument indexes a document using an idempotent PUT request.

func (*ESClient) SearchKeyword

func (client *ESClient) SearchKeyword(
	ctx context.Context, indexName, query string,
) ([]map[string]any, error)

SearchKeyword performs a bounded simple-query-string search. Results retain Elasticsearch metadata while exposing the document under the stable "doc" key.

type ESConfig

type ESConfig struct {
	Addresses         []string
	Username          string
	Password          string
	APIKey            string
	HTTPClient        *http.Client
	AllowInsecureHTTP bool
	RequestTimeout    time.Duration
	MaxRequestBytes   int64
	MaxResponseBytes  int64
	MaxQueryBytes     int
	RetryAttempts     int
}

ESConfig holds Elasticsearch cluster configuration. HTTPS is required unless AllowInsecureHTTP is explicitly enabled for a trusted development network.

type Engine

type Engine interface {
	IndexDocument(ctx context.Context, indexName, docID string, payload any) error
	SearchKeyword(ctx context.Context, indexName, query string) ([]map[string]any, error)
}

Engine defines the contract for full-text search indexing and keyword search providers.

type ExecutionError

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

ExecutionError hides backend details while preserving the cause for errors.Is/As.

func (*ExecutionError) Error

func (e *ExecutionError) Error() string

Error implements error without exposing storage or scope details to callers.

func (*ExecutionError) Unwrap

func (e *ExecutionError) Unwrap() error

Unwrap returns the internal execution cause.

type FacetBucket

type FacetBucket struct {
	Value any   `json:"value"`
	Count int64 `json:"count"`
}

FacetBucket contains one aggregated value and document count.

type FacetMode

type FacetMode string

FacetMode controls whether a facet excludes its own filters.

const (
	// FacetDisjunctive excludes filters on the faceted field when counting buckets.
	FacetDisjunctive FacetMode = "disjunctive"
	// FacetConjunctive applies all filters when counting buckets.
	FacetConjunctive FacetMode = "conjunctive"
)

type FacetRequest

type FacetRequest struct {
	Field          string    `json:"field"`
	Mode           FacetMode `json:"mode,omitempty"`
	Limit          int       `json:"limit,omitempty"`
	Sort           FacetSort `json:"sort,omitempty"`
	IncludeMissing bool      `json:"include_missing,omitempty"`
}

FacetRequest asks the backend to aggregate values for an attribute.

type FacetResult

type FacetResult struct {
	Field   string        `json:"field"`
	Buckets []FacetBucket `json:"buckets"`
}

FacetResult contains the buckets computed for one attribute.

type FacetSort

type FacetSort string

FacetSort selects how facet buckets are ordered.

const (
	// FacetSortCount orders buckets by descending document count.
	FacetSortCount FacetSort = "count"
	// FacetSortValue orders buckets by value.
	FacetSortValue FacetSort = "value"
)

type Filter

type Filter struct {
	Field    string   `json:"field"`
	Operator Operator `json:"operator"`
	Value    any      `json:"value,omitempty"`
	// contains filtered or unexported fields
}

Filter constrains results by comparing an attribute with a value.

type Hit

type Hit struct {
	ID         string         `json:"id"`
	Score      float64        `json:"score,omitempty"`
	Attributes map[string]any `json:"attributes"`
}

Hit is a matched search document and its relevance score.

type InMemSearchEngine

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

InMemSearchEngine provides a lightweight in-memory search Engine implementation.

func NewInMemSearchEngine

func NewInMemSearchEngine() *InMemSearchEngine

NewInMemSearchEngine initializes an in-memory search engine.

func (*InMemSearchEngine) IndexDocument

func (e *InMemSearchEngine) IndexDocument(ctx context.Context, indexName, docID string, payload any) error

IndexDocument stores a document in the named in-memory index.

func (*InMemSearchEngine) Search

func (e *InMemSearchEngine) Search(ctx context.Context, query string) ([]map[string]any, error)

Search queries the legacy default index.

func (*InMemSearchEngine) SearchKeyword

func (e *InMemSearchEngine) SearchKeyword(ctx context.Context, indexName, query string) ([]map[string]any, error)

SearchKeyword returns documents whose IDs contain query, ignoring case.

type MemoryBackend

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

MemoryBackend is a concurrency-safe, process-local Backend implementation.

func NewMemoryBackend

func NewMemoryBackend() *MemoryBackend

NewMemoryBackend creates an empty in-memory backend.

func (*MemoryBackend) Delete

func (b *MemoryBackend) Delete(_ context.Context, resource, documentID string) error

Delete removes a document from process memory.

func (*MemoryBackend) Index

func (b *MemoryBackend) Index(_ context.Context, resource string, _ Schema, document Document) error

Index clones and stores a document in process memory.

func (*MemoryBackend) Name

func (b *MemoryBackend) Name() string

Name identifies this backend as memory.

func (*MemoryBackend) Search

func (b *MemoryBackend) Search(ctx context.Context, resource string, schema Schema, request SearchRequest) (SearchResult, error)

Search evaluates a request against a consistent in-memory snapshot.

type Operator

type Operator string

Operator identifies a filter comparison operation.

const (
	// OperatorEqual matches equal values.
	OperatorEqual Operator = "eq"
	// OperatorNotEqual matches non-equal values.
	OperatorNotEqual Operator = "neq"
	// OperatorIn matches any value in a supplied set.
	OperatorIn Operator = "in"
	// OperatorNotIn excludes values in a supplied set.
	OperatorNotIn Operator = "not_in"
	// OperatorGreaterThan matches values greater than the operand.
	OperatorGreaterThan Operator = "gt"
	// OperatorGreaterOrEq matches values greater than or equal to the operand.
	OperatorGreaterOrEq Operator = "gte"
	// OperatorLessThan matches values less than the operand.
	OperatorLessThan Operator = "lt"
	// OperatorLessOrEq matches values less than or equal to the operand.
	OperatorLessOrEq Operator = "lte"
	// OperatorBetween matches values within an inclusive range.
	OperatorBetween Operator = "between"
	// OperatorContains performs a case-insensitive substring match.
	OperatorContains Operator = "contains"
	// OperatorExists tests whether the attribute is present.
	OperatorExists Operator = "exists"
)

type Registry

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

Registry owns a concurrency-safe collection of named resources.

func NewRegistry

func NewRegistry(resources ...*Resource) (*Registry, error)

NewRegistry creates a registry and rejects nil or duplicate resources.

func (*Registry) Register

func (r *Registry) Register(resource *Resource) error

Register adds a resource if its name is not already registered.

func (*Registry) Resource

func (r *Registry) Resource(name string) (*Resource, bool)

Resource returns a resource and whether it is registered.

func (*Registry) Search

func (r *Registry) Search(ctx context.Context, name string, request SearchRequest) (SearchResult, error)

Search dispatches a request to a registered resource.

type Resource

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

Resource binds a validated schema and optional authorization scope to a backend.

func NewResource

func NewResource(name string, schema Schema, backend Backend, options ...ResourceOption) (*Resource, error)

NewResource validates and creates a named searchable resource.

func (*Resource) Delete

func (r *Resource) Delete(ctx context.Context, documentID string) error

Delete removes a document by ID.

func (*Resource) Index

func (r *Resource) Index(ctx context.Context, document Document) error

Index validates and stores a document.

func (*Resource) Name

func (r *Resource) Name() string

Name returns the stable resource name used by backends and registries.

func (*Resource) Schema

func (r *Resource) Schema() Schema

Schema returns a copy of the resource schema.

func (*Resource) Search

func (r *Resource) Search(ctx context.Context, request SearchRequest) (SearchResult, error)

Search normalizes a request, enforces scope filters, and queries the backend.

type ResourceOption

type ResourceOption func(*Resource) error

ResourceOption configures a Resource during construction.

func WithScope

func WithScope(scope ScopeFunc) ResourceOption

WithScope adds mandatory filters resolved from each request context.

type SQLDatabase

type SQLDatabase interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}

SQLDatabase is the database/sql subset required by DatabaseBackend.

type SQLQuery

type SQLQuery struct {
	Statement string
	Args      []any
}

SQLQuery is a parameterized statement and its ordered arguments.

type Schema

type Schema struct {
	Attributes   map[string]AttributeDefinition `json:"attributes"`
	AllowUnknown bool                           `json:"allow_unknown,omitempty"`
}

Schema defines the accepted attributes for a search resource.

func NewSchema

func NewSchema(definitions ...AttributeDefinition) (Schema, error)

NewSchema validates definitions and creates a schema keyed by attribute name.

func (Schema) NormalizeRequest

func (s Schema) NormalizeRequest(request SearchRequest) (SearchRequest, error)

NormalizeRequest validates a request and applies documented default limits and modes.

func (Schema) ValidateDocument

func (s Schema) ValidateDocument(document Document) error

ValidateDocument verifies an ID and every supplied attribute against the schema.

type ScopeFunc

type ScopeFunc func(ctx context.Context) ([]Filter, error)

ScopeFunc returns mandatory filters for the current request context.

type SearchRequest

type SearchRequest struct {
	Query   string         `json:"query,omitempty"`
	Filters []Filter       `json:"filters,omitempty"`
	Facets  []FacetRequest `json:"facets,omitempty"`
	Sort    []Sort         `json:"sort,omitempty"`
	Cursor  string         `json:"cursor,omitempty"`
	Limit   int            `json:"limit,omitempty"`
}

SearchRequest contains a validated keyword, filter, facet, sort, and page request.

type SearchResult

type SearchResult struct {
	Items      []Hit                  `json:"items"`
	Total      int64                  `json:"total"`
	Facets     map[string]FacetResult `json:"facets,omitempty"`
	NextCursor string                 `json:"next_cursor,omitempty"`
	Backend    string                 `json:"backend"`
}

SearchResult is the backend-independent response returned for a search request.

type Sort

type Sort struct {
	Field     string        `json:"field"`
	Direction SortDirection `json:"direction,omitempty"`
}

Sort defines one ordered result field.

type SortDirection

type SortDirection string

SortDirection specifies ascending or descending result order.

const (
	// SortAscending orders smaller values first.
	SortAscending SortDirection = "asc"
	// SortDescending orders larger values first.
	SortDescending SortDirection = "desc"
)

Jump to

Keyboard shortcuts

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