Documentation
¶
Overview ¶
Package mygram is a Go client library for the MygramDB full-text search engine.
MygramDB is an in-memory full-text search engine using a memcached-style text protocol, providing 25-200x faster search performance compared to MySQL FULLTEXT.
Basic usage:
client := mygram.NewClient("localhost:11016")
defer client.Close()
if err := client.Connect(); err != nil {
log.Fatal(err)
}
resp, err := client.Search("threads", "keyword", mygram.SearchOptions{
Limit: 100,
SortColumn: "created_at",
SortDesc: true,
})
Index ¶
- func ConvertSearchExpression(expression string) (string, error)
- func HasComplexExpression(expr *SearchExpression) bool
- func ParseTableIdentity(identity string) (database, table string, err error)
- func QualifyTableIdentity(table, database string) (string, error)
- func ToQueryString(expr *SearchExpression) string
- type CacheStats
- type CircuitBreakerConfig
- type CircuitOpenError
- type Client
- func (c *Client) CacheClear(table string) error
- func (c *Client) CacheClearContext(ctx context.Context, table string) error
- func (c *Client) CacheDisable() error
- func (c *Client) CacheDisableContext(ctx context.Context) error
- func (c *Client) CacheEnable() error
- func (c *Client) CacheEnableContext(ctx context.Context) error
- func (c *Client) CacheStats() (*CacheStats, error)
- func (c *Client) CacheStatsContext(ctx context.Context) (*CacheStats, error)
- func (c *Client) Close() error
- func (c *Client) Connect() error
- func (c *Client) ConnectContext(ctx context.Context) error
- func (c *Client) Count(table, query string, opts CountOptions) (*CountResponse, error)
- func (c *Client) CountContext(ctx context.Context, table, query string, opts CountOptions) (*CountResponse, error)
- func (c *Client) DisableDebug() error
- func (c *Client) DisableDebugContext(ctx context.Context) error
- func (c *Client) DumpInfo(filepath string) (string, error)
- func (c *Client) DumpInfoContext(ctx context.Context, filepath string) (string, error)
- func (c *Client) DumpLoad(filepath string) error
- func (c *Client) DumpLoadContext(ctx context.Context, filepath string) error
- func (c *Client) DumpSave(filepath string) (string, error)
- func (c *Client) DumpSaveContext(ctx context.Context, filepath string) (string, error)
- func (c *Client) DumpStatus() (*DumpStatus, error)
- func (c *Client) DumpStatusContext(ctx context.Context) (*DumpStatus, error)
- func (c *Client) DumpVerify(filepath string) (string, error)
- func (c *Client) DumpVerifyContext(ctx context.Context, filepath string) (string, error)
- func (c *Client) EnableDebug() error
- func (c *Client) EnableDebugContext(ctx context.Context) error
- func (c *Client) Facet(table, column string, opts FacetOptions) (*FacetResponse, error)
- func (c *Client) FacetContext(ctx context.Context, table, column string, opts FacetOptions) (*FacetResponse, error)
- func (c *Client) Get(table, primaryKey string) (*Document, error)
- func (c *Client) GetConfig() (string, error)
- func (c *Client) GetConfigContext(ctx context.Context) (string, error)
- func (c *Client) GetContext(ctx context.Context, table, primaryKey string) (*Document, error)
- func (c *Client) GetReplicationStatus() (*ReplicationStatus, error)
- func (c *Client) GetReplicationStatusContext(ctx context.Context) (*ReplicationStatus, error)
- func (c *Client) Info() (*ServerInfo, error)
- func (c *Client) InfoContext(ctx context.Context) (*ServerInfo, error)
- func (c *Client) IsConnected() bool
- func (c *Client) Optimize(table string) error
- func (c *Client) OptimizeContext(ctx context.Context, table string) error
- func (c *Client) Search(table, query string, opts SearchOptions) (*SearchResponse, error)
- func (c *Client) SearchContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
- func (c *Client) SearchRaw(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (c *Client) SearchRawContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (c *Client) SearchRawWithHighlights(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (c *Client) SearchRawWithHighlightsContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (c *Client) SearchWithHighlights(table, query string, opts SearchOptions) (*SearchResponse, error)
- func (c *Client) SearchWithHighlightsContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
- func (c *Client) SendCommand(command string) (string, error)
- func (c *Client) SendCommandContext(ctx context.Context, command string) (string, error)
- func (c *Client) SetVariable(name, value string) error
- func (c *Client) SetVariableContext(ctx context.Context, name, value string) error
- func (c *Client) ShowVariables(likePattern string) (string, error)
- func (c *Client) ShowVariablesContext(ctx context.Context, likePattern string) (string, error)
- func (c *Client) StartReplication() error
- func (c *Client) StartReplicationContext(ctx context.Context) error
- func (c *Client) StopReplication() error
- func (c *Client) StopReplicationContext(ctx context.Context) error
- func (c *Client) Sync(table string) (string, error)
- func (c *Client) SyncContext(ctx context.Context, table string) (string, error)
- func (c *Client) SyncStatus() (string, error)
- func (c *Client) SyncStatusContext(ctx context.Context) (string, error)
- func (c *Client) SyncStop(table string) (string, error)
- func (c *Client) SyncStopContext(ctx context.Context, table string) (string, error)
- type ClientConfig
- type ConnectionError
- type CountOptions
- type CountResponse
- type DebugInfo
- type Document
- type DumpStatus
- type FacetOptions
- type FacetResponse
- type FacetValue
- type HighlightOptions
- type Pool
- func (p *Pool) CacheClear(table string) error
- func (p *Pool) CacheClearContext(ctx context.Context, table string) error
- func (p *Pool) CacheDisable() error
- func (p *Pool) CacheDisableContext(ctx context.Context) error
- func (p *Pool) CacheEnable() error
- func (p *Pool) CacheEnableContext(ctx context.Context) error
- func (p *Pool) CacheStats() (*CacheStats, error)
- func (p *Pool) CacheStatsContext(ctx context.Context) (*CacheStats, error)
- func (p *Pool) Close() error
- func (p *Pool) Count(table, query string, opts CountOptions) (*CountResponse, error)
- func (p *Pool) CountContext(ctx context.Context, table, query string, opts CountOptions) (*CountResponse, error)
- func (p *Pool) DisableDebug() error
- func (p *Pool) DisableDebugContext(ctx context.Context) error
- func (p *Pool) DumpInfo(filepath string) (string, error)
- func (p *Pool) DumpInfoContext(ctx context.Context, filepath string) (string, error)
- func (p *Pool) DumpLoad(filepath string) error
- func (p *Pool) DumpLoadContext(ctx context.Context, filepath string) error
- func (p *Pool) DumpSave(filepath string) (string, error)
- func (p *Pool) DumpSaveContext(ctx context.Context, filepath string) (string, error)
- func (p *Pool) DumpStatus() (*DumpStatus, error)
- func (p *Pool) DumpStatusContext(ctx context.Context) (*DumpStatus, error)
- func (p *Pool) DumpVerify(filepath string) (string, error)
- func (p *Pool) DumpVerifyContext(ctx context.Context, filepath string) (string, error)
- func (p *Pool) EnableDebug() error
- func (p *Pool) EnableDebugContext(ctx context.Context) error
- func (p *Pool) Facet(table, column string, opts FacetOptions) (*FacetResponse, error)
- func (p *Pool) FacetContext(ctx context.Context, table, column string, opts FacetOptions) (*FacetResponse, error)
- func (p *Pool) Get(table, primaryKey string) (*Document, error)
- func (p *Pool) GetConfig() (string, error)
- func (p *Pool) GetConfigContext(ctx context.Context) (string, error)
- func (p *Pool) GetContext(ctx context.Context, table, primaryKey string) (*Document, error)
- func (p *Pool) GetReplicationStatus() (*ReplicationStatus, error)
- func (p *Pool) GetReplicationStatusContext(ctx context.Context) (*ReplicationStatus, error)
- func (p *Pool) Info() (*ServerInfo, error)
- func (p *Pool) InfoContext(ctx context.Context) (*ServerInfo, error)
- func (p *Pool) Optimize(table string) error
- func (p *Pool) OptimizeContext(ctx context.Context, table string) error
- func (p *Pool) Search(table, query string, opts SearchOptions) (*SearchResponse, error)
- func (p *Pool) SearchContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
- func (p *Pool) SearchRaw(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (p *Pool) SearchRawContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (p *Pool) SearchRawWithHighlights(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (p *Pool) SearchRawWithHighlightsContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (p *Pool) SearchWithHighlights(table, query string, opts SearchOptions) (*SearchResponse, error)
- func (p *Pool) SearchWithHighlightsContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
- func (p *Pool) SendCommand(command string) (string, error)
- func (p *Pool) SendCommandContext(ctx context.Context, command string) (string, error)
- func (p *Pool) SetVariable(name, value string) error
- func (p *Pool) SetVariableContext(ctx context.Context, name, value string) error
- func (p *Pool) ShowVariables(likePattern string) (string, error)
- func (p *Pool) ShowVariablesContext(ctx context.Context, likePattern string) (string, error)
- func (p *Pool) StartReplication() error
- func (p *Pool) StartReplicationContext(ctx context.Context) error
- func (p *Pool) Stats() PoolStats
- func (p *Pool) StopReplication() error
- func (p *Pool) StopReplicationContext(ctx context.Context) error
- func (p *Pool) Sync(table string) (string, error)
- func (p *Pool) SyncContext(ctx context.Context, table string) (string, error)
- func (p *Pool) SyncStatus() (string, error)
- func (p *Pool) SyncStatusContext(ctx context.Context) (string, error)
- func (p *Pool) SyncStop(table string) (string, error)
- func (p *Pool) SyncStopContext(ctx context.Context, table string) (string, error)
- func (p *Pool) WithConn(ctx context.Context, fn func(c *Client) error) error
- type PoolConfig
- type PoolEvent
- type PoolStats
- type ProtocolError
- type ReplicationStatus
- type RetryPolicy
- type SearchExpression
- type SearchOptions
- type SearchRawOptions
- type SearchResponse
- type SearchResult
- type ServerError
- type ServerInfo
- type SimplifiedExpression
- type TimeoutError
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ConvertSearchExpression ¶
ConvertSearchExpression converts a search expression to a MygramDB query string.
func HasComplexExpression ¶
func HasComplexExpression(expr *SearchExpression) bool
HasComplexExpression returns whether the expression contains OR or grouping.
func ParseTableIdentity ¶ added in v0.3.0
ParseTableIdentity splits a (possibly database-qualified) table identity into its parts.
Bare names return an empty database and the table name; qualified names are split on the first '.' so "app_db.articles" yields ("app_db", "articles"). The identity is validated as a protocol identifier first.
func QualifyTableIdentity ¶ added in v0.3.0
QualifyTableIdentity builds a database-qualified table identity ("database.table") for MygramDB v1.7+ multi-database deployments.
A single-database deployment continues to accept a bare table name, so an empty database returns just the validated table name. When a database is supplied, both parts are validated as identifiers and must not themselves contain a '.' separator; they are then joined as "database.table".
func ToQueryString ¶
func ToQueryString(expr *SearchExpression) string
ToQueryString converts a SearchExpression to a MygramDB query string.
Types ¶
type CacheStats ¶
type CacheStats struct {
Enabled bool
Hits int
Misses int
HitRate float64
CurrentEntries int
MemoryBytes int
Evictions int
}
CacheStats represents cache statistics.
type CircuitBreakerConfig ¶ added in v0.4.0
type CircuitBreakerConfig struct {
// FailureThreshold is the number of consecutive network failures that open
// the breaker. 0 or negative selects the default (5).
FailureThreshold int
// ResetTimeout is how long the breaker stays open before admitting a trial.
// 0 or negative selects the default (10s).
ResetTimeout time.Duration
}
CircuitBreakerConfig configures a Pool's circuit breaker. Consecutive connect/timeout failures up to FailureThreshold open the breaker; it stays open for ResetTimeout, then admits a single trial (half-open) before closing on success or re-opening on failure. Set PoolConfig.CircuitBreaker to enable it; a nil pointer disables it.
type CircuitOpenError ¶ added in v0.4.0
type CircuitOpenError struct {
Message string
}
CircuitOpenError is returned by a Pool whose circuit breaker is open (or half-open with a trial already in flight). It is raised without touching the network so a caller fails fast instead of piling requests onto a server that is already unreachable. It is not classified as a network failure, so it does not itself drive the breaker.
func (*CircuitOpenError) Error ¶ added in v0.4.0
func (e *CircuitOpenError) Error() string
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a MygramDB client.
A Client wraps a single connection and serializes every command with an internal mutex, so it is safe for concurrent use but processes at most one request at a time. For concurrent workloads use a Pool, which lends out many Clients and adds reconnection and retry.
func NewClient ¶
NewClient creates a new client for the given address. addr should be in "host:port" form; an address that does not parse as host:port is treated as a Unix socket path (so a bare "localhost" without a port becomes a socket path, not a TCP host).
The returned Client owns a single connection and must be connected with Connect (or ConnectContext) before issuing commands. Most applications should use NewPool instead, which manages many connections with reconnection and retry; use Client directly only to own and control a single connection.
func NewClientWithConfig ¶
func NewClientWithConfig(config ClientConfig) *Client
NewClientWithConfig creates a new client with the given configuration.
func (*Client) CacheClear ¶
CacheClear clears the cache. If table is specified, only that table's cache is cleared.
func (*Client) CacheClearContext ¶
CacheClearContext clears the cache with the given context.
func (*Client) CacheDisable ¶
CacheDisable disables the cache.
func (*Client) CacheDisableContext ¶
CacheDisableContext disables the cache with the given context.
func (*Client) CacheEnableContext ¶
CacheEnableContext enables the cache with the given context.
func (*Client) CacheStats ¶
func (c *Client) CacheStats() (*CacheStats, error)
CacheStats retrieves cache statistics.
func (*Client) CacheStatsContext ¶
func (c *Client) CacheStatsContext(ctx context.Context) (*CacheStats, error)
CacheStatsContext retrieves cache statistics with the given context.
func (*Client) ConnectContext ¶
ConnectContext establishes a connection to the server with the given context.
func (*Client) Count ¶
func (c *Client) Count(table, query string, opts CountOptions) (*CountResponse, error)
Count returns the number of matching documents.
func (*Client) CountContext ¶
func (c *Client) CountContext(ctx context.Context, table, query string, opts CountOptions) (*CountResponse, error)
CountContext performs a count query with the given context.
func (*Client) DisableDebug ¶
DisableDebug disables debug mode.
func (*Client) DisableDebugContext ¶
DisableDebugContext disables debug mode with the given context.
func (*Client) DumpInfoContext ¶
DumpInfoContext retrieves metadata of a dump file with the given context.
func (*Client) DumpLoadContext ¶
DumpLoadContext loads the index from a file with the given context.
func (*Client) DumpSaveContext ¶
DumpSaveContext saves the index to a file with the given context.
func (*Client) DumpStatus ¶
func (c *Client) DumpStatus() (*DumpStatus, error)
DumpStatus retrieves the status of a dump operation.
func (*Client) DumpStatusContext ¶
func (c *Client) DumpStatusContext(ctx context.Context) (*DumpStatus, error)
DumpStatusContext retrieves the status of a dump operation with the given context.
func (*Client) DumpVerify ¶
DumpVerify verifies the integrity of a dump file.
func (*Client) DumpVerifyContext ¶
DumpVerifyContext verifies the integrity of a dump file with the given context.
func (*Client) EnableDebugContext ¶
EnableDebugContext enables debug mode with the given context.
func (*Client) Facet ¶ added in v0.2.0
func (c *Client) Facet(table, column string, opts FacetOptions) (*FacetResponse, error)
Facet aggregates distinct values of a filter column with their document counts. Optionally scoped to a search result set via opts.Query and related options. Available on MygramDB >= v1.6.
func (*Client) FacetContext ¶ added in v0.2.0
func (c *Client) FacetContext(ctx context.Context, table, column string, opts FacetOptions) (*FacetResponse, error)
FacetContext is the context-aware variant of Facet.
func (*Client) GetConfigContext ¶
GetConfigContext retrieves server configuration with the given context.
func (*Client) GetContext ¶
GetContext retrieves a document by its primary key with the given context.
func (*Client) GetReplicationStatus ¶
func (c *Client) GetReplicationStatus() (*ReplicationStatus, error)
GetReplicationStatus retrieves the replication status.
func (*Client) GetReplicationStatusContext ¶
func (c *Client) GetReplicationStatusContext(ctx context.Context) (*ReplicationStatus, error)
GetReplicationStatusContext retrieves the replication status with the given context.
func (*Client) Info ¶
func (c *Client) Info() (*ServerInfo, error)
Info retrieves server information.
func (*Client) InfoContext ¶
func (c *Client) InfoContext(ctx context.Context) (*ServerInfo, error)
InfoContext retrieves server information with the given context.
func (*Client) IsConnected ¶
IsConnected returns whether the client is currently connected.
func (*Client) Optimize ¶
Optimize optimizes the index. If table is specified, only that table's index is optimized.
func (*Client) OptimizeContext ¶
OptimizeContext optimizes the index with the given context.
func (*Client) Search ¶
func (c *Client) Search(table, query string, opts SearchOptions) (*SearchResponse, error)
Search performs a full-text search.
func (*Client) SearchContext ¶
func (c *Client) SearchContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
SearchContext performs a full-text search with the given context.
func (*Client) SearchRaw ¶ added in v0.3.0
func (c *Client) SearchRaw(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRaw searches using a pre-built boolean expression (MygramDB >= v1.8).
The expression is sent verbatim (unquoted) so the server tokenizes it and its AST parser can interpret AND / OR / NOT / parentheses, including OR groups nested under AND such as "alpha AND (beta OR gamma)". A quoted expression would be treated by a v1.8 server as a single literal phrase, so quoting is intentionally not applied. Pair this with ConvertSearchExpression to preserve OR / grouping semantics that Search's AND/NOT decomposition cannot express.
func (*Client) SearchRawContext ¶ added in v0.3.0
func (c *Client) SearchRawContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRawContext is the context-aware variant of SearchRaw.
func (*Client) SearchRawWithHighlights ¶ added in v0.3.0
func (c *Client) SearchRawWithHighlights(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRawWithHighlights is a SearchRaw variant that requests highlighted snippets. Any highlight options passed in opts are preserved; otherwise server defaults are used.
func (*Client) SearchRawWithHighlightsContext ¶ added in v0.3.0
func (c *Client) SearchRawWithHighlightsContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRawWithHighlightsContext is the context-aware variant of SearchRawWithHighlights.
func (*Client) SearchWithHighlights ¶ added in v0.3.0
func (c *Client) SearchWithHighlights(table, query string, opts SearchOptions) (*SearchResponse, error)
SearchWithHighlights is a Search variant that requests highlighted snippets. Any highlight options passed in opts are preserved; otherwise server defaults are used. Snippets are returned in SearchResult.Snippet. Requires MygramDB >= v1.6.
func (*Client) SearchWithHighlightsContext ¶ added in v0.3.0
func (c *Client) SearchWithHighlightsContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
SearchWithHighlightsContext is the context-aware variant of SearchWithHighlights.
func (*Client) SendCommand ¶
SendCommand sends a raw command to the server and returns the response.
func (*Client) SendCommandContext ¶
SendCommandContext sends a raw command to the server with the given context.
The context bounds how long the call waits: its deadline, if any, caps the I/O timeout, and a context that is already canceled or past its deadline fails fast before anything is sent. Once the request is in flight, cancellation of a deadline-less context does not interrupt it; the command still completes or hits TimeoutMs.
func (*Client) SetVariable ¶ added in v0.3.0
SetVariable sets a runtime variable (MygramDB >= v1.7, MySQL-compatible SET).
func (*Client) SetVariableContext ¶ added in v0.3.0
SetVariableContext sets a runtime variable with the given context.
func (*Client) ShowVariables ¶ added in v0.3.0
ShowVariables shows runtime variables (MygramDB >= v1.7, MySQL-compatible SHOW VARIABLES). An empty likePattern lists every variable; a non-empty pattern is matched MySQL-style (e.g. "logging%"). The raw server response is returned unparsed.
func (*Client) ShowVariablesContext ¶ added in v0.3.0
ShowVariablesContext is the context-aware variant of ShowVariables.
func (*Client) StartReplication ¶
StartReplication starts replication.
func (*Client) StartReplicationContext ¶
StartReplicationContext starts replication with the given context.
func (*Client) StopReplication ¶
StopReplication stops replication.
func (*Client) StopReplicationContext ¶
StopReplicationContext stops replication with the given context.
func (*Client) Sync ¶ added in v0.3.0
Sync starts an on-demand sync (full reload) of a table (MygramDB >= v1.7). The raw server acknowledgement is returned.
func (*Client) SyncContext ¶ added in v0.3.0
SyncContext is the context-aware variant of Sync.
func (*Client) SyncStatus ¶ added in v0.3.0
SyncStatus retrieves the status of in-flight and recent sync operations (MygramDB >= v1.7). The raw SYNC_STATUS report is returned unparsed.
func (*Client) SyncStatusContext ¶ added in v0.3.0
SyncStatusContext is the context-aware variant of SyncStatus.
type ClientConfig ¶
type ClientConfig struct {
// Host is the server hostname or IP address. Default is "127.0.0.1".
Host string
// Port is the server port number. Default is 11016.
Port int
// SocketPath is the Unix domain socket path. When specified, it takes priority over TCP.
SocketPath string
// TimeoutMs is the command timeout in milliseconds. Default is 5000.
//
// This field is milliseconds (an int) for parity with the other language
// clients. The pool-level limits (PoolConfig.ConnMaxLifetime and friends)
// are time.Duration; mind the difference when configuring both.
TimeoutMs int
// RecvBufferSize is the receive buffer size. Default is 65536.
RecvBufferSize int
// MaxQueryLength is the maximum length of a query expression. 0 means unlimited. Default is 128.
MaxQueryLength int
// MaxResponseSize is the maximum accepted response size in bytes. When a
// response exceeds it, the read is aborted with a ProtocolError and the
// connection is closed (its stream position is no longer known). 0 means
// unlimited, which is the default for backward compatibility. A bounded
// value (for example 64<<20) is recommended to guard against a runaway or
// malformed response exhausting memory.
MaxResponseSize int
// AutoReconnect transparently re-establishes a dropped connection. When
// enabled, SendCommandContext reconnects once and resends the command if
// the socket is found dead *before* the request is written. A disconnect
// that occurs *after* the request was sent is surfaced as a ConnectionError
// without resending, since the command may already have been applied
// server-side. Default is false (legacy behavior). A Pool always enables it
// on the connections it owns so a transient drop is absorbed on the slot.
AutoReconnect bool
// DisableTCPKeepAlive turns off the client's SO_KEEPALIVE idle override on
// TCP connections. The zero value keeps keep-alive enabled with the
// TCPKeepAliveIdle period, so a silently dropped peer is detected without
// waiting for the next command's read timeout. Set it to true to leave the
// dialer's built-in keep-alive default in place instead. Ignored for
// Unix-socket connections. Defaulting keep-alive on this way keeps the
// behavior identical whether a client is built with NewClient or with
// NewClientWithConfig/NewPool.
DisableTCPKeepAlive bool
// TCPKeepAliveIdle is the idle period before keep-alive probing begins.
// Applies unless DisableTCPKeepAlive is set. 0 selects the default (60s).
TCPKeepAliveIdle time.Duration
}
ClientConfig holds connection settings for the MygramDB server.
func DefaultConfig ¶
func DefaultConfig() ClientConfig
DefaultConfig returns the default configuration.
type ConnectionError ¶
ConnectionError is an error returned when a connection fails.
func (*ConnectionError) Error ¶
func (e *ConnectionError) Error() string
func (*ConnectionError) Unwrap ¶
func (e *ConnectionError) Unwrap() error
type CountOptions ¶
type CountOptions struct {
// AndTerms is a list of additional keywords combined with AND.
AndTerms []string
// NotTerms is a list of keywords to exclude with NOT.
NotTerms []string
// Filters is a map of column filter conditions (key=value).
Filters map[string]string
}
CountOptions holds options for a count request.
type CountResponse ¶
type CountResponse struct {
// Count is the number of matched documents.
Count int
// Debug contains debug information (only available when debug mode is enabled).
Debug *DebugInfo
}
CountResponse represents a count response.
type DebugInfo ¶
type DebugInfo struct {
QueryTimeMs float64
IndexTimeMs float64
FilterTimeMs float64
Terms int
Ngrams int
Candidates int
AfterIntersection int
AfterNot int
AfterFilters int
Final int
Optimization string
Sort string
Cache string
CacheAgeMs float64
CacheSavedMs float64
Limit int
Offset int
}
DebugInfo holds query metrics from debug mode.
type Document ¶
type Document struct {
// PrimaryKey is the document's primary key.
PrimaryKey string
// Fields is a map of filter column key-value pairs.
Fields map[string]string
}
Document represents a document retrieved by GET.
type DumpStatus ¶
type DumpStatus struct {
SaveInProgress bool
LoadInProgress bool
Status string
Filepath string
TablesProcessed int
TablesTotal int
CurrentTable string
ElapsedSeconds float64
ResultFilepath string
Error string
}
DumpStatus represents the status of a dump operation.
type FacetOptions ¶ added in v0.2.0
type FacetOptions struct {
// Query, when non-empty, scopes the facet aggregation to documents
// matching the given search text (same semantics as SEARCH).
Query string
// AndTerms is a list of additional keywords combined with AND.
AndTerms []string
// NotTerms is a list of keywords to exclude with NOT.
NotTerms []string
// Filters is a map of column filter conditions (key=value).
Filters map[string]string
// Limit bounds the number of returned (value, count) pairs.
// 0 means "no limit".
Limit int
}
FacetOptions holds options for a FACET request. Introduced in MygramDB v1.6.
type FacetResponse ¶ added in v0.2.0
type FacetResponse struct {
// Results is the list of (value, count) pairs ordered by count
// descending.
Results []FacetValue
}
FacetResponse is the response to a FACET command.
type FacetValue ¶ added in v0.2.0
type FacetValue struct {
// Value is the facet column's distinct value as a string.
Value string
// Count is the number of documents that have this value.
Count int64
}
FacetValue is a single aggregated (value, count) pair returned by the FACET command.
type HighlightOptions ¶ added in v0.2.0
type HighlightOptions struct {
// OpenTag is the tag inserted before each matched term. When empty
// the server default ("<em>") is used.
OpenTag string
// CloseTag is the tag inserted after each matched term. When empty
// the server default ("</em>") is used.
//
// OpenTag and CloseTag must be set (or unset) together.
CloseTag string
// SnippetLen is the maximum number of code points per snippet
// fragment. Valid range is 1..10000. 0 means "use server default"
// (100).
SnippetLen int
// MaxFragments is the maximum number of snippet fragments joined by
// ellipsis. Valid range is 1..100. 0 means "use server default" (3).
MaxFragments int
}
HighlightOptions configures the HIGHLIGHT clause introduced in MygramDB v1.6. A zero-value HighlightOptions requests default highlighting ("<em>"/"</em>" tags, 100 code point snippets, up to 3 fragments).
type Pool ¶ added in v0.4.0
type Pool struct {
// contains filtered or unexported fields
}
Pool is a bounded pool of MygramDB connections. It exposes the same command methods as Client; for each call it borrows a connection, runs the request, and returns the connection to the pool, transparently reconnecting and retrying where it is safe to do so. A Pool is safe for concurrent use.
The token accounting maintains the invariant that the number of open connections (idle plus in use) never exceeds MaxOpenConns: every connection holds exactly one slot in sem from the moment it is dialed until it is closed. Idle connections keep their slot while parked in the idle channel.
func NewPool ¶ added in v0.4.0
func NewPool(cfg PoolConfig) *Pool
NewPool creates a pool with the given configuration. It performs no I/O; connections are opened lazily on first use.
func (*Pool) CacheClear ¶ added in v0.4.0
CacheClear clears the cache.
func (*Pool) CacheClearContext ¶ added in v0.4.0
CacheClearContext clears the cache with the given context.
func (*Pool) CacheDisable ¶ added in v0.4.0
CacheDisable disables the cache.
func (*Pool) CacheDisableContext ¶ added in v0.4.0
CacheDisableContext disables the cache with the given context.
func (*Pool) CacheEnable ¶ added in v0.4.0
CacheEnable enables the cache.
func (*Pool) CacheEnableContext ¶ added in v0.4.0
CacheEnableContext enables the cache with the given context.
func (*Pool) CacheStats ¶ added in v0.4.0
func (p *Pool) CacheStats() (*CacheStats, error)
CacheStats retrieves cache statistics.
func (*Pool) CacheStatsContext ¶ added in v0.4.0
func (p *Pool) CacheStatsContext(ctx context.Context) (*CacheStats, error)
CacheStatsContext retrieves cache statistics with the given context.
func (*Pool) Close ¶ added in v0.4.0
Close closes the pool. Idle connections are closed immediately; connections currently in use are closed when they are returned. After Close, command methods return a ConnectionError. Close is idempotent.
func (*Pool) Count ¶ added in v0.4.0
func (p *Pool) Count(table, query string, opts CountOptions) (*CountResponse, error)
Count returns the number of matching documents.
func (*Pool) CountContext ¶ added in v0.4.0
func (p *Pool) CountContext(ctx context.Context, table, query string, opts CountOptions) (*CountResponse, error)
CountContext performs a count query with the given context.
func (*Pool) DisableDebug ¶ added in v0.4.0
DisableDebug disables debug mode.
func (*Pool) DisableDebugContext ¶ added in v0.4.0
DisableDebugContext disables debug mode with the given context.
func (*Pool) DumpInfoContext ¶ added in v0.4.0
DumpInfoContext retrieves metadata of a dump file with the given context.
func (*Pool) DumpLoadContext ¶ added in v0.4.0
DumpLoadContext loads the index from a file with the given context.
func (*Pool) DumpSaveContext ¶ added in v0.4.0
DumpSaveContext saves the index to a file with the given context.
func (*Pool) DumpStatus ¶ added in v0.4.0
func (p *Pool) DumpStatus() (*DumpStatus, error)
DumpStatus retrieves the status of a dump operation.
func (*Pool) DumpStatusContext ¶ added in v0.4.0
func (p *Pool) DumpStatusContext(ctx context.Context) (*DumpStatus, error)
DumpStatusContext retrieves the status of a dump operation with the given context.
func (*Pool) DumpVerify ¶ added in v0.4.0
DumpVerify verifies the integrity of a dump file.
func (*Pool) DumpVerifyContext ¶ added in v0.4.0
DumpVerifyContext verifies the integrity of a dump file with the given context.
func (*Pool) EnableDebug ¶ added in v0.4.0
EnableDebug enables debug mode.
func (*Pool) EnableDebugContext ¶ added in v0.4.0
EnableDebugContext enables debug mode with the given context.
func (*Pool) Facet ¶ added in v0.4.0
func (p *Pool) Facet(table, column string, opts FacetOptions) (*FacetResponse, error)
Facet aggregates distinct values of a filter column with their document counts.
func (*Pool) FacetContext ¶ added in v0.4.0
func (p *Pool) FacetContext(ctx context.Context, table, column string, opts FacetOptions) (*FacetResponse, error)
FacetContext is the context-aware variant of Facet.
func (*Pool) GetConfigContext ¶ added in v0.4.0
GetConfigContext retrieves server configuration with the given context.
func (*Pool) GetContext ¶ added in v0.4.0
GetContext retrieves a document by its primary key with the given context.
func (*Pool) GetReplicationStatus ¶ added in v0.4.0
func (p *Pool) GetReplicationStatus() (*ReplicationStatus, error)
GetReplicationStatus retrieves the replication status.
func (*Pool) GetReplicationStatusContext ¶ added in v0.4.0
func (p *Pool) GetReplicationStatusContext(ctx context.Context) (*ReplicationStatus, error)
GetReplicationStatusContext retrieves the replication status with the given context.
func (*Pool) Info ¶ added in v0.4.0
func (p *Pool) Info() (*ServerInfo, error)
Info retrieves server information.
func (*Pool) InfoContext ¶ added in v0.4.0
func (p *Pool) InfoContext(ctx context.Context) (*ServerInfo, error)
InfoContext retrieves server information with the given context.
func (*Pool) OptimizeContext ¶ added in v0.4.0
OptimizeContext optimizes the index with the given context.
func (*Pool) Search ¶ added in v0.4.0
func (p *Pool) Search(table, query string, opts SearchOptions) (*SearchResponse, error)
Search performs a full-text search.
func (*Pool) SearchContext ¶ added in v0.4.0
func (p *Pool) SearchContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
SearchContext performs a full-text search with the given context.
func (*Pool) SearchRaw ¶ added in v0.4.0
func (p *Pool) SearchRaw(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRaw searches using a pre-built boolean expression.
func (*Pool) SearchRawContext ¶ added in v0.4.0
func (p *Pool) SearchRawContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRawContext is the context-aware variant of SearchRaw.
func (*Pool) SearchRawWithHighlights ¶ added in v0.4.0
func (p *Pool) SearchRawWithHighlights(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRawWithHighlights is a SearchRaw variant that requests highlighted snippets.
func (*Pool) SearchRawWithHighlightsContext ¶ added in v0.4.0
func (p *Pool) SearchRawWithHighlightsContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRawWithHighlightsContext is the context-aware variant of SearchRawWithHighlights.
func (*Pool) SearchWithHighlights ¶ added in v0.4.0
func (p *Pool) SearchWithHighlights(table, query string, opts SearchOptions) (*SearchResponse, error)
SearchWithHighlights is a Search variant that requests highlighted snippets.
func (*Pool) SearchWithHighlightsContext ¶ added in v0.4.0
func (p *Pool) SearchWithHighlightsContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
SearchWithHighlightsContext is the context-aware variant of SearchWithHighlights.
func (*Pool) SendCommand ¶ added in v0.4.0
SendCommand sends a raw command to the server and returns the response.
func (*Pool) SendCommandContext ¶ added in v0.4.0
SendCommandContext sends a raw command with the given context. Raw commands are treated as state-changing and are never retried after they reach the server.
func (*Pool) SetVariable ¶ added in v0.4.0
SetVariable sets a runtime variable.
func (*Pool) SetVariableContext ¶ added in v0.4.0
SetVariableContext sets a runtime variable with the given context.
func (*Pool) ShowVariables ¶ added in v0.4.0
ShowVariables shows runtime variables.
func (*Pool) ShowVariablesContext ¶ added in v0.4.0
ShowVariablesContext is the context-aware variant of ShowVariables.
func (*Pool) StartReplication ¶ added in v0.4.0
StartReplication starts replication.
func (*Pool) StartReplicationContext ¶ added in v0.4.0
StartReplicationContext starts replication with the given context.
func (*Pool) StopReplication ¶ added in v0.4.0
StopReplication stops replication.
func (*Pool) StopReplicationContext ¶ added in v0.4.0
StopReplicationContext stops replication with the given context.
func (*Pool) SyncContext ¶ added in v0.4.0
SyncContext is the context-aware variant of Sync.
func (*Pool) SyncStatus ¶ added in v0.4.0
SyncStatus retrieves the status of in-flight and recent sync operations.
func (*Pool) SyncStatusContext ¶ added in v0.4.0
SyncStatusContext is the context-aware variant of SyncStatus.
func (*Pool) SyncStopContext ¶ added in v0.4.0
SyncStopContext is the context-aware variant of SyncStop.
func (*Pool) WithConn ¶ added in v0.4.0
WithConn borrows a single connection and runs fn against it. Use it to run a sequence of requests on one connection, or a request whose retry semantics you want to control yourself. The pool applies no retries around fn. The connection is returned to the pool afterwards, or discarded if fn reports a connection-level failure.
type PoolConfig ¶ added in v0.4.0
type PoolConfig struct {
ClientConfig
// MaxOpenConns bounds the total number of connections (idle plus in use).
// A borrow that would exceed it blocks until a connection is returned or
// the context is canceled. 0 or negative means the default (10). There is
// deliberately no "unlimited" option: an explicit cap is the point.
MaxOpenConns int
// MaxIdleConns bounds how many idle connections are retained for reuse.
// 0 or negative means "same as MaxOpenConns". Values above MaxOpenConns are
// clamped to MaxOpenConns.
MaxIdleConns int
// ConnMaxLifetime is the maximum age of a connection measured from when it
// was opened. Expired connections are discarded on borrow, and a background
// reaper also sweeps idle ones so a quiet pool does not keep them open. 0
// means no limit.
ConnMaxLifetime time.Duration
// ConnMaxIdleTime is the maximum time a connection may sit idle before it
// is discarded. It is enforced both on borrow and by the background reaper.
// 0 means no limit.
ConnMaxIdleTime time.Duration
// Retry is the retry policy for idempotent and never-sent commands. A zero
// value selects the default policy.
Retry RetryPolicy
// CircuitBreaker configures a circuit breaker around the command API. It
// sits outside the retry policy, so an open breaker fails fast without
// retrying or touching the network. A nil pointer disables it.
CircuitBreaker *CircuitBreakerConfig
// OnEvent, when set, receives observability events (see PoolEvent). It is
// called synchronously on the pool's hot path, so it must not block; a
// panic in the callback is recovered and ignored.
OnEvent func(event PoolEvent, payload map[string]any)
}
PoolConfig configures a Pool. The embedded ClientConfig is applied to every connection the pool opens. Time-based limits use time.Duration (the pool is Go-native), whereas the embedded ClientConfig keeps its millisecond fields for parity with the other language clients.
type PoolEvent ¶ added in v0.4.0
type PoolEvent string
PoolEvent identifies an observability event emitted by a Pool through PoolConfig.OnEvent. The payload map varies by event; see each constant.
const ( // EventAcquire is emitted when a connection is handed out. Payload: // {"wait_seconds": float64} — time the borrow spent waiting (0 if it did // not wait). EventAcquire PoolEvent = "acquire" // EventConnectionDiscarded is emitted when a connection is dropped after // failing validation, expiring, or overflowing the idle limit. Empty payload. EventConnectionDiscarded PoolEvent = "connection_discarded" // EventRetry is emitted before a request retry's backoff. Payload: // {"attempt": int, "error": string}. EventRetry PoolEvent = "retry" // EventBreakerStateChange is emitted when the circuit breaker changes state. // Payload: {"state": string} — one of "closed", "open", "half_open". EventBreakerStateChange PoolEvent = "breaker_state_change" )
type PoolStats ¶ added in v0.4.0
type PoolStats struct {
// Open is the number of open connections (idle plus in use).
Open int
// Idle is the number of connections currently available for reuse.
Idle int
// InUse is the number of connections currently borrowed.
InUse int
// WaitCount is the approximate number of borrows that had to wait for a
// connection. It counts entries into the waiting path, some of which may
// then complete without actually blocking, so it slightly overstates
// contention.
WaitCount int64
// WaitDuration is the cumulative time borrows spent in the waiting path.
WaitDuration time.Duration
// Discarded is the number of connections closed instead of being reused
// (unhealthy, expired, or beyond the idle limit).
Discarded int64
// Retries is the number of request retries performed.
Retries int64
}
PoolStats is a snapshot of a Pool's runtime statistics.
type ProtocolError ¶
type ProtocolError struct {
Message string
}
ProtocolError is an error returned when a protocol violation occurs.
func (*ProtocolError) Error ¶
func (e *ProtocolError) Error() string
type ReplicationStatus ¶
type ReplicationStatus struct {
// Running is true when replication is active.
Running bool
// GTID is the current GTID position.
GTID string
// StatusStr is the raw response string.
StatusStr string
// ProcessedEvents is the total number of binlog events processed since
// startup. Populated only by the multi-line REPLICATION STATUS response.
ProcessedEvents int
// QueueSize is the number of events currently pending in the
// replication apply queue. Populated only by the multi-line response.
QueueSize int
}
ReplicationStatus represents the replication state.
type RetryPolicy ¶ added in v0.4.0
type RetryPolicy struct {
// MaxRetries is the maximum number of additional attempts after the first.
// The zero value selects the default of 1 (so up to two total attempts). A
// negative value explicitly disables retries (zero additional attempts);
// use it when a workload must never re-issue a command, even a safe one.
MaxRetries int
// BaseBackoff is the base delay for the exponential-with-full-jitter
// backoff between attempts. Default is 50ms.
BaseBackoff time.Duration
}
RetryPolicy controls how the pool retries failed commands. Only failures that are safe to retry are ever retried: a command whose write never reached the server (any command), or a read-phase failure of an idempotent command. Server errors, validation errors and timeouts are never retried.
type SearchExpression ¶
type SearchExpression struct {
// RequiredTerms contains keywords marked as required with +.
RequiredTerms []string
// ExcludedTerms contains keywords marked for exclusion with -.
ExcludedTerms []string
// OptionalTerms contains keywords without any modifier.
OptionalTerms []string
// RawExpression holds the original expression when it contains OR/grouping (complex expressions).
RawExpression string
}
SearchExpression represents a parsed search expression.
func ParseSearchExpression ¶
func ParseSearchExpression(expression string) (*SearchExpression, error)
ParseSearchExpression parses a web-search-style search expression.
Supported syntax:
- +term: required keyword
- -term: excluded keyword
- "phrase": phrase search
- OR: logical OR
- (expr): grouping
type SearchOptions ¶
type SearchOptions struct {
// Limit is the maximum number of results to return. Default is 1000.
Limit int
// Offset is the number of results to skip. Default is 0.
Offset int
// AndTerms is a list of additional keywords combined with AND.
AndTerms []string
// NotTerms is a list of keywords to exclude with NOT.
NotTerms []string
// Filters is a map of column filter conditions (key=value).
Filters map[string]string
// SortColumn is the column name to sort by.
//
// Use the special value "_score" to sort by BM25 relevance score
// (requires verify_text=ascii|all on the server, MygramDB >= v1.6).
SortColumn string
// SortDesc indicates descending sort order when true.
SortDesc bool
// Fuzzy enables fuzzy (Levenshtein) matching with the given edit
// distance. Valid values are 0 (disabled), 1 and 2. Requires
// MygramDB >= v1.6.
Fuzzy int
// Highlight, when non-nil, enables the HIGHLIGHT clause so that
// matching snippets are returned alongside each primary key.
// Requires verify_text=ascii|all on the server and MygramDB >= v1.6.
Highlight *HighlightOptions
}
SearchOptions holds options for a search request.
type SearchRawOptions ¶ added in v0.3.0
type SearchRawOptions struct {
// Limit is the maximum number of results to return. 0 means the server
// default.
Limit int
// Offset is the number of results to skip. Default is 0.
Offset int
// Highlight, when non-nil, enables the HIGHLIGHT clause so that matching
// snippets are returned alongside each primary key.
Highlight *HighlightOptions
}
SearchRawOptions holds options for a raw search request that sends a pre-built boolean expression. Introduced in MygramDB v1.7; since v1.8 the expression is sent verbatim (unquoted) so the server's AST parser interprets AND/OR/NOT and grouping (see Client.SearchRaw). Unlike SearchOptions, a raw search exposes only pagination and highlight controls — AND/NOT/FILTER refinements belong inside the expression itself.
type SearchResponse ¶
type SearchResponse struct {
// Results is the list of search results.
Results []SearchResult
// TotalCount is the total number of matches after filtering.
TotalCount int
// Debug contains debug information (only available when debug mode is enabled).
Debug *DebugInfo
}
SearchResponse represents a search response.
type SearchResult ¶
type SearchResult struct {
// PrimaryKey is the document's primary key.
PrimaryKey string
// Snippet contains the highlighted text fragment for this result,
// populated only when SearchOptions.Highlight was set (MygramDB
// >= v1.6). Empty otherwise.
Snippet string
}
SearchResult represents a single search result.
type ServerError ¶
type ServerError struct {
Message string
}
ServerError is an error returned when the server responds with ERROR.
func (*ServerError) Error ¶
func (e *ServerError) Error() string
type ServerInfo ¶
type ServerInfo struct {
// Version is the server version.
Version string
// UptimeSeconds is the number of seconds since server startup.
UptimeSeconds int
// TotalRequests is the total number of processed requests.
TotalRequests int
// ActiveConnections is the current number of client connections.
ActiveConnections int
// IndexSizeBytes is the memory used by the index in bytes.
IndexSizeBytes int
// DocCount is the total number of documents in the index.
DocCount int
// Tables is the list of table names.
Tables []string
}
ServerInfo represents server information.
type SimplifiedExpression ¶
type SimplifiedExpression struct {
// MainTerm is the main search keyword.
MainTerm string
// AndTerms is a list of additional keywords combined with AND.
AndTerms []string
// NotTerms is a list of keywords to exclude with NOT.
NotTerms []string
}
SimplifiedExpression represents a simplified search expression.
func SimplifySearchExpression ¶
func SimplifySearchExpression(expression string) (*SimplifiedExpression, error)
SimplifySearchExpression decomposes a search expression into MainTerm/AndTerms/NotTerms. The result maps directly to the MygramDB SEARCH command format.
OR-only or parenthesized sub-expressions (e.g. "python OR ruby" or "(a OR b)") are surfaced as a single parenthesized MainTerm so the OR semantics survive when the caller AND-composes the result. Mixed expressions that combine required terms with an OR sub-expression keep the required terms; the OR sub-expression is currently not surfaced.
type TimeoutError ¶
type TimeoutError struct {
Message string
// Err is the underlying cause, if any (for example context.DeadlineExceeded
// when the caller's context deadline elapsed). It is nil for a timeout
// driven purely by the configured TimeoutMs.
Err error
// contains filtered or unexported fields
}
TimeoutError is an error returned when an operation times out.
It satisfies net.Error (Timeout reports true), so existing code that checks for timeouts via net.Error keeps working. When the timeout was caused by the caller's context deadline, Err is context.DeadlineExceeded and is exposed via Unwrap, so errors.Is(err, context.DeadlineExceeded) matches.
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
func (*TimeoutError) Temporary ¶ added in v0.4.0
func (e *TimeoutError) Temporary() bool
Temporary satisfies net.Error. A command timeout is not treated as a transient condition (matching os.ErrDeadlineExceeded), so it returns false.
func (*TimeoutError) Timeout ¶ added in v0.4.0
func (e *TimeoutError) Timeout() bool
Timeout reports that this error represents a timeout, satisfying net.Error.
func (*TimeoutError) Unwrap ¶ added in v0.4.0
func (e *TimeoutError) Unwrap() error
type ValidationError ¶
type ValidationError struct {
Message string
}
ValidationError is an error returned when input validation fails.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string