Skip to content

Node.js / Python / Go Client Libraries ​

MygramDB provides official TCP client libraries for application code. Use them when you want typed search, count, document lookup, FACET, runtime variables, and on-demand sync without building the TCP protocol yourself.

Scope

This page covers the application clients for Node.js, Python, and Go, plus where the bundled C/C++ SDK fits. The C/C++ API, CMake package, and pkg-config usage are documented on libmygramclient.

Support Matrix ​

LanguagePackageRequirementNotes
Node.jsmygramdb-clientNode.js 22+TypeScript types, pure JavaScript implementation, optional native binding
Pythonmygramdb-clientPython 3.11+asyncio, zero external dependencies, dataclass types
Gogithub.com/libraz/go-mygram-clientGo 1.26+standard library only, context.Context variants, safe for concurrent use
C / C++bundled libmygramclientC11 / C++17C and C++ APIs, installed SDK

The C/C++ SDK installs the CMake targets MygramDB::client_static and MygramDB::client_shared and a mygramclient.pc pkg-config file.

Releases for MygramDB v1.12

Use mygramdb-client 1.7.0 (Node.js), mygramdb-client 1.6.0 (Python), or go-mygram-client v0.7.0 (Go) or later with v1.11 and v1.12 servers. These releases frame each reply by the command that produced it, so FACET, CONFIG HELP <path>, SYNC STATUS, and a failing HIGHLIGHT or DEBUG search are read to their real end. They also quote by Unicode White_Space like the server, and name the 1008 and 1009 configuration-variable errors.

Load data before querying

The clients are thin wrappers around MygramDB server commands. If existing rows have not been loaded yet, run SYNC <table> first. See SYNC Command.

Rebuild C/C++ programs

The shared library uses soname 2 (VERSION 2.0.0); public search-expression structures changed layout. Rebuild and relink native programs against the current headers. See libmygramclient for the C/C++ API.

Shared Concepts ​

What is raw boolean search?

Raw boolean search passes a full search expression, with AND, OR, NOT, and parentheses, straight to the server's query parser. Use it for conditions such as python OR (ruby AND rails) that the simple search() builder cannot express.

  • Use articles on a single-database server, or app_db.articles when the instance indexes tables from multiple databases.
  • search() / Search() suits simple terms and AND/NOT-style searches.
  • For OR and parentheses, convert the expression and pass the result to searchRaw() / SearchRaw() / search_raw().
  • The web-syntax converter treats a whole-word or as OR, quotes literal words such as order and terms with apostrophes, and turns a minus inside a group into NOT. Each phrase and OR group is emitted once, so pass the output directly to the raw search method.
  • The converter groups an expression the way the server does. Implicit AND binds tighter than OR, so a OR b c converts to (a OR b c), the same as its parenthesized form. A negated group excludes the whole group: x +(a -(b OR c)) converts to x AND (a NOT (b OR c)). A word that only begins with OR, such as OR-tools, stays a term, and + or - directly beside a top-level OR (+a OR b) is rejected as a missing operand.
  • A search response carries the current page of results and the total number of matches before limit/offset.
  • FACET results are paginated as well. Each value's count is the number of matching documents for that value, and totalCount / total_count / TotalCount is the number of distinct values before pagination. Values with equal counts keep a stable order across pages.
  • BM25 scoring, highlighting, fuzzy search, and facets depend on the server-side table configuration.
  • Runtime variables and SYNC are TCP commands that the client libraries expose.

Administrative commands require authentication

CONFIG, SET / SHOW VARIABLES, DUMP, REPLICATION, SYNC, OPTIMIZE, DEBUG, and CACHE require authentication only when the server has a non-empty api.admin_token. search, count, get, facet, and INFO work without authentication. When api.admin_token is set, INFO omits its replication section until the connection completes AUTH.

To have the client send AUTH on each new connection, including automatic reconnects, configure adminToken (Node.js), admin_token (Python), or AdminToken (Go). An AUTH sent by hand with sendCommand() or send_command() applies only to that connection, so use the SDK option when reconnects must keep admin access.

Install ​

Install the package for your language.

bash
npm install mygramdb-client
bash
yarn add mygramdb-client
pnpm add mygramdb-client
bun add mygramdb-client
bash
pip install mygramdb-client
bash
go get github.com/libraz/go-mygram-client

