Documentation
¶
Overview ¶
Package search provides portable lexical search over explicitly defined indexes. Indexes are derived data: keep an authoritative source from which to rebuild. Drivers select storage and ranking; applications retain their search contract.
Index ¶
- Constants
- Variables
- func Decode[T any](d Document) (T, error)
- func SafeError(err error) error
- type AsyncObserver
- type Backend
- type Bucket
- type BulkOutcome
- type BulkResult
- type CountPrecision
- type DecodeError
- type Definition
- type Direction
- type Document
- type DocumentID
- type Event
- type EventPhase
- type FacetResult
- type Field
- type FieldName
- type FieldType
- type Filter
- func And(f ...Filter) Filter
- func Between(f FieldName, a, b Value) Filter
- func ContainsAll(f FieldName, v ...Value) Filter
- func ContainsAny(f FieldName, v ...Value) Filter
- func Equal(f FieldName, v Value) Filter
- func Exists(f FieldName) Filter
- func GreaterThan(f FieldName, v Value) Filter
- func GreaterThanOrEqual(f FieldName, v Value) Filter
- func In(f FieldName, v ...Value) Filter
- func LessThan(f FieldName, v Value) Filter
- func LessThanOrEqual(f FieldName, v Value) Filter
- func Not(f Filter) Filter
- func Or(f ...Filter) Filter
- type FilterKind
- type FilterView
- type Fragment
- type Highlight
- type Hit
- type HitOf
- type Index
- func (i *Index) Bulk(ctx context.Context, ms []Mutation) (BulkResult, error)
- func (i *Index) Definition() Definition
- func (i *Index) Delete(ctx context.Context, id DocumentID) (Receipt, error)
- func (i *Index) Search(ctx context.Context, q Query) (Result, error)
- func (i *Index) Upsert(ctx context.Context, d Document) (Receipt, error)
- func (i *Index) Wait(ctx context.Context, r Receipt) (Outcome, error)
- type IndexName
- type ItemOutcomePrecision
- type ItemResult
- type ItemStatus
- type JSONPointer
- type Limits
- type MultiObserver
- type Mutation
- type MutationKind
- type Observer
- type ObserverFunc
- type Option
- type Outcome
- type OutcomeState
- type Page
- type Query
- type Receipt
- type Result
- type Segment
- type Sort
- type TermFacet
- type Total
- type TotalRelation
- type UnknownOutcomeError
- type Value
- type ValueKind
Constants ¶
const ( // KeywordValue represents an exact UTF-8 string. KeywordValue ValueKind = "keyword" // BooleanValue represents a Boolean. BooleanValue ValueKind = "boolean" // IntegerValue represents an exactly portable signed integer. IntegerValue ValueKind = "integer" // MaxInteger is the largest exactly portable integer. MaxInteger int64 = 1<<53 - 1 )
Variables ¶
var ErrClosed = errors.New("search: closed")
ErrClosed identifies a closed driver.
var ErrConflict = errors.New("search: conflict")
ErrConflict identifies a competing owner or conflicting request.
var ErrIndexNotFound = errors.New("search: index not found")
ErrIndexNotFound identifies an unprovisioned index.
var ErrInvalidDefinition = errors.New("search: invalid definition")
ErrInvalidDefinition identifies an invalid schema.
var ErrInvalidDocument = errors.New("search: invalid document")
ErrInvalidDocument identifies invalid document input.
var ErrInvalidQuery = errors.New("search: invalid query")
ErrInvalidQuery identifies invalid query input.
var ErrInvalidReceipt = errors.New("search: invalid receipt")
ErrInvalidReceipt identifies a forged, foreign, or empty receipt.
var ErrMutationFailed = errors.New("search: mutation failed")
ErrMutationFailed identifies accepted work that failed.
var ErrNotFound = errors.New("search: document not found")
ErrNotFound identifies a missing document.
var ErrOutcomeUnknown = errors.New("search: mutation outcome unknown")
ErrOutcomeUnknown means work may have been accepted and must be reconciled.
var ErrRateLimited = errors.New("search: rate limited")
ErrRateLimited identifies throttling.
var ErrReceiptExpired = errors.New("search: receipt expired")
ErrReceiptExpired identifies accepted work whose result is no longer retained.
var ErrSchemaDrift = errors.New("search: schema drift")
ErrSchemaDrift identifies a difference from the provisioned schema.
ErrUnauthorized identifies rejected credentials or permissions.
ErrUnavailable identifies a failed connection or incomplete backend response.
var ErrUnsupported = errors.New("search: unsupported operation")
ErrUnsupported identifies an unavailable backend capability.
Functions ¶
Types ¶
type AsyncObserver ¶
type AsyncObserver struct {
// contains filtered or unexported fields
}
AsyncObserver delivers retained events in FIFO order from one bounded worker. Applications own Shutdown; an observer that blocks indefinitely also blocks its worker.
func NewAsyncObserver ¶
func NewAsyncObserver(observer Observer, capacity int) (*AsyncObserver, error)
NewAsyncObserver starts a single delivery worker with capacity from 1 to 65536. @group Observability
func (*AsyncObserver) Dropped ¶
func (a *AsyncObserver) Dropped() uint64
Dropped reports the cumulative number of events discarded by bounded delivery. @group Observability
type Backend ¶
type Backend interface {
Search(context.Context, Definition, Query) (Result, error)
Upsert(context.Context, Definition, Document) (Receipt, error)
Delete(context.Context, Definition, DocumentID) (Receipt, error)
Bulk(context.Context, Definition, []Mutation) (BulkResult, error)
Wait(context.Context, Receipt) (Outcome, error)
}
Backend is the consumer-owned request-path contract implemented by concrete drivers. Implementations must support concurrent calls and return caller-owned response collections.
type BulkOutcome ¶
type BulkOutcome struct {
Items []ItemResult
Precision ItemOutcomePrecision
}
BulkOutcome retains terminal per-item evidence without inventing precision.
type BulkResult ¶
type BulkResult struct {
Receipt Receipt
Items []ItemResult
Precision ItemOutcomePrecision
}
BulkResult retains submission precision and accepted-work receipt.
type CountPrecision ¶
type CountPrecision string
CountPrecision describes term-bucket count accuracy.
const ( // CountExact reports complete term counts. CountExact CountPrecision = "exact" // CountEstimated reports approximate term counts. CountEstimated CountPrecision = "estimated" )
type DecodeError ¶
type DecodeError struct {
ID DocumentID
}
DecodeError identifies a malformed typed hit without disclosing its contents.
func (*DecodeError) Error ¶
func (e *DecodeError) Error() string
Error reports only the classification; callers may inspect ID under their disclosure policy. @group Results
func (*DecodeError) Unwrap ¶
func (e *DecodeError) Unwrap() error
Unwrap preserves invalid-document classification. @group Results
type Definition ¶
type Definition struct {
Name IndexName
Fields []Field
DefaultSearchable []FieldName
DefaultSort []Sort
}
Definition describes rebuildable index data and default query behavior.
func (Definition) Fingerprint ¶
func (d Definition) Fingerprint() (string, error)
Fingerprint returns a versioned canonical hash of the normalized search contract. @group Definitions
func (Definition) Validate ¶
func (d Definition) Validate() error
Validate checks a definition with conservative default limits. @group Definitions
type Document ¶
type Document struct {
ID DocumentID
Body json.RawMessage
}
Document retains explicit identity separately from application-owned JSON.
type Event ¶
type Event struct {
Kind string
ReceiptID string
Phase EventPhase
Index IndexName
Duration time.Duration
DocumentCount int
HitCount int
TotalRelation TotalRelation
ErrorCode string
Outcome string
}
Event contains bounded metadata without document, query, or backend prose.
type EventPhase ¶
type EventPhase string
EventPhase distinguishes submission latency from visibility and search latency.
const ( // PhaseSubmission identifies accepted-work submission. PhaseSubmission EventPhase = "submission" // PhaseTerminal identifies terminal mutation observation. PhaseTerminal EventPhase = "terminal" // PhaseSearchComplete identifies a complete search call. PhaseSearchComplete EventPhase = "search_complete" )
type FacetResult ¶
type FacetResult struct {
Name string
Field FieldName
Buckets []Bucket
Precision CountPrecision
Truncated bool
}
FacetResult retains truncation separately from count precision.
type Field ¶
type Field struct {
Name FieldName
Path JSONPointer
Type FieldType
Required bool
Searchable bool
Filterable bool
Sortable bool
Facetable bool
}
Field maps one declared name to an explicit document path.
type FieldName ¶
type FieldName string
FieldName identifies a declared mapping, independently of its JSON path.
type FieldType ¶
type FieldType string
FieldType defines the portable mapping shapes.
const ( // TextField enables analyzed full-text matching only. TextField FieldType = "text" // KeywordField enables exact scalar operations. KeywordField FieldType = "keyword" // BooleanField enables Boolean filtering, ordering, and facets. BooleanField FieldType = "boolean" // IntegerField enables exact integer filtering and ordering. IntegerField FieldType = "integer" // KeywordsField enables array membership and term facets. KeywordsField FieldType = "keywords" )
type Filter ¶
type Filter struct {
// contains filtered or unexported fields
}
Filter is an immutable expression. A zero filter means no predicate on Query only.
func And ¶
And combines predicates without allowing caller mutation of the child slice. @group Filters
func ContainsAll ¶
ContainsAll tests whether an array contains a nonempty set. @group Filters
func ContainsAny ¶
ContainsAny tests array intersection with a nonempty set. @group Filters
func GreaterThan ¶
GreaterThan compares an integer against an exclusive lower bound. @group Filters
func GreaterThanOrEqual ¶
GreaterThanOrEqual compares an integer against an inclusive lower bound. @group Filters
func LessThanOrEqual ¶
LessThanOrEqual compares an integer against an inclusive upper bound. @group Filters
func (Filter) View ¶
func (f Filter) View() FilterView
View returns cloned collections so compilers cannot alter the expression. @group Filters
type FilterKind ¶
type FilterKind string
FilterKind identifies an immutable expression node.
const ( // FilterAnd applies conjunction, with an empty conjunction matching all. FilterAnd FilterKind = "and" // FilterOr applies disjunction, with an empty disjunction matching none. FilterOr FilterKind = "or" // FilterNot complements its child's two-valued result. FilterNot FilterKind = "not" // FilterEqual compares an exact scalar. FilterEqual FilterKind = "equal" // FilterIn tests membership in a scalar set. FilterIn FilterKind = "in" // FilterContainsAny tests at least one array member. FilterContainsAny FilterKind = "contains_any" // FilterContainsAll tests every requested array member. FilterContainsAll FilterKind = "contains_all" // FilterLessThan compares integers exclusively. FilterLessThan FilterKind = "less_than" // FilterLessThanOrEqual compares integers inclusively. FilterLessThanOrEqual FilterKind = "less_than_or_equal" // FilterGreaterThan compares integers exclusively. FilterGreaterThan FilterKind = "greater_than" // FilterGreaterThanOrEqual compares integers inclusively. FilterGreaterThanOrEqual FilterKind = "greater_than_or_equal" // FilterBetween tests an inclusive integer interval. FilterBetween FilterKind = "between" // FilterExists tests presence of a non-null value, including an empty array. FilterExists FilterKind = "exists" )
type FilterView ¶
type FilterView struct {
Kind FilterKind
Field FieldName
Values []Value
Children []Filter
}
FilterView is a detached driver-facing expression view.
type Fragment ¶
type Fragment struct {
Segments []Segment
}
Fragment groups adjacent highlight segments.
type Highlight ¶
type Highlight struct {
Field FieldName
}
Highlight requests untrusted text segments for one searchable field.
type Hit ¶
type Hit struct {
Document Document
Score *float64
SortValues []Value
Highlights map[FieldName][]Fragment
}
Hit is one document and its response-local ranking metadata.
type HitOf ¶
type HitOf[T any] struct { ID DocumentID Value T Score *float64 SortValues []Value Highlights map[FieldName][]Fragment }
HitOf is a typed hit whose document need not contain its identity.
type Index ¶
type Index struct {
// contains filtered or unexported fields
}
Index validates calls and owns its immutable definition. It is safe for concurrent use.
func NewIndex ¶
func NewIndex(b Backend, d Definition, opts ...Option) (*Index, error)
NewIndex validates a definition without performing backend I/O or schema mutation. @group Construction
func (*Index) Bulk ¶
Bulk rejects duplicate IDs and validates the entire bounded batch before submission. @group Mutations
func (*Index) Definition ¶
func (i *Index) Definition() Definition
Definition returns an owned copy of the normalized definition. @group Definitions
func (*Index) Delete ¶
Delete removes an ID idempotently; visibility is established through Wait. @group Mutations
func (*Index) Search ¶
Search validates literal text, filters, limits, and result documents before exposure. @group Queries
type ItemOutcomePrecision ¶
type ItemOutcomePrecision string
ItemOutcomePrecision prevents aggregate success from implying individual success.
const ( // PerItem means every item has an individually proven outcome. PerItem ItemOutcomePrecision = "per_item" // BatchOnly means only the aggregate outcome is known. BatchOnly ItemOutcomePrecision = "batch_only" )
type ItemResult ¶
type ItemResult struct {
Position int
ID DocumentID
Status ItemStatus
Error error
}
ItemResult preserves the input position even when the backend reorders work.
type ItemStatus ¶
type ItemStatus string
ItemStatus retains submission and terminal states separately.
const ( // ItemAccepted reports proven submission only. ItemAccepted ItemStatus = "accepted" // ItemRejected reports a submission rejection. ItemRejected ItemStatus = "rejected" // ItemUnknown reports an unprovable individual outcome. ItemUnknown ItemStatus = "unknown" // ItemSucceeded reports proven per-item visibility. ItemSucceeded ItemStatus = "succeeded" // ItemFailed reports proven per-item failure. ItemFailed ItemStatus = "failed" )
type Limits ¶
type Limits struct {
NameBytes int
DefinitionBytes int
DocumentBytes int
JSONDepth int
ObjectMembers int
ArrayLength int
DefinitionFields int
JSONPointerDepth int
TextBytes int
QueryBytes int
QueryTerms int
QueryFields int
FilterNodes int
FilterDepth int
FilterValues int
FilterValueBytes int
FacetNameBytes int
ResultLimit uint64
ResultWindow uint64
Facets int
HighlightFields int
BulkDocuments int
BulkBytes int
}
Limits bounds work before it reaches a backend. Zero option fields inherit defaults.
func DefaultLimits ¶
func DefaultLimits() Limits
DefaultLimits returns conservative allocation and backend-work budgets. @group Construction
type MultiObserver ¶
type MultiObserver []Observer
MultiObserver delivers events in registration order with independent panic isolation.
type Mutation ¶
type Mutation struct {
// contains filtered or unexported fields
}
Mutation is an immutable tagged operation whose zero value is invalid.
func DeleteMutation ¶
func DeleteMutation(id DocumentID) (Mutation, error)
DeleteMutation validates an ID for idempotent deletion. @group Mutations
func UpsertMutation ¶
UpsertMutation takes ownership of document bytes after structural validation. @group Mutations
func (Mutation) ID ¶
func (m Mutation) ID() DocumentID
ID returns the explicit document identity. @group Mutations
func (Mutation) Kind ¶
func (m Mutation) Kind() MutationKind
Kind identifies which operation this mutation contains. @group Mutations
type MutationKind ¶
type MutationKind string
MutationKind distinguishes complete replacement from idempotent deletion.
const ( // MutationUpsert replaces a complete document. MutationUpsert MutationKind = "upsert" // MutationDelete removes an ID if present. MutationDelete MutationKind = "delete" )
type ObserverFunc ¶
ObserverFunc adapts an application callback to an Observer.
type Option ¶
Option configures domain limits or safe observation before the handle is published.
func WithLimits ¶
WithLimits replaces nonzero limits, up to sixteen times each default ceiling. @group Construction
func WithObserver ¶
WithObserver attaches synchronous, panic-isolated observation without retaining contexts. @group Construction
type Outcome ¶
type Outcome struct {
State OutcomeState
VisibleAt time.Time
Bulk *BulkOutcome
Error error
}
Outcome returns terminal failure as data, keeping any bulk details available.
type OutcomeState ¶
type OutcomeState string
OutcomeState describes a trustworthy terminal mutation outcome.
const ( // OutcomeSucceeded proves visibility to subsequent queries on this index. OutcomeSucceeded OutcomeState = "succeeded" // OutcomeFailed identifies terminal failure. OutcomeFailed OutcomeState = "failed" // OutcomeUnknown identifies accepted work whose terminal result cannot be proved. OutcomeUnknown OutcomeState = "unknown" )
type Query ¶
type Query struct {
Text string
Fields []FieldName
Filter Filter
Sort []Sort
Facets []TermFacet
Highlight []Highlight
Offset uint64
Limit uint64
}
Query specifies literal all-terms text, typed filtering, and bounded pagination.
type Receipt ¶
type Receipt struct {
// contains filtered or unexported fields
}
Receipt is an opaque, immutable process-local accepted-work token.
func NewReceipt ¶
NewReceipt creates a bounded driver token without attaching it to an Index. @group Receipts
type Result ¶
type Result struct {
Hits []Hit
Total Total
Facets []FacetResult
Took time.Duration
}
Result contains one complete backend search response.
type Total ¶
type Total struct {
Value uint64
Relation TotalRelation
}
Total retains count precision independently of pagination.
type TotalRelation ¶
type TotalRelation string
TotalRelation describes the accuracy of a result count.
const ( // TotalExact reports a complete count. TotalExact TotalRelation = "exact" // TotalEstimated reports an approximate count. TotalEstimated TotalRelation = "estimated" // TotalLowerBound reports a proven minimum. TotalLowerBound TotalRelation = "lower_bound" )
type UnknownOutcomeError ¶
type UnknownOutcomeError struct {
// contains filtered or unexported fields
}
UnknownOutcomeError retains recoverable accepted-work evidence without exposing backend prose.
func NewUnknownOutcomeError ¶
func NewUnknownOutcomeError(receipt Receipt) *UnknownOutcomeError
NewUnknownOutcomeError lets a driver return recoverable evidence after uncertain submission. @group Receipts
func (*UnknownOutcomeError) Error ¶
func (e *UnknownOutcomeError) Error() string
Error reports uncertainty without serializing the opaque token. @group Receipts
func (*UnknownOutcomeError) Receipt ¶
func (e *UnknownOutcomeError) Receipt() (Receipt, bool)
Receipt returns immutable recovery evidence when the driver obtained a trustworthy token. @group Receipts
func (*UnknownOutcomeError) Unwrap ¶
func (e *UnknownOutcomeError) Unwrap() error
Unwrap preserves the stable uncertainty classification. @group Receipts
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value is an immutable typed filter, facet, or sort scalar. Its zero value is invalid.
func (Value) MarshalJSON ¶
MarshalJSON preserves a Value's scalar JSON shape for typed result DTOs and rejects its invalid zero value. @group Values
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
driver
|
|
|
elasticsearch
Package elasticsearch implements service-backed lexical search with Elasticsearch.
|
Package elasticsearch implements service-backed lexical search with Elasticsearch. |
|
meilisearch
Package meilisearch implements asynchronous service-backed lexical search.
|
Package meilisearch implements asynchronous service-backed lexical search. |
|
opensearch
Package opensearch implements service-backed lexical search with OpenSearch.
|
Package opensearch implements service-backed lexical search with OpenSearch. |
|
postgressearch
Package postgressearch implements portable lexical search using PostgreSQL full-text search.
|
Package postgressearch implements portable lexical search using PostgreSQL full-text search. |
|
redissearch
Package redissearch implements bounded, exact lexical search with Redis Search on a standalone Redis service.
|
Package redissearch implements bounded, exact lexical search with Redis Search on a standalone Redis service. |
|
sqlitesearch
Package sqlitesearch implements portable lexical search using SQLite FTS5.
|
Package sqlitesearch implements portable lexical search using SQLite FTS5. |
|
typesensesearch
Package typesensesearch implements service-backed search with Typesense.
|
Package typesensesearch implements service-backed search with Typesense. |
|
blevesearch
module
|
|
|
internal
|
|
|
driverutil
Package driverutil implements physical encoding shared by first-party drivers.
|
Package driverutil implements physical encoding shared by first-party drivers. |
|
sqlsearch
Package sqlsearch implements transactional storage shared by native SQL full-text drivers.
|
Package sqlsearch implements transactional storage shared by native SQL full-text drivers. |
|
Package searchfake supplies a scripted backend for isolated application tests.
|
Package searchfake supplies a scripted backend for isolated application tests. |
|
Package searchtest supplies reusable semantic fixtures for real backend drivers.
|
Package searchtest supplies reusable semantic fixtures for real backend drivers. |