mygram

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 9, 2026 License: MIT Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-mygram-client

CI Go Reference Go codecov License golangci-lint Zero Dependencies

Go client library for MygramDB — a high-performance in-memory full-text search engine with MySQL replication support.

Compatible with MygramDB v1.6 (BM25 scoring, HIGHLIGHT, FUZZY, FACET).

Overview

MygramDB provides 25-200x faster full-text search than MySQL FULLTEXT. This client communicates via MygramDB's TCP text protocol (memcached-style) with zero external dependencies.

MySQL FULLTEXT MygramDB
Search Speed Baseline 25-200x faster
Storage On-disk In-memory
Replication — MySQL binlog
Protocol MySQL TCP (memcached-style)
Features
  • Zero Dependencies — Standard library only
  • Context Support — All methods have context.Context variants
  • Search Expression Parser — Web-style search syntax (+required, -excluded, "phrase", OR, grouping)
  • Full Protocol Support — All MygramDB commands (SEARCH, COUNT, GET, INFO, etc.)
  • Input Validation — Built-in protection against control character injection
  • Thread Safe — Safe for concurrent use

Installation

go get github.com/libraz/go-mygram-client

Quick Start

package main

import (
	"fmt"
	"log"

	mygram "github.com/libraz/go-mygram-client"
)