Connect, run a search sorted by created_at, then count matches and fetch one document by primary key.

ts
import { createMygramClient } from 'mygramdb-client'

const client = createMygramClient({ host: 'localhost', port: 11016 })
await client.connect()

const results = await client.search('articles', 'hello', {
  limit: 100,
  sortColumn: 'created_at',
  sortDesc: true
})

console.log(`${results.totalCount} results`)

const count = await client.count('articles', 'technology')
const doc = await client.get('articles', '12345')

client.disconnect()
python
import asyncio
from mygramdb_client import MygramClient, ClientConfig, SearchOptions

async def main():
    async with MygramClient(ClientConfig(host='localhost', port=11016)) as client:
        results = await client.search(
            'articles',
            'hello',
            SearchOptions(limit=100, sort_column='created_at', sort_desc=True),
        )
        print(f'{results.total_count} results')

        count = await client.count('articles', 'technology')
        doc = await client.get('articles', '12345')

asyncio.run(main())
go
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)
	}

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

Build and parse a database-qualified table name, convert a web-style expression, and run it as a raw boolean search.

ts
import {
  convertSearchExpression,
  qualifyTableIdentity,
  parseTableIdentity
} from 'mygramdb-client'

const table = qualifyTableIdentity('articles', 'app_db') // app_db.articles
console.log(parseTableIdentity(table)) // { database: 'app_db', table: 'articles' }

const raw = convertSearchExpression('python OR (ruby AND rails)')
const res = await client.searchRaw(table, raw, { limit: 50 })
python
import asyncio
from mygramdb_client import (
    ClientConfig,
    MygramClient,
    SearchRawOptions,
    convert_search_expression,
    parse_table_identity,
    qualify_table_identity,
)

async def main():
    async with MygramClient(ClientConfig(host='localhost', port=11016)) as client:
        table = qualify_table_identity('articles', 'app_db')  # app_db.articles
        print(parse_table_identity(table))                    # ('app_db', 'articles')

        raw = convert_search_expression('python OR (ruby AND rails)')
        res = await client.search_raw(table, raw, SearchRawOptions(limit=50))

asyncio.run(main())
go
table, _ := mygram.QualifyTableIdentity("articles", "app_db")
db, name, _ := mygram.ParseTableIdentity(table)
fmt.Println(db, name) // app_db articles

raw, _ := mygram.ConvertSearchExpression("python OR (ruby AND rails)")
resp, _ := client.SearchRaw(table, raw, mygram.SearchRawOptions{Limit: 50})
fmt.Println(resp.TotalCount)

resp, _ = client.SearchRawWithHighlights(
	table,
	raw,
	mygram.SearchRawOptions{Limit: 10},
)
fmt.Println(resp.Results)

Parsed expressions changed shape

The parsed SearchExpression returned by parseSearchExpression() / parse_search_expression() / ParseSearchExpression() no longer has optionalTerms / optional_terms / OptionalTerms; the field was always empty. requiredIsGroup and excludedIsGroup (required_is_group, excluded_is_group; RequiredIsGroup, ExcludedIsGroup) run parallel to the required and excluded terms and mark the entries that are (...) groups, so a quoted phrase shaped like a group, such as "(a OR b)", stays a literal phrase. Code that read the removed field must drop it.

Advanced Search and Administration ​

The examples below add BM25 ranking, HIGHLIGHT, FACET, runtime variables, and SYNC. The Node.js and Go examples also show FUZZY, and the Python example combines everything in one program.

Node.js / TypeScript ​

ts
const ranked = await client.search('articles', 'machine learning', {
  sortColumn: '_score',
  sortDesc: true,
  limit: 10
})

const highlighted = await client.search('articles', 'golang', {
  highlight: {
    openTag: '<strong>',
    closeTag: '</strong>',
    snippetLen: 200,
    maxFragments: 3
  },
  sortColumn: '_score',
  sortDesc: true,
  limit: 10
})

const fuzzy = await client.search('articles', 'machne', {
  fuzzy: 1,
  limit: 10
})

const facets = await client.facet('articles', 'category', {
  query: 'machine learning',
  filters: { status: '1' },
  limit: 10
})
ts
const adminToken = process.env.MYGRAM_API_ADMIN_TOKEN
const adminClient = createMygramClient({
  host: 'localhost',
  port: 11016,
  ...(adminToken ? { adminToken } : {})
})
await adminClient.connect()

