Query Syntax Guide
A query is a set of search terms combined with AND, OR, NOT, parentheses, and quoted phrases, followed by optional FILTER, SORT, LIMIT, and OFFSET clauses. This page is the reference. For task-oriented examples, see the Query Guide.
This is not SQL
MygramDB queries are a small search command language, not SQL. A query such as SEARCH articles mysql FILTER status = 1 LIMIT 10 carries only search terms and search options.
Table of Contents
- Basic Syntax
- Boolean Operators
- Complex Boolean Queries
- Operator Precedence
- Quoted Phrases
- Filter Conditions
- Sorting (SORT clause)
- Pagination (LIMIT/OFFSET)
- BM25 Relevance Scoring (SORT _score)
- Highlighting (HIGHLIGHT)
- Fuzzy Search (FUZZY)
- Error Handling
- Performance Tips
Basic Syntax
Command Format
SEARCH <table> <query_expression> [FILTER ...] [SORT ...] [LIMIT ...] [OFFSET ...]
COUNT <table> <query_expression> [FILTER ...]INFO
<table> accepts the database-qualified form `database.table` (e.g. app_db.articles). In a single-database deployment (only one distinct database is configured), a bare table name such as articles also works. Qualification is required only when the configuration spans two or more databases; a bare name is then rejected as ambiguous.
Simple Term Search
SEARCH <table> <term>Example:
SEARCH threads golangTerms may include punctuation unless it is a query delimiter. For example, c++, e-mail, and v1.9.0 are each parsed as one term.
Response Format
SEARCH Response:
OK RESULTS <total_count> <id1> <id2> <id3> ...total_count is the number of matching documents before LIMIT and OFFSET; the IDs on the same line are the current page. The server obtains the total and page from one index read, so they describe the same result set.
Example:
OK RESULTS 3 101 205 387COUNT Response:
OK COUNT <number>Example:
OK COUNT 42Boolean Operators
AND Search
Search for documents containing all specified terms.
How this differs from a bare space
A bare space is not an AND. Without an operator, golang tutorial is searched as one contiguous string, as if it were quoted. Write golang AND tutorial to require both terms anywhere in the document.
SEARCH <table> term1 AND term2 AND term3Example:
SEARCH threads golang AND tutorialOR Search
Search for documents containing any of the specified terms.
SEARCH <table> term1 OR term2 OR term3Example:
SEARCH threads golang OR python OR rustNOT Search
Exclude documents containing specific terms.
Using NOT well
NOT removes documents from the result set. A query that starts with NOT produces a very wide candidate set, so on large indexes pair it with positive terms.
SEARCH <table> term1 NOT term2Example:
SEARCH threads tutorial NOT beginnerAND NOT is accepted as an equivalent exclusion form. It is useful for expression converters that emit every additional condition after AND:
SEARCH threads tutorial AND NOT beginnerComplex Boolean Queries
Parentheses for Precedence
Use parentheses to group expressions and control operator precedence:
SEARCH <table> (term1 OR term2) AND term3Example:
SEARCH threads (golang OR python) AND tutorialThis finds documents containing "tutorial" AND either "golang" OR "python".
Nested Expressions
You can nest multiple levels of parentheses:
SEARCH <table> ((term1 OR term2) AND term3) OR term4Example:
SEARCH threads ((golang OR python) AND web) OR rustThis finds:
- Documents with "web" AND ("golang" OR "python")
- OR documents with "rust"
Complex Query Examples
Find Go or Python tutorials, excluding beginner content
SEARCH threads (golang OR python) AND tutorial NOT beginnerFind database content about MySQL or PostgreSQL, excluding SQLite
SEARCH posts database AND (mysql OR postgresql) NOT sqliteFind machine learning content in Python or R, excluding TensorFlow
SEARCH articles "machine learning" AND (python OR R) NOT tensorflowOperator Precedence
When no parentheses are used, operators have the following precedence (highest to lowest):
- NOT (highest)
- AND (medium)
- OR (lowest)
Precedence Examples
| Query | Parsed as |
|---|---|
a OR b AND c | a OR (b AND c) |
NOT a AND b | (NOT a) AND b |
a AND b OR c AND d | (a AND b) OR (c AND d) |
Pin the intent with parentheses
Parentheses are optional where the precedence already gives the result you want, but they keep complex conditions from being misread.
Quoted Phrases
Use double quotes " or single quotes ' for exact phrase matching:
SEARCH <table> "exact phrase"
SEARCH <table> 'machine learning'Escape Sequences
Quoted strings support these escape sequences:
| Sequence | Meaning |
|---|---|
\n | Newline |
\t | Tab |
\r | Carriage return |
\\ | Backslash |
\" | Double quote |
\' | Single quote |
Example:
SEARCH articles "hello \"world\""Mixing Quotes with Operators
Quoted phrases can be combined with boolean operators:
SEARCH threads "web framework" AND (golang OR python)
SEARCH posts "machine learning" NOT "deep learning"
SEARCH articles required AND 'not'Quoted clause keywords are literal terms. The last query requires the word not; quoting prevents it from becoming a NOT clause.
Filter Conditions
Filter results by column values using the FILTER clause.
Syntax
SEARCH <table> <query> FILTER <column> <operator> <value> [FILTER <col> <op> <val> ...]FILTER can be repeated. A document must match every filter (AND).
Supported Operators
| Operator | Alias | Meaning |
|---|---|---|
= | EQ | Equal |
!= / <> | NE | Not equal |
> | GT | Greater than |
>= | GTE | Greater than or equal |
< | LT | Less than |
<= | LTE | Less than or equal |
Examples
Single filter:
SEARCH articles tech FILTER status = 1Multiple filters:
SEARCH articles tech FILTER status = 1 FILTER category = aiComparison operators:
SEARCH articles tech FILTER views > 1000
SEARCH articles tech FILTER created_at >= 1704067200
SEARCH articles tech FILTER priority != 0
SEARCH articles tech FILTER status <> archivedWith boolean queries:
SEARCH threads (golang OR python) AND tutorial FILTER status = publishedFilter Column Types
FILTER accepts these value types:
- Integer:
status=1,priority=5 - String:
category=tech,author=john - Date/Time: query-time
date,datetime, andtimestampvalues are integer Unix epoch seconds; for example,created_at >= 1704067200selects values from 2024-01-01 00:00:00 UTC onward. Atimevalue is a signed duration in seconds, so-90000means minus 25 hours.
FILTER requires configuration
FILTER works only on columns registered under filters or required_filters in config.yaml. Any other column is rejected.
required_filters decides whether a row is indexed at all, and it has its own configuration syntax. Its ISO 8601 and clock-time values do not apply to query-time FILTER values. The same column may be listed in both settings: required_filters controls index admission, while FILTER narrows the indexed rows for each request.
Filter Performance
- Bitmap indexes: Very fast for low-cardinality columns (e.g., status, category)
- Filtering order: Filters are applied after text search intersection
Sorting (SORT clause)
Sort search results using the SORT clause.
Syntax
SEARCH <table> <query> SORT [BY] <column> [ASC|DESC]Not SQL's ORDER BY
MygramDB has no ORDER BY syntax. Use SORT to order search results.
BY is optional, so SORT BY created_at DESC and SORT created_at DESC are equivalent.
Numeric filter columns keep their declared type when sorted. A bigint_unsigned column orders values above 2^63 by their unsigned numeric value.
Default Behavior
If SORT is not specified, results are sorted by primary key in descending order (newest first).
SEARCH threads golang
-- Equivalent to: SEARCH threads golang SORT id DESCSorting by Primary Key
Full syntax:
SEARCH threads golang SORT id ASC
SEARCH threads golang SORT id DESC
SEARCH threads golang SORT BY id DESCShorthand syntax (recommended):
SEARCH threads golang SORT ASC -- Primary key ascending
SEARCH threads golang SORT DESC -- Primary key descendingSorting by Filter Column
Sort by any indexed filter column:
SEARCH threads golang SORT created_at DESC LIMIT 10
SEARCH threads golang SORT BY created_at DESC LIMIT 10
SEARCH posts database SORT _score ASC LIMIT 20Combining with Boolean Queries
SEARCH threads (golang OR python) AND tutorial SORT created_at DESC LIMIT 10
SEARCH posts ((mysql OR postgresql) AND database) NOT sqlite SORT _score ASCPerformance Considerations
Sorting Algorithm:
- With a small LIMIT: Uses
partial_sortwhenLIMIT + OFFSETis less than half of the result set, for O(N × log(K)) work where K = LIMIT + OFFSET. - Otherwise: Uses a full sort, O(N × log(N)). If
LIMITis omitted, the server usesapi.default_limit; the effective limit and offset still determine which algorithm runs. - Memory: Sorting can allocate temporary sort-key storage for eligible result sets, so do not assume it is in-place.
For large result sets (e.g., 1M documents with 800K matches):
- Keep
LIMIT + OFFSETwell below the result count to use the partial-sort path. - Measure the chosen sort column on production-like data; primary-key sorting still compares the matching results.
- Results are sorted before OFFSET and LIMIT are applied, so pagination is correct. For example, 800K matches with
LIMIT 100use the partial-sort path.
Column Validation
- Primary key: Always valid
- Filter columns: Must be configured
- Non-existent columns: Rejected with an error
Pagination (LIMIT/OFFSET)
Control the number of results returned using LIMIT and OFFSET.
LIMIT - Maximum Results
SEARCH <table> <query> LIMIT <n>Example:
SEARCH articles tech LIMIT 10Default: 100 (configurable via api.default_limit in config.yaml) Range: 1-1000. api.default_limit itself must be between 5 and 1000, but an explicit LIMIT clause accepts any value from 1 up to 1000.
MySQL-style LIMIT <offset>,<count> is also accepted; combining it with a separate OFFSET clause is an error.
OFFSET - Skip Results
SEARCH <table> <query> OFFSET <n>Example:
SEARCH articles tech LIMIT 10 OFFSET 20This returns results 21-30 (skips first 20).
Pagination Examples
Page 1 (first 10 results):
SEARCH articles tech LIMIT 10 OFFSET 0Page 2 (results 11-20):
SEARCH articles tech LIMIT 10 OFFSET 10Page 3 (results 21-30):
SEARCH articles tech LIMIT 10 OFFSET 20Maximum Query Length
MygramDB rejects queries whose combined expression length (search text + AND/NOT terms + FILTER values) exceeds the configured limit.
- Default: 128 characters
- Config:
api.max_query_length(0disables the guard) - Error:
ERROR 3005 Query expression length (...) exceeds maximum allowed length...
Keep boolean expressions compact or raise the limit in config.yaml if applications require longer filters.
Complete Example with All Options
SEARCH threads (golang OR python) AND tutorial
FILTER status = published
SORT created_at DESC
LIMIT 10
OFFSET 20This query:
- Finds documents with "tutorial" AND ("golang" OR "python")
- Filters to only published documents
- Sorts by creation date (newest first)
- Returns results 21-30 (page 3 with 10 results per page)
Pagination Performance
- OFFSET cost: O(N) where N = OFFSET (results are still generated, just not returned)
- Best practice: Use LIMIT with SORT for consistent pagination
- Deep pagination: Large OFFSET values (e.g., 10000+) can be slow
BM25 Relevance Scoring (SORT _score)
Sort results by relevance using the BM25 ranking function.
What is BM25?
BM25 is a standard ranking function that scores relevance from how often a term appears, how rare the term is, and how long the document is. Use it when you want the most relevant documents on top rather than plain ID order.
Syntax
SEARCH <table> <query> SORT _score [ASC|DESC]How It Works
BM25 computes a relevance score for each document based on:
- TF (Term Frequency): How often the search term appears in the document
- IDF (Inverse Document Frequency): How rare the term is across all documents
- Document length normalization: Shorter documents with matching terms score higher
Parameters (configurable in the bm25 section of config.yaml):
bm25.k1— Term frequency saturation (default1.2)bm25.b— Document length normalization (default0.75; 0 = none, 1 = full)
Examples
SEARCH articles "machine learning" SORT _score DESC LIMIT 10
SEARCH articles golang AND tutorial SORT _score LIMIT 20Requirements
SORT _score requires bm25.enable: true. The server retains normalized text for scoring independently of memory.verify_text, which controls n-gram post-filtering.
| Setting | Why | Error when missing |
|---|---|---|
bm25.enable: true | Turns on relevance scoring | SORT _score requires BM25 to be enabled in configuration |
bm25:
enable: true
k1: 1.2
b: 0.75
memory:
verify_text: "off" # post-filtering policy; text is still retained for scoringCombining with Filters
SEARCH articles "database" SORT _score DESC FILTER category = tech LIMIT 10Highlighting (HIGHLIGHT)
Return text snippets with search terms highlighted using configurable tags.
Normalized text is retained
The server retains normalized text for the query-level HIGHLIGHT feature even when memory.verify_text is "off". verify_text controls n-gram post-filtering; it does not disable snippet generation.
Syntax
SEARCH <table> <query> HIGHLIGHT [TAG <open> <close>] [SNIPPET_LEN <n>] [MAX_FRAGMENTS <n>]Options
| Option | Default | Range | Description |
|---|---|---|---|
| TAG | <em> / </em> | — | Open and close tags wrapping matched terms |
| SNIPPET_LEN | 100 | 1–10,000 | Max code points per snippet fragment |
| MAX_FRAGMENTS | 3 | 1–100 | Max fragments joined by ellipsis (...) |
Examples
Default highlighting:
SEARCH articles "machine learning" HIGHLIGHT LIMIT 10Custom tags:
SEARCH articles "golang" HIGHLIGHT TAG <strong> </strong> LIMIT 10Longer snippets with more fragments:
SEARCH articles "database" HIGHLIGHT SNIPPET_LEN 200 MAX_FRAGMENTS 5 LIMIT 10Combining with Other Clauses
SEARCH articles "tech" HIGHLIGHT TAG <b> </b> SORT _score DESC FILTER status = 1 LIMIT 10Fuzzy Search (FUZZY)
Match terms within a specified Levenshtein edit distance (insertions, deletions, substitutions).
What is Levenshtein edit distance?
Levenshtein edit distance is the number of insertions, deletions, and substitutions needed to turn one string into another. FUZZY 1 tolerates about one typo; FUZZY 2 allows a somewhat wider candidate set.
Syntax
SEARCH <table> <query> FUZZY [distance]Parameters
- distance (optional):
1(default) or21: Match terms within 1 edit operation2: Match terms within 2 edit operations
Examples
SEARCH articles "machne" FUZZY LIMIT 10
SEARCH articles "databse" FUZZY 2 LIMIT 10Performance
Fuzzy search pre-filters candidates by length difference to avoid unnecessary distance computations. FUZZY 1 (the default) is the fastest.
FUZZY returns every document that the same query returns without FUZZY, including terms shorter than the configured n-gram size and mixed CJK/ASCII terms, and may add edit-distance matches.
FUZZY accepts only 1 or 2. Other distances return a query error.
Error Handling
Invalid Queries
These queries return errors. Syntax errors use code 3000; an expression that the boolean parser cannot read uses 3010.
| Query | Response |
|---|---|
SEARCH threads (golang AND python | ERROR 3000 Unclosed parenthesis |
SEARCH threads golang AND python) | ERROR 3000 Unmatched closing parenthesis |
SEARCH threads golang AND | ERROR 3000 AND requires a term |
SEARCH threads golang NOT | ERROR 3000 NOT requires a term |
SEARCH threads "golang tutorial | ERROR 3000 Unclosed quote: " |
Empty parentheses or an operator with nothing on one side inside a group fail in the boolean parser, with a message such as Expected term or opening parenthesis '('.
Invalid Filters
Non-existent table:
SEARCH nonexistent tech
ERROR 4007 Table not found: nonexistentInvalid filter column:
SEARCH articles tech FILTER bad!name=1
ERROR 3006 Invalid filter columnInvalid Sorting
Non-existent column:
SEARCH articles tech SORT nonexistent DESC
ERROR 3007 Sort column 'nonexistent' not found. Column does not exist as filter column or primary key. Check column name spelling.Performance Tips
Each SEARCH runs through a fixed pipeline: the query is parsed to an AST, n-gram lookup produces candidate documents, then AND/NOT/FILTER narrow that candidate set in sequence before SORT and LIMIT/OFFSET produce the final page. The tips below each target one stage of this pipeline, and the DEBUG command reports timing per stage using these same names.
1. Place Restrictive Terms First
-- Good: Specific term first
SEARCH articles "machine learning" AND tutorial
-- Less optimal: Generic term first
SEARCH articles tutorial AND "machine learning"2. Use Parentheses for Clarity
-- Explicit and readable
SEARCH threads (golang OR python) AND (web OR api)
-- Harder to understand
SEARCH threads golang OR python AND web OR api3. Avoid Leading NOT Operators
-- Good: Positive term first
SEARCH articles tech NOT old
-- Less optimal: Leading NOT
SEARCH articles NOT oldLeading NOT requires scanning all documents before exclusion.
4. Combine Filters and Text Search
-- Good: Filter narrows results early
SEARCH articles tech FILTER category = ai FILTER status = 1
-- Works but less efficient
SEARCH articles tech AND ai AND publishedFilters on indexed columns are faster than text search on those terms.
5. Keep Sorted Pages Small
The server uses a partial sort when LIMIT + OFFSET is less than half of the matching result count. If LIMIT is omitted, api.default_limit supplies the effective value. A large offset can therefore require a full sort even when the requested page is small.
-- A small page can use partial sort when it is less than half of the matches
SEARCH articles tech SORT created_at DESC LIMIT 10
-- A large offset can make the effective page size too large for partial sort
SEARCH articles tech SORT created_at DESC LIMIT 10 OFFSET 100006. Minimize Deep Pagination
-- Efficient
SEARCH articles tech LIMIT 10 OFFSET 0
-- Less efficient (large OFFSET)
SEARCH articles tech LIMIT 10 OFFSET 10000Consider alternative pagination strategies for deep results (e.g., cursor-based).
7. Preserve Boolean Cache Keys
Boolean-query cache keys preserve parsed token, quote, and parenthesis structure. Queries whose full-width whitespace, parentheses, or quoting produce different expressions use separate cache entries; equivalent Unicode whitespace that parses identically may share an entry.
COUNT Command
All boolean query syntax works with COUNT as well:
COUNT <table> <query_expression> [FILTER ...]Examples:
COUNT threads (golang OR python) AND tutorial
COUNT articles tech FILTER status = 1 FILTER category = ai
COUNT posts database AND (mysql OR postgresql) NOT sqliteNote: COUNT does not support SORT, LIMIT, or OFFSET (not needed for counting).
Implementation Details
Grammar (BNF)
Queries are parsed into an abstract syntax tree (AST) with this grammar, which encodes the precedence described above:
query → or_expr
or_expr → and_expr (OR and_expr)*
and_expr → not_expr (AND not_expr)*
not_expr → NOT not_expr | primary
primary → TERM | '(' or_expr ')'Performance Characteristics
- AND operations: Efficient intersection using sorted posting lists
- OR operations: Efficient union using set operations
- NOT operations: Complement against all documents (potentially expensive)
- Parentheses: No performance overhead; only affects parsing
N-gram Tokenization
MygramDB uses n-gram tokenization for indexing and search:
- Default n-gram size: 2 (bigrams) - configurable per table
- CJK ideographs: Separate n-gram size for kanji/hanzi (configurable); kana and other scripts use
ngram_size - Unicode normalization: NFKC normalization, width conversion, optional lowercasing
Terms shorter than the configured n-gram size use stored normalized text for substring matching, including terms under NOT. Standard server initialization retains this text independently of memory.verify_text. If a store has no normalized text for fallback, the query returns ERROR 4000 instead of ignoring a short NOT term or returning an incomplete result.
Snapshot Synchronization Commands
SYNC Command
Manually trigger snapshot synchronization from MySQL to MygramDB.
Syntax:
SYNC <table_name>Example:
SYNC articlesResponse:
OK SYNC STARTED table=articlesSee SYNC Command Guide for detailed usage.
SYNC STATUS Command
Check the progress and status of SYNC operations.
Syntax:
SYNC STATUSResponse Examples:
OK SYNC_STATUS
table=articles status=IN_PROGRESS progress=10000/25000 rows (40.0%) rate=5000 rows/sOK SYNC_STATUS
table=articles status=COMPLETED rows=25000 time=5.2s gtid=uuid:123 replication=STARTEDWhen no sync has run:
OK SYNC_STATUS
status=IDLE message="No sync operation performed"See SYNC Command Guide for detailed field descriptions.
See Also
- Query Guide - Practical search examples
- SYNC Command Guide - Manual snapshot synchronization
- Protocol Reference - All commands and protocol details
- Configuration Guide - Configure filters, n-gram sizes, and limits
- Performance Tuning - Advanced optimization techniques