func main() {
	client := mygram.NewClient("localhost:11016")
	defer client.Close()

	if err := client.Connect(); err != nil {
		log.Fatal(err)
	}

	// Search
	resp, err := client.Search("articles", "hello", mygram.SearchOptions{
		Limit:      100,
		SortColumn: "created_at",
		SortDesc:   true,
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Found %d results\n", resp.TotalCount)

	// Count
	count, err := client.Count("articles", "technology", mygram.CountOptions{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Count: %d\n", count.Count)

	// Get document by ID
	doc, err := client.Get("articles", "12345")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Doc: %s %v\n", doc.PrimaryKey, doc.Fields)
}

Search Expressions

Parse web-style search queries into structured search parameters:

// Space = AND, - = NOT, "" = phrase, OR = OR, () = grouping
expr, err := mygram.SimplifySearchExpression("hello world -spam")
// expr = &SimplifiedExpression{MainTerm: "hello", AndTerms: ["world"], NotTerms: ["spam"]}

resp, err := client.Search("articles", expr.MainTerm, mygram.SearchOptions{
	AndTerms:   expr.AndTerms,
	NotTerms:   expr.NotTerms,
	Limit:      100,
	Offset:     50,
	Filters:    map[string]string{"status": "published", "lang": "en"},
	SortColumn: "created_at",
	SortDesc:   true,
})

MygramDB v1.6 Features

BM25 Relevance Scoring

Sort by relevance using the special _score sort column (requires verify_text: ascii|all on the server):

resp, _ := client.Search("articles", "machine learning", mygram.SearchOptions{
    SortColumn: "_score",
    SortDesc:   true,
    Limit:      10,
})
Fuzzy Search (Levenshtein)
// Match within 1 edit (default) or 2 edits.
resp, _ := client.Search("articles", "machne", mygram.SearchOptions{
    Fuzzy: 1,
    Limit: 10,
})
Highlighting
resp, _ := client.Search("articles", "golang", mygram.SearchOptions{
    Highlight: &mygram.HighlightOptions{
        OpenTag:      "<strong>",
        CloseTag:     "</strong>",
        SnippetLen:   200,
        MaxFragments: 3,
    },
    SortColumn: "_score",
    SortDesc:   true,
    Limit:      10,
})

for _, r := range resp.Results {
    fmt.Println(r.PrimaryKey, r.Snippet)
}

A zero-value &HighlightOptions{} enables highlighting with server defaults (<em>/</em>, 100 code points, up to 3 fragments).

Facets

Aggregate distinct filter column values with document counts. Optionally scope the aggregation to a search result set:

// All distinct statuses:
resp, _ := client.Facet("articles", "status", mygram.FacetOptions{})

// Top categories among documents matching "machine learning":
resp, _ := client.Facet("articles", "category", mygram.FacetOptions{
    Query:   "machine learning",
    Filters: map[string]string{"status": "1"},
    Limit:   10,
})

for _, v := range resp.Results {
    fmt.Printf("%s: %d\n", v.Value, v.Count)
}

Development

make test       # Run unit tests
make test-race  # Run unit tests with race detector
make test-e2e   # Run e2e tests against a live MygramDB server
make lint       # Run golangci-lint
make fmt        # Format code
make coverage   # Generate coverage report
End-to-end tests

make test-e2e exercises every public method against a running MygramDB instance. Tests are gated by the e2e build tag, so the default go test ./... (and CI) never connect to a server.

# Default: connect to 127.0.0.1:11016
make test-e2e

# Override the endpoint
MYGRAM_HOST=db.example.com MYGRAM_PORT=11016 make test-e2e

# Skip side-effect heavy suites
MYGRAM_E2E_SKIP_DUMP=1 MYGRAM_E2E_SKIP_REPLICATION=1 make test-e2e

If the server is unreachable, every e2e test is skipped (not failed). Suites that mutate global server state (replication start/stop, cache toggle, dump round-trip) restore the original state on exit.

License

MIT

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertSearchExpression

func ConvertSearchExpression(expression string) (string, error)

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

func NewClient(addr string) *Client

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

func (c *Client) CacheClear(table string) error

CacheClear clears the cache. If table is specified, only that table's cache is cleared.

func (*Client) CacheClearContext

func (c *Client) CacheClearContext(ctx context.Context, table string) error

CacheClearContext clears the cache with the given context.

func (*Client) CacheDisable

func (c *Client) CacheDisable() error

CacheDisable disables the cache.

func (*Client) CacheDisableContext

func (c *Client) CacheDisableContext(ctx context.Context) error

CacheDisableContext disables the cache with the given context.

func (*Client) CacheEnable

func (c *Client) CacheEnable() error

CacheEnable enables the cache.

func (*Client) CacheEnableContext

func (c *Client) CacheEnableContext(ctx context.Context) error

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) Close

func (c *Client) Close() error

Close closes the connection.

func (*Client) Connect

func (c *Client) Connect() error

Connect establishes a connection to the server.

func (*Client) ConnectContext

func (c *Client) ConnectContext(ctx context.Context) error

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

func (c *Client) DisableDebug() error

DisableDebug disables debug mode.

func (*Client) DisableDebugContext

func (c *Client) DisableDebugContext(ctx context.Context) error

DisableDebugContext disables debug mode with the given context.

func (*Client) DumpInfo

func (c *Client) DumpInfo(filepath string) (string, error)

DumpInfo retrieves metadata of a dump file.

func (*Client) DumpInfoContext

func (c *Client) DumpInfoContext(ctx context.Context, filepath string) (string, error)

DumpInfoContext retrieves metadata of a dump file with the given context.

func (*Client) DumpLoad

func (c *Client) DumpLoad(filepath string) error

DumpLoad loads the index from a file.

func (*Client) DumpLoadContext

func (c *Client) DumpLoadContext(ctx context.Context, filepath string) error

DumpLoadContext loads the index from a file with the given context.

func (*Client) DumpSave

func (c *Client) DumpSave(filepath string) (string, error)

DumpSave saves the index to a file.

func (*Client) DumpSaveContext

func (c *Client) DumpSaveContext(ctx context.Context, filepath string) (string, error)

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

func (c *Client) DumpVerify(filepath string) (string, error)

DumpVerify verifies the integrity of a dump file.

func (*Client) DumpVerifyContext

func (c *Client) DumpVerifyContext(ctx context.Context, filepath string) (string, error)

DumpVerifyContext verifies the integrity of a dump file with the given context.

func (*Client) EnableDebug

func (c *Client) EnableDebug() error

EnableDebug enables debug mode.

func (*Client) EnableDebugContext

func (c *Client) EnableDebugContext(ctx context.Context) error

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) Get

func (c *Client) Get(table, primaryKey string) (*Document, error)

Get retrieves a document by its primary key.

func (*Client) GetConfig

func (c *Client) GetConfig() (string, error)

GetConfig retrieves server configuration in YAML format.

func (*Client) GetConfigContext

func (c *Client) GetConfigContext(ctx context.Context) (string, error)

GetConfigContext retrieves server configuration with the given context.

func (*Client) GetContext

func (c *Client) GetContext(ctx context.Context, table, primaryKey string) (*Document, error)

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

func (c *Client) IsConnected() bool

IsConnected returns whether the client is currently connected.

func (*Client) Optimize

func (c *Client) Optimize(table string) error

Optimize optimizes the index. If table is specified, only that table's index is optimized.

func (*Client) OptimizeContext

func (c *Client) OptimizeContext(ctx context.Context, table string) error

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

func (c *Client) SendCommand(command string) (string, error)

SendCommand sends a raw command to the server and returns the response.

func (*Client) SendCommandContext

func (c *Client) SendCommandContext(ctx context.Context, command string) (string, error)

SendCommandContext sends a raw command to the server with the given context.

func (*Client) StartReplication

func (c *Client) StartReplication() error

StartReplication starts replication.

func (*Client) StartReplicationContext

func (c *Client) StartReplicationContext(ctx context.Context) error

StartReplicationContext starts replication with the given context.

func (*Client) StopReplication

func (c *Client) StopReplication() error

StopReplication stops replication.

func (*Client) StopReplicationContext

func (c *Client) StopReplicationContext(ctx context.Context) error

StopReplicationContext stops replication with the given context.

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

type ConnectionError struct {
	Message string
	Err     error
}

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

	// 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 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.

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
}

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

Jump to

Keyboard shortcuts

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