await adminClient.setVariable('logging.level', 'info')
console.log(await adminClient.showVariables('logging%'))

await adminClient.sync('app_db.articles')
console.log(await adminClient.syncStatus())
await adminClient.syncStop('app_db.articles')
adminClient.disconnect()

Set MYGRAM_API_ADMIN_TOKEN when the server has api.admin_token configured. The client authenticates during connect() and on subsequent reconnects.

Python ​

python
import asyncio
import os
from mygramdb_client import ClientConfig, FacetOptions, MygramClient, SearchOptions

async def main():
    config = ClientConfig(
        host='localhost',
        port=11016,
        admin_token=os.environ.get('MYGRAM_API_ADMIN_TOKEN', ''),
    )
    async with MygramClient(config) as client:
        res = await client.search_with_highlights(
            'articles',
            'golang',
            SearchOptions(limit=10, sort_column='_score', sort_desc=True),
        )

        facets = await client.facet(
            'articles',
            'category',
            FacetOptions(query='machine learning', filters={'status': '1'}, limit=10),
        )

        await client.set_variable('logging.level', 'info')
        print(await client.show_variables('logging%'))

        await client.sync('app_db.articles')
        print(await client.sync_status())
        await client.sync_stop('app_db.articles')

asyncio.run(main())

Set MYGRAM_API_ADMIN_TOKEN when the server has api.admin_token configured. ClientConfig makes the client authenticate when it connects and after a transparent reconnect.

Go ​

go
ranked, _ := client.Search("articles", "machine learning", mygram.SearchOptions{
	SortColumn: "_score",
	SortDesc:   true,
	Limit:      10,
})
fmt.Println(ranked.TotalCount)

highlighted, _ := client.Search("articles", "golang", mygram.SearchOptions{
	Highlight: &mygram.HighlightOptions{
		OpenTag:      "<strong>",
		CloseTag:     "</strong>",
		SnippetLen:   200,
		MaxFragments: 3,
	},
	SortColumn: "_score",
	SortDesc:   true,
	Limit:      10,
})
if len(highlighted.Results) > 0 {
	fmt.Println(highlighted.Results[0].Snippet)
}

fuzzy, _ := client.Search("articles", "machne", mygram.SearchOptions{
	Fuzzy: 1,
	Limit: 10,
})
fmt.Println(fuzzy.TotalCount)

facets, _ := client.Facet("articles", "category", mygram.FacetOptions{
	Query:   "machine learning",
	Filters: map[string]string{"status": "1"},
	Limit:   10,
})
fmt.Println(facets.Results)
go
package main

import (
	"fmt"
	"log"
	"os"

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

func main() {
	adminToken := os.Getenv("MYGRAM_API_ADMIN_TOKEN")
	client := mygram.NewClientWithConfig(mygram.ClientConfig{
		Host:       "localhost",
		Port:       11016,
		AdminToken: adminToken,
	})
	defer client.Close()
	if err := client.Connect(); err != nil {
		log.Fatal(err)
	}

	if err := client.SetVariable("logging.level", "info"); err != nil {
		log.Fatal(err)
	}
	vars, err := client.ShowVariables("logging%")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(vars)

	if _, err := client.Sync("app_db.articles"); err != nil {
		log.Fatal(err)
	}
	status, err := client.SyncStatus()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(status)
	if _, err := client.SyncStop("app_db.articles"); err != nil {
		log.Fatal(err)
	}
}

Set MYGRAM_API_ADMIN_TOKEN when the server has api.admin_token configured. ClientConfig.AdminToken is sent on every connection, including reconnects.

Go concurrency

The Go client is designed for concurrent use. Use the context.Context variants such as SearchContext, SearchRawContext, and SyncContext when you need request-scoped cancellation or deadlines.

Server-Side References ​

FeatureDocumentation
Query syntax, AND / OR / NOTQuery Syntax
BM25 _scoreQuery Guide - Relevance Sort
HIGHLIGHTQuery Guide - Highlighting
FUZZYQuery Guide - Fuzzy Search
FACETQuery Guide - FACET
SYNCSYNC Command
Runtime variablesOperations

Repositories ​