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
- Variables
- type AttributeDefinition
- type AttributeType
- type Backend
- type Client
- type DatabaseBackend
- func (b *DatabaseBackend) Compile(resource string, schema Schema, request SearchRequest) (DatabaseQueryPlan, error)
- func (b *DatabaseBackend) Delete(ctx context.Context, resource, documentID string) error
- func (b *DatabaseBackend) Index(ctx context.Context, resource string, schema Schema, document Document) error
- func (b *DatabaseBackend) Name() string
- func (b *DatabaseBackend) Search(ctx context.Context, resource string, schema Schema, request SearchRequest) (SearchResult, error)
- func (b *DatabaseBackend) Setup(ctx context.Context) error
- type DatabaseConfig
- type DatabaseQueryPlan
- type Document
- type ESClient
- type ESConfig
- type Engine
- type ExecutionError
- type FacetBucket
- type FacetMode
- type FacetRequest
- type FacetResult
- type FacetSort
- type Filter
- type Hit
- type InMemSearchEngine
- func (e *InMemSearchEngine) IndexDocument(ctx context.Context, indexName, docID string, payload any) error
- func (e *InMemSearchEngine) Search(ctx context.Context, query string) ([]map[string]any, error)
- func (e *InMemSearchEngine) SearchKeyword(ctx context.Context, indexName, query string) ([]map[string]any, error)
- type MemoryBackend
- func (b *MemoryBackend) Delete(_ context.Context, resource, documentID string) error
- func (b *MemoryBackend) Index(_ context.Context, resource string, _ Schema, document Document) error
- func (b *MemoryBackend) Name() string
- func (b *MemoryBackend) Search(ctx context.Context, resource string, schema Schema, request SearchRequest) (SearchResult, error)
- type Operator
- type Registry
- type Resource
- func (r *Resource) Delete(ctx context.Context, documentID string) error
- func (r *Resource) Index(ctx context.Context, document Document) error
- func (r *Resource) Name() string
- func (r *Resource) Schema() Schema
- func (r *Resource) Search(ctx context.Context, request SearchRequest) (SearchResult, error)
- type ResourceOption
- type SQLDatabase
- type SQLQuery
- type Schema
- type ScopeFunc
- type SearchRequest
- type SearchResult
- type Sort
- type SortDirection
Constants ¶
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 ¶
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.
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.
type DatabaseConfig ¶
type DatabaseConfig struct {
Table string
}
DatabaseConfig configures the PostgreSQL search document table.
type DatabaseQueryPlan ¶
DatabaseQueryPlan contains the SQL generated for one normalized search request.
type ESClient ¶
type ESClient struct {
// contains filtered or unexported fields
}
ESClient manages Elasticsearch indexing and full-text keyword queries.
func NewElasticsearchClient ¶
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 ¶
FacetBucket contains one aggregated value and document count.
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 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) 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 ¶
NewRegistry creates a registry and rejects nil or duplicate resources.
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) 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 ¶
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 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 ¶
ValidateDocument verifies an ID and every supplied attribute against the schema.
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" )