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 ToQueryString(expr *SearchExpression) string
- type CacheStats
- 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) SendCommand(command string) (string, error)
- func (c *Client) SendCommandContext(ctx context.Context, command 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
- type ClientConfig
- type ConnectionError
- type CountOptions
- type CountResponse
- type DebugInfo
- type Document
- type DumpStatus
- type FacetOptions
- type FacetResponse
- type FacetValue
- type HighlightOptions
- type ProtocolError
- type ReplicationStatus
- type SearchExpression
- type SearchOptions
- 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 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 Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a MygramDB client.
func NewClient ¶
NewClient creates a new client for the given address. addr should be in "host:port" format or a Unix socket path.
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) 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.
func (*Client) StartReplication ¶
StartReplication starts replication.
func (*Client) StartReplicationContext ¶
StartReplicationContext starts replication with the given context.
func (*Client) StopReplication ¶
StopReplication stops replication.
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.
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
}
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 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
}
ReplicationStatus represents the replication state.
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 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.
type TimeoutError ¶
type TimeoutError struct {
Message string
}
TimeoutError is an error returned when an operation times out.
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
type ValidationError ¶
type ValidationError struct {
Message string
}
ValidationError is an error returned when input validation fails.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string