### install() usage example Source: https://docs.machbase.com/neo/jsh/modules/service Example of installing a service named 'alpha' with executable 'echo' and args ['hello']. The callback prints the error message on failure or the snapshot's config name and status on success. ```javascript const service = require('service'); const client = new service.Client(); client.install({ name: 'alpha', enable: false, executable: 'echo', args: ['hello'], }, (err, snapshot) => { if (err) { console.println(err.message); return; } console.println(snapshot.config.name, snapshot.status); }); ``` -------------------------------- ### Setup: Install dotnet-sdk, create project, add MQTTnet Source: https://docs.machbase.com/neo/api-mqtt/examples/mqtt-csharp Setup steps for creating a C# MQTT client project: install the .NET SDK, create a project directory, create a console project targeting net7.0, and add the MQTTnet package version 4.3.3.952. ```sh brew install dotnet-sdk ``` ```sh mkdir csharp-mqtt && cd csharp-mqtt ``` ```sh dotnet new console --framework net7.0 ``` ```sh dotnet add package MQTTnet --version 4.3.3.952 ``` -------------------------------- ### Example machadmin workflows Source: https://docs.machbase.com/dbms/reference/command-line-tools/machadmin Example workflows: initialize and start, check and stop, and renew the license. ```bash # Initialize the database and start the server machadmin -c machadmin -u # Check server status, then stop it machadmin -e machadmin -s # Renew the license machadmin -s machadmin -t new_license.dat machadmin -u ``` -------------------------------- ### Install neo-client Source: https://docs.machbase.com/dbms/development-tools-integration/go Use the go get command to install the Machbase Neo client module. ```bash go get github.com/machbase/neo-client/v2 ``` -------------------------------- ### Start Cluster with machclusterctl start Source: https://docs.machbase.com/dbms/installation-deployment-upgrade/cluster-edition Starts the installed cluster again. The install command already starts the Coordinator, Deployers, Lookup, Brokers, and Warehouses, so this is only needed when you want to start the cluster after it has been stopped. ```bash machclusterctl start ``` -------------------------------- ### Install full package on Coordinator and Deployer hosts Source: https://docs.machbase.com/dbms/installation-deployment-upgrade/cluster-edition Install the full package on the Coordinator host and on each Deployer host. The Coordinator example creates /home/machbase/coordinator and extracts the tarball there; the Deployer example creates /home/machbase/deployer and extracts the same tarball there. Run each on the host for its corresponding role. ```bash mkdir -p /home/machbase/coordinator scp machbase@package-host:/path/to/machbase-cluster-8.7.0.official-LINUX-X86-64-release.tgz /home/machbase/ tar zxf /home/machbase/machbase-cluster-8.7.0.official-LINUX-X86-64-release.tgz -C /home/machbase/coordinator ``` ```bash mkdir -p /home/machbase/deployer scp machbase@package-host:/path/to/machbase-cluster-8.7.0.official-LINUX-X86-64-release.tgz /home/machbase/ tar zxf /home/machbase/machbase-cluster-8.7.0.official-LINUX-X86-64-release.tgz -C /home/machbase/deployer ``` -------------------------------- ### ALTER SYSTEM INSTALL LICENSE grammar and examples Source: https://docs.machbase.com/dbms/reference/sql/syntax/system-session-alter-syntax Grammar and examples for installing a license. The default path is $MACHBASE_HOME/conf/license.dat; a specified path is given as a quoted string after '='. ```sql -- Default path ($MACHBASE_HOME/conf/license.dat) alter_system_install_license_stmt ::= 'ALTER SYSTEM INSTALL LICENSE' -- Specified path alter_system_install_license_path_stmt ::= 'ALTER SYSTEM INSTALL LICENSE' '=' "'" path "'" ``` ```sql -- Install from the default path ALTER SYSTEM INSTALL LICENSE; -- Install from a specified path ALTER SYSTEM INSTALL LICENSE = '/tmp/new_license.dat'; ``` -------------------------------- ### Prepare example LOOKUP and TAG tables Source: https://docs.machbase.com/dbms/lookup-table-usage/query-analysis Creates the LOOKUP table ch9_query_master and the TAG table ch9_query_data, then inserts sample rows into both. Use this as the prerequisite setup for the query examples in this section. ```sql CREATE LOOKUP TABLE ch9_query_master ( sensor_id VARCHAR(32) PRIMARY KEY, site VARCHAR(32), unit VARCHAR(16), status VARCHAR(16) ); INSERT INTO ch9_query_master VALUES ('TEMP-01', 'SEOUL', 'C', 'ACTIVE'); INSERT INTO ch9_query_master VALUES ('TEMP-02', 'BUSAN', 'C', 'INACTIVE'); CREATE TAG TABLE ch9_query_data ( name VARCHAR(32) PRIMARY KEY, time DATETIME BASETIME, value DOUBLE SUMMARIZED ); INSERT INTO ch9_query_data VALUES ('TEMP-01', TO_DATE('2026-01-01 00:00:00'), 23.5); INSERT INTO ch9_query_data VALUES ('TEMP-02', TO_DATE('2026-01-01 00:00:00'), 19.0); ``` -------------------------------- ### License info response example Source: https://docs.machbase.com/neo/api-http/ui-api Example response from GET /web/api/license. Contains license id, type, customer, project, country code, install date, and issue date. ```json { "success": true, "reason": "success or error reason", "elapse": "elapse time", "data": { "id": "license id", "type": "type", "customer": "customer", "project": "project", "countryCode": "country code", "installDate": "installation date", "issueDate": "license issue date" } } ``` -------------------------------- ### sqlTimeformat() usage example Source: https://docs.machbase.com/neo/tql/utilities Demonstrates the use of sqlTimeformat with a CSV output in the Asia/Seoul timezone. ```js FAKE( json({ [ 1701345032123456789, 10], [ 1701345043219876543, 11] })) MAPVALUE(0, time(value(0)) ) CSV( sqlTimeformat("YYYY-MM-DD HH24:MI:SS.nnnnnn"), tz("Asia/Seoul") ) ``` ```text 2023-11-30 20:50:32.123456,10 2023-11-30 20:50:43.219876,11 ``` -------------------------------- ### Common machclusterctl command examples Source: https://docs.machbase.com/dbms/reference/command-line-tools/machclusterctl Examples of common machclusterctl operations: validate, install, apply, start, stop, status, connect, and export. Includes node-specific start/stop with --node and --type options. ```bash # Validate YAML machclusterctl validate -f my_cluster.yaml # Install a new cluster machclusterctl install -f my_cluster.yaml # Apply changes to a running cluster machclusterctl apply -f my_cluster.yaml # Start the cluster machclusterctl start # Stop/start a specific node or node type machclusterctl stop --node broker-1 machclusterctl start --type warehouse # Check status machclusterctl status # Connect to a Broker and run SQL machclusterctl connect # Stop the cluster machclusterctl stop # Export the configuration machclusterctl export -o cluster_config_backup.yaml ``` -------------------------------- ### Prepare EXAMPLE table and data Source: https://docs.machbase.com/neo/tql/example-time Run this SQL to create the EXAMPLE tag table and insert sample data used by the time examples. ```sql CREATE TAG TABLE IF NOT EXISTS EXAMPLE ( NAME VARCHAR(20) PRIMARY KEY, TIME DATETIME BASETIME, VALUE DOUBLE SUMMARIZED ); INSERT INTO EXAMPLE VALUES('TAG0', TO_DATE('2021-08-12 12:00:00 123:456:789'), 10); INSERT INTO EXAMPLE VALUES('TAG0', TO_DATE('2021-08-13 12:00:00 123:456:789'), 11); ``` -------------------------------- ### strSprintf() formatting example Source: https://docs.machbase.com/neo/tql/utilities Formats a string using a format specifier and provides the resulting output. ```js FAKE( csv(`world,3.141792`) ) MAPVALUE(1, parseFloat(value(1))) MAPVALUE(2, strSprintf(`hello %s? %1.2f`, value(0), value(1))) CSV() ``` ```csv world,3.141792,hello world? 3.14 ``` -------------------------------- ### Time function usage Source: https://docs.machbase.com/neo/tql/utilities Examples of using the time function with current time and epoch timestamps. ```js SQL(`select to_char(time), value from example where time < ?`, time('now')) CSV() ``` ```js SQL(`select to_char(time), value from example where time = ?`, time(1628737200123456789)) CSV() ``` -------------------------------- ### strTrimPrefix(str, prefix) : string Source: https://docs.machbase.com/neo/tql/utilities Returns str without the provided leading prefix string. If str doesn't start with prefix, str is returned unchanged. ```APIDOC ## strTrimPrefix(str, prefix) : string ### Description Returns str without the provided leading prefix string. If str doesn't start with prefix, str is returned unchanged. ### Syntax `strTrimPrefix(str, prefix) : string` ### Parameters - **str** (string) - Required - The string to trim. - **prefix** (string) - Required - The prefix to remove. ### Returns - **string** - The resulting string. ``` -------------------------------- ### timeAdd('now') usage Source: https://docs.machbase.com/neo/tql/utilities Example of using timeAdd with 'now' to query data from 10 seconds ago. ```js SQL(`select to_char(time), value from example where time < ?`, timeAdd('now', '-10s')) CSV() ``` -------------------------------- ### ansiTimeformat() usage example Source: https://docs.machbase.com/neo/tql/utilities Demonstrates the use of ansiTimeformat with a CSV output in the UTC timezone. ```js FAKE( json({ [ 1701345032123456789, 10], [ 1701345043219876543, 11] })) MAPVALUE(0, time(value(0)) ) CSV( ansiTimeformat("yyyy-mm-dd hh:nn:ss.ffffff"), tz("UTC")) ``` ```text 2023-11-30 11:50:32.123456,10 2023-11-30 11:50:43.219876,11 ``` -------------------------------- ### timeAdd(epoch) usage Source: https://docs.machbase.com/neo/tql/utilities Example of using timeAdd with a specific epoch timestamp to query data from 5 seconds before that time. ```js SQL(`select to_char(time), value from example where time = ?`, timeAdd(1628737200123456789, '-5s')) CSV() ``` -------------------------------- ### Math functions with MAPVALUE and CHART Source: https://docs.machbase.com/neo/tql/utilities TQL example using math functions (sin, pow) with MAPVALUE to compute a value and render a 3D line chart. The code uses FAKE to generate a meshgrid, MAPVALUE to compute sin(pow(x,2)+pow(y,2))/(pow(x,2)+pow(y,2)), then builds a list and pops values, and finally uses CHART with a line3D series. ```js FAKE(meshgrid(linspace(-4,4,100), linspace(-4,4, 100))) MAPVALUE(2, sin(pow(value(0), 2) + pow(value(1), 2)) / (pow(value(0), 2) + pow(value(1), 2)) ) MAPVALUE(0, list(value(0), value(1), value(2))) POPVALUE(1, 2) CHART( plugins("gl"), size("600px", "600px"), chartOption({ grid3D:{}, xAxis3D:{}, yAxis3D:{}, zAxis3D:{}, series:[ {type: "line3D", data: column(0)}, ] }) ) ``` -------------------------------- ### Typical pkg workflow: init, install, run Source: https://docs.machbase.com/neo/jsh/packages Shows the typical workflow for creating a project, installing dependencies, and running a script. The commands are executed in the /work directory and assume the pkg CLI is available. ```sh /work > pkg init demo-app /work > pkg install github.com/acme/demo /work > pkg install generic-pkg /work > pkg run start ``` -------------------------------- ### hrtime() Usage Example Source: https://docs.machbase.com/neo/jsh/modules/process Usage example for hrtime(). Creates a start time, then computes the difference from that start, and prints whether the result is an array and its length. ```javascript const process = require('process'); const start = process.hrtime(); const diff = process.hrtime([start[0], start[1]]); console.println(Array.isArray(diff), diff.length); ``` -------------------------------- ### simplex() noise with MAPVALUE and CHART Source: https://docs.machbase.com/neo/tql/utilities TQL example using simplex() to generate Simplex noise based on seed and dimension values. The code creates a meshgrid, maps the absolute value of simplex(123, x, y) multiplied by 10, and renders a 3D bar chart with a visualMap color range. ```js FAKE( meshgrid( linspace(0, 10, 100), linspace(0, 10, 100) ) ) MAPVALUE(2, abs( simplex(123, value(0), value(1)) ) * 10) MAPVALUE(0, list(value(0), value(1), value(2))) CHART( plugins("gl"), size("600px", "600px"), chartOption({ visualMap: { max: 8, inRange:{ color:[ "#313695", "#74add1", "#e0f3f8", "#fee090", "#f46d43", "#a50026"]} }, grid3D:{ boxWidth:100, boxDepth:100, boxHeight:20}, xAxis3D:{}, yAxis3D:{}, zAxis3D:{}, series:[ {type: "bar3D", data: column(0), itemStyle:{opacity:1.0}}, ] }) ) ``` -------------------------------- ### strTime with sqlTimeformat() Source: https://docs.machbase.com/neo/tql/utilities Formats the current time using the sqlTimeformat pattern 'YYYY/MM/DD HH24:MI:SS.nnn' with UTC time zone. The example uses FAKE, MAPVALUE, and MARKDOWN functions to generate and display the result. ```js FAKE( linspace(0, 1, 1)) MAPVALUE(0, strTime(time("now"), sqlTimeformat("YYYY/MM/DD HH24:MI:SS.nnn"), tz("UTC")), "result") MARKDOWN(rownum(true)) ``` -------------------------------- ### Create Coordinator metadata and start Source: https://docs.machbase.com/dbms/installation-deployment-upgrade/cluster-edition Create metadata and start the Coordinator. Run these commands after configuring machbase.conf. ```bash machcoordinatoradmin -c machcoordinatoradmin -u ``` -------------------------------- ### Start Deployer process Source: https://docs.machbase.com/dbms/reference/command-line-tools/machdeployeradmin Starts the Deployer process using the -u/--startup option. ```bash machdeployeradmin -u ``` -------------------------------- ### Install paho-mqtt Source: https://docs.machbase.com/neo/api-mqtt/examples/mqtt-python Installs the paho-mqtt library via pip. Required for all examples on this page. ```bash pip install paho-mqtt ``` -------------------------------- ### timeformat() usage Source: https://docs.machbase.com/neo/tql/utilities Example of formatting time values in a CSV output using timeformat and a specific timezone. ```js FAKE( json({ [ 1701345032123456789, 10], [ 1701345043219876543, 11] })) MAPVALUE(0, time(value(0)) ) CSV(timeformat("DEFAULT"), tz("Asia/Seoul")) ``` -------------------------------- ### CREATE USER Examples Source: https://docs.machbase.com/dbms/reference/sql/syntax/user-auth-syntax Examples of creating a basic user, a user with a specific password policy, and a user with public-key authentication. ```sql -- Create a basic user CREATE USER app_user IDENTIFIED BY 'App#1234'; -- Specify password policy CREATE USER ops_user IDENTIFIED BY 'Ops@Strong1' PASSWORD POLICY HIGH; -- Create with AUTH KEY (public-key authentication) CREATE USER app_user IDENTIFIED BY 'App#1234' WITH AUTH KEY ( key='-----BEGIN PUBLIC KEY-----\nMFkw...(omitted)...==\n-----END PUBLIC KEY-----\n', valid_before='2047-12-31', comment='initial key' ); ``` -------------------------------- ### strTime with numeric timeformat Source: https://docs.machbase.com/neo/tql/utilities Formats the current time using a numeric time format pattern '2006/01/02 15:04:05.999' with UTC time zone. The example uses FAKE, MAPVALUE, and MARKDOWN functions to generate and display the result. ```js FAKE( linspace(0, 1, 1)) MAPVALUE(0, strTime(time("now"), "2006/01/02 15:04:05.999", tz("UTC")), "result") MARKDOWN(rownum(true)) ``` -------------------------------- ### strTime with named timeformat Source: https://docs.machbase.com/neo/tql/utilities Formats the current time using the named time format 'RFC822' with UTC time zone. The example uses FAKE, MAPVALUE, and MARKDOWN functions to generate and display the result. ```js FAKE( linspace(0, 1, 1)) MAPVALUE(0, strTime(time("now"), "RFC822", tz("UTC")), "time") MARKDOWN(rownum(true)) ``` -------------------------------- ### Rollup Thread Lifecycle Examples Source: https://docs.machbase.com/neo/sql/rollup Practical examples of starting, stopping, and forcing rollup aggregation. ```sql EXEC ROLLUP_START('_tag_data_rollup_30sec'); EXEC ROLLUP_STOP('_tag_data_rollup_10min'); EXEC ROLLUP_FORCE('_tag_rollup_hour'); -- Process pending data for the hourly rollup now ``` -------------------------------- ### MQTT client usage example Source: https://docs.machbase.com/neo/jsh/modules/mqtt A complete example demonstrating client initialization, event handling for connection, subscription, messaging, and disconnection. ```js const mqtt = require('mqtt'); const client = new mqtt.Client({ servers: ['tcp://127.0.0.1:1883'], username: 'user', password: 'pass', keepAlive: 60, connectRetryDelay: 2000, connectTimeout: 10 * 1000, cleanStartOnInitialConnection: true, }); client.on('open', () => { console.println('Connected'); client.subscribe('test/topic', { qos: 0, properties: { subscriptionIdentifier: 7, }, }); }); client.on('subscribed', (topic, reason) => { console.println('Subscribed:', topic, 'reason:', reason); client.publish('test/topic', 'Hello, MQTT!'); }); client.on('message', (msg) => { console.println('Message:', msg.topic, msg.payloadText); client.unsubscribe(msg.topic, { properties: { user: { source: 'example', }, }, }); }); client.on('unsubscribed', (topic, reason) => { console.println('Unsubscribed:', topic, 'reason:', reason); client.close(); }); client.on('error', (err) => { console.println('Error:', err.message); }); client.on('close', () => { console.println('Disconnected'); }); ``` -------------------------------- ### networkInterfaces() Usage Example Source: https://docs.machbase.com/neo/jsh/modules/os Example usage of networkInterfaces() to get the interface object and print its type. ```javascript const os = require('os'); const ifaces = os.networkInterfaces(); console.println(typeof ifaces); ``` -------------------------------- ### install() syntax Source: https://docs.machbase.com/neo/jsh/modules/service Syntax for client.install(config, callback). Installs a service from a config object and returns the installed service snapshot. ```javascript client.install(config, callback) ``` -------------------------------- ### parseBool example with code and result Source: https://docs.machbase.com/neo/tql/utilities Parses the string 'True' into a boolean value using the parseBool function. The code uses FAKE, MAPVALUE, and JSON functions, and the result shows the parsed value in a JSON response. ```js FAKE( csv(`world,True`) ) MAPVALUE(1, parseBool(value(1))) JSON() ``` ```json { "data": { "columns": [ "column0", "column1" ], "types": [ "string", "bool" ], "rows": [ [ "world", true ] ] }, "success": true, "reason": "success", "elapse": "122.667µs" } ``` -------------------------------- ### parseFloat example with code and result Source: https://docs.machbase.com/neo/tql/utilities Parses the string '3.141792' into a float number using the parseFloat function. The code uses FAKE, MAPVALUE, and JSON functions, and the result shows the parsed value in a JSON response. ```js FAKE( csv(`world,3.141792`) ) MAPVALUE(1, parseFloat(value(1))) JSON() ``` ```json { "data": { "columns": [ "column0", "column1" ], "types": [ "string", "double" ], "rows": [ [ "world", 3.141792 ] ] }, "success": true, "reason": "success", "elapse": "140.125µs" } ``` -------------------------------- ### servicectl start/stop usage example Source: https://docs.machbase.com/neo/jsh/services Usage example for starting and stopping the service named 'alpha'. ```sh /work > servicectl start alpha /work > servicectl stop alpha ``` -------------------------------- ### platform() and arch() usage example Source: https://docs.machbase.com/neo/jsh/modules/fs Usage example showing how to print the runtime platform and architecture using console.println. ```javascript const fs = require('fs'); console.println(fs.platform()); console.println(fs.arch()); ``` -------------------------------- ### Start Deployer Source: https://docs.machbase.com/dbms/installation-deployment-upgrade/cluster-edition Create metadata and start the Deployer. Run these commands after configuring machbase.conf. ```bash machdeployeradmin -c machdeployeradmin -u ``` -------------------------------- ### servicectl details get JSON output example Source: https://docs.machbase.com/neo/jsh/services Usage example for `servicectl details get` with `--format json` and a specific key. When a key is given, the output is a JSON object containing only that key. ```sh /work > servicectl details get alpha labels --format json { "labels": { "tier": "gold" } } ``` -------------------------------- ### Client.install(config, callback) Source: https://docs.machbase.com/neo/jsh/modules/service Installs a service with the given configuration. ```APIDOC ## Client.install(config, callback) ### Description Installs a service using the provided configuration. ### Method RPC ### Endpoint install(config, callback) ### Parameters - **config** (Object) - Required - Service configuration object. - **callback** (Function) - Required - Callback function with signature (err, result). ### Request Example ```js client.install({ name: 'my-service', ... }, (err, result) => { if (err) console.println(err.message); }); ``` ### Response - **result** (Object) - The install result. ``` -------------------------------- ### client.install(config, callback) Source: https://docs.machbase.com/neo/jsh/modules/service Installs a service from a config object and returns the installed service snapshot. ```APIDOC ## client.install(config, callback) ### Description Installs a service from a config object and returns the installed service snapshot. ### Method install ### Endpoint client.install(config, callback) ### Parameters #### Request Body - **config** (object) - Required - The service configuration object. - **name** (string) - Required - The name of the service. - **enable** (boolean) - Required - Whether the service is enabled. - **executable** (string) - Required - The executable to run. - **args** (array) - Optional - Arguments for the executable. #### Callback - **callback** (function) - Required - Callback function with (err, snapshot). ### Request Example ```js client.install({ name: 'alpha', enable: false, executable: 'echo', args: ['hello'], }, (err, snapshot) => { if (err) { console.println(err.message); return; } console.println(snapshot.config.name, snapshot.status); }); ``` ### Response #### Success Response - **snapshot** (object) - The installed service snapshot. - **config** (object) - The service configuration. - **status** (string) - The service status. #### Response Example ```js { "config": { "name": "alpha", "enable": false, "executable": "echo", "args": ["hello"] }, "status": "installed" } ``` ``` -------------------------------- ### param() example with curl GET request Source: https://docs.machbase.com/neo/tql/basic A complete example of using param() in a TQL script saved as 'example.tql' and invoking it with a curl GET request. The SQL statement uses a placeholder '?' that is filled by param('name'). ```js SQL( `select * from example where name = ?`, param('name')) CSV() ``` ```bash curl http://127.0.0.1:5654/db/tql/param.tql?name=TAG0 ``` -------------------------------- ### parseArgs.formatHelp() example Source: https://docs.machbase.com/neo/jsh/modules/util/parseargs Generates help text for a single-command config with usage, options, and positionals. The example includes options with descriptions and defaults, and prints the resulting help string. ```javascript const parseArgs = require('util/parseArgs'); const help = parseArgs.formatHelp({ usage: 'Usage: myapp [options] ', options: { userName: { type: 'string', short: 'u', description: 'User name', default: 'guest' }, enableDebug: { type: 'boolean', short: 'd', description: 'Enable debug mode', default: false } }, positionals: [ { name: 'file', description: 'Input file to process' } ] }); console.println(help); ``` -------------------------------- ### SUBSTR Usage Examples Source: https://docs.machbase.com/dbms/reference/sql/functions/functions-full Examples demonstrating SUBSTR with various start and length parameters on a sample table. ```sql Mach> CREATE LOG TABLE substr_table (c1 VARCHAR(10)); Created successfully. Mach> INSERT INTO substr_table values('ABCDEFG'); 1 row(s) inserted. Mach> INSERT INTO substr_table values('abstract'); 1 row(s) inserted. Mach> SELECT SUBSTR(c1, 1, 1) FROM substr_table; SUBSTR(c1, 1, 1) -------------------- a A [2] row(s) selected. Mach> SELECT SUBSTR(c1, 3, 3) FROM substr_table; SUBSTR(c1, 3, 3) -------------------- str CDE [2] row(s) selected. Mach> SELECT SUBSTR(c1, 2) FROM substr_table; SUBSTR(c1, 2) ----------------- bstract BCDEFG [2] row(s) selected. Mach> drop table substr_table; Dropped successfully. ``` -------------------------------- ### Create and populate example table Source: https://docs.machbase.com/neo/tql/reading SQL statements to create a tag table and insert sample data for testing TQL queries. ```sql CREATE TAG TABLE IF NOT EXISTS EXAMPLE ( NAME VARCHAR(20) PRIMARY KEY, TIME DATETIME BASETIME, VALUE DOUBLE SUMMARIZED); INSERT INTO EXAMPLE VALUES('TAG0', TO_DATE('2021-08-12'), 10); INSERT INTO EXAMPLE VALUES('TAG0', TO_DATE('2021-08-13'), 11); ``` -------------------------------- ### servicectl details get box output example Source: https://docs.machbase.com/neo/jsh/services Usage example showing the default box output for `servicectl details get alpha`. The table lists keys, types, and values for the service's runtime details. ```sh /work > servicectl details get alpha DETAILS (3) ┌─────────┬─────────┬────────────────────┐ │ KEY │ TYPE │ VALUE │ ├─────────┼─────────┼────────────────────┤ │ enabled │ boolean │ true │ │ labels │ object │ {"tier":"gold"} │ │ retries │ number │ 3 │ └─────────┴─────────┴────────────────────┘ ``` -------------------------------- ### Drop table via HTTP GET Source: https://docs.machbase.com/neo/api-http/create-drop Example of dropping a table using a direct HTTP GET request. ```http GET http://127.0.0.1:5654/db/query ?q=drop table EXAMPLE ``` -------------------------------- ### Run Machbase Go Examples Source: https://docs.machbase.com/dbms/development-tools-integration/go Commands to execute the provided example scripts located in the _example/ directory of the neo-client repository. ```bash go run ./_example/query.go -s 127.0.0.1:5656 -u sys -p manager go run ./_example/append.go -s 127.0.0.1:5656 -u sys -p manager go run ./_example/insert.go -s 127.0.0.1:5656 -u sys -p manager go run ./_example/scanbytag.go -s 127.0.0.1:5656 -u sys -p manager ``` -------------------------------- ### TOP_K usage example Source: https://docs.machbase.com/dbms/reference/sql/functions/functions-full Example query using TOP_K to get the top 3 most frequent alarm codes from event_log. Example result shows format '101:532,205:317,301:90'. ```sql SELECT TOP_K(alarm_code, 3) FROM event_log; ``` -------------------------------- ### Full MQTT client example in Go Source: https://docs.machbase.com/neo/api-mqtt/examples/mqtt-go Complete Go program demonstrating MQTT client usage with machbase-neo: connects, subscribes to replies, checks table existence, creates a tag table, inserts data, appends 100 records, queries, and disconnects. Includes comments on topic vs payload table specification. ```go package main import ( "fmt" "sync" "time" paho "github.com/eclipse/paho.mqtt.golang" ) func main() { wg := sync.WaitGroup{} // paho mqtt client options opts := paho.NewClientOptions() opts.SetCleanSession(true) opts.SetConnectRetry(false) opts.SetAutoReconnect(false) opts.SetProtocolVersion(4) opts.SetClientID("machbase-mqtt-cli") opts.AddBroker("127.0.0.1:5653") opts.SetKeepAlive(30 * time.Second) // connect to server with paho mqtt client client := paho.NewClient(opts) connectToken := client.Connect() connectToken.WaitTimeout(1 * time.Second) if connectToken.Error() != nil { panic(connectToken.Error()) } client.Subscribe("db/reply/#", 1, func(_ paho.Client, msg paho.Message) { defer wg.Done() buff := msg.Payload() str := string(buff) fmt.Println("RECV", msg.Topic(), " :", str) }) // check table existence jsonStr := `{ "q": "select count(*) from M$SYS_TABLES where name = 'TAGDATA'" }` wg.Add(1) client.Publish("db/query", 1, false, []byte(jsonStr)) wg.Wait() // create table jsonStr = `{ "q": "create tag table if not exists TAGDATA (name varchar(200) primary key, time datetime basetime, value double summarized, jstr varchar(80))" }` wg.Add(1) client.Publish("db/query", 1, false, []byte(jsonStr)) wg.Wait() // insert jsonStr = `{ "reply": "db/reply", "data": { "columns":["name", "time", "value"], "rows": [ [ "my-car", 1670380342000000000, 32.1 ], [ "my-car", 1670380343000000000, 65.4 ], [ "my-car", 1670380344000000000, 76.5 ] ] } }` // it is also possible to specify table in the topic like `db/write/TAGDATA`, // if both (topic and payload) ways used in a time, table name of payload will be taken by server wg.Add(1) client.Publish("db/write/TAGDATA", 1, false, []byte(jsonStr)) wg.Wait() // append for i := 0; i < 100; i++ { // both forms are available // 1) append a single record: `[ columns... ]` // 2) append multiple records: `[ [columns...], [columns...] ]` jsonStr = fmt.Sprintf(`[ "my-car", %d, %.1f, "{\"speed\":\"%.1fkmh\",\"lat\":37.38906,\"lon\":127.12182}" ]`, time.Now().UnixNano(), float32(80+i), float32(80+i)) client.Publish("db/append/TAGDATA", 1, false, []byte(jsonStr)) } // select jsonStr = `{ "q":"select count(*) from TAGDATA" }` wg.Add(1) client.Publish("db/query", 1, false, []byte(jsonStr)) wg.Wait() client.Unsubscribe("db/reply/#") // disconnect mqtt connection client.Disconnect(100) } ``` -------------------------------- ### CREATE TABLE examples Source: https://docs.machbase.com/dbms/reference/sql/syntax/ddl-syntax Examples of creating LOG, TAG, LOOKUP, VOLATILE, and TRANSACTION tables, including metadata, properties, IF NOT EXISTS, and NOT NULL constraints. ```sql -- Create a LOG table with the explicit LOG keyword. CREATE LOG TABLE sensor_log ( id INTEGER, name VARCHAR(64), value DOUBLE, status VARCHAR(20) ); -- Create a TAG table: BASETIME required; SUMMARIZED marks the ROLLUP column. CREATE TAG TABLE tag ( name VARCHAR(40) PRIMARY KEY, time DATETIME BASETIME, value DOUBLE SUMMARIZED ); -- TAG table with metadata and properties CREATE TAG TABLE sensors ( name VARCHAR(40) PRIMARY KEY, time DATETIME BASETIME, value DOUBLE SUMMARIZED ) METADATA ( location VARCHAR(100), unit VARCHAR(20) ) TAG_PARTITION_COUNT = 4; -- LOOKUP table (PRIMARY KEY required) CREATE LOOKUP TABLE devices ( device_id VARCHAR(40) PRIMARY KEY, ip IPV4, status VARCHAR(20) ); -- VOLATILE table CREATE VOLATILE TABLE cache_data ( id INTEGER PRIMARY KEY, value DOUBLE ); -- Exact fixed-point columns in a TRANSACTION table CREATE TRANSACTION TABLE invoice ( id LONG PRIMARY KEY, amount DECIMAL(18,2), tax NUMERIC(18,4) ); -- Use IF NOT EXISTS CREATE TAG TABLE IF NOT EXISTS tag ( name VARCHAR(40) PRIMARY KEY, time DATETIME BASETIME, value DOUBLE SUMMARIZED ); -- NOT NULL constraint CREATE TABLE t1 ( c1 INTEGER NOT NULL, c2 VARCHAR(200) ); ``` -------------------------------- ### GET /web/api/pkgs/insall/:name Source: https://docs.machbase.com/neo/api-http/ui-api Installs a package by name. ```APIDOC ## GET /web/api/pkgs/insall/:name ### Description Install package ### Method GET ### Endpoint /web/api/pkgs/insall/:name ### Parameters #### Path Parameters - **name** (string) - Required - Install package name ### Response #### Success Response (200) - **success** (boolean) - Success flag - **reason** (string) - Reason - **data** (object) - Optional, omitted if empty - **log** (string) - Log message - **elapse** (string) - Elapsed time #### Response Example { "success": true, "reason": "success", "data":{}, // omitempty "log":"", "elapse": "23.1491ms" } ``` -------------------------------- ### servicectl controller usage examples Source: https://docs.machbase.com/neo/jsh/commands Usage examples for servicectl controller. Shows metrics, resets counters, and gets metrics (alias). ```sh servicectl controller metrics servicectl controller reset servicectl controller get ``` -------------------------------- ### start() syntax Source: https://docs.machbase.com/neo/jsh/modules/service Syntax for client.start(name, callback). Starts a service and returns the updated service snapshot. ```javascript client.start(name, callback) ``` -------------------------------- ### CLI example for toTUILines() Source: https://docs.machbase.com/neo/jsh/modules/vizspec CLI example for toTUILines(). Invokes the 'viz lines' command with height 5, series series-1, and input file sample.json. ```sh viz lines --height 5 --series series-1 sample.json ``` -------------------------------- ### Create LOG table, add indexes, and compare EXPLAIN plans Source: https://docs.machbase.com/dbms/log-table-usage/index-performance Creates a LOG table with sample rows, adds LSM, KEYWORD, and BITMAP indexes, flushes table and index, then runs EXPLAIN and SEARCH queries plus SHOW INDEXES to compare access paths before and after index creation. The search returns rows 2 and 3; these rows illustrate behavior, not performance. ```sql CREATE LOG TABLE ch7_index ( event_id INTEGER, event_time DATETIME, severity SHORT, message VARCHAR(256) ); INSERT INTO ch7_index VALUES ( 1, TO_DATE('2026-01-01 10:00:00', 'YYYY-MM-DD HH24:MI:SS'), 1, 'service started'); INSERT INTO ch7_index VALUES ( 2, TO_DATE('2026-01-01 10:01:00', 'YYYY-MM-DD HH24:MI:SS'), 3, 'database timeout'); INSERT INTO ch7_index VALUES ( 3, TO_DATE('2026-01-01 10:02:00', 'YYYY-MM-DD HH24:MI:SS'), 3, 'connection timeout'); EXPLAIN SELECT event_id FROM ch7_index WHERE severity = 3; CREATE INDEX ch7_index_time ON ch7_index(event_time) INDEX_TYPE LSM; CREATE INDEX ch7_index_message ON ch7_index(message) INDEX_TYPE KEYWORD; CREATE INDEX ch7_index_severity ON ch7_index(severity) INDEX_TYPE BITMAP BITMAP_ENCODE = RANGE; EXEC TABLE_FLUSH(ch7_index); EXEC INDEX_FLUSH(ch7_index); EXPLAIN SELECT event_id FROM ch7_index WHERE severity = 3; EXPLAIN SELECT event_id FROM ch7_index WHERE message SEARCH 'timeout'; SELECT event_id FROM ch7_index WHERE message SEARCH 'timeout' ORDER BY event_id; SHOW INDEXES; ``` -------------------------------- ### Install from JSON file: servicectl install Source: https://docs.machbase.com/neo/jsh/services Syntax and usage example for installing a service from a JSON file. The file name is determined by the service 'name' field; if it contains "name": "alpha", the installed configuration is stored as /etc/services/alpha.json. ```sh servicectl install ``` ```sh /work > servicectl install svc.json ``` -------------------------------- ### Complete Go example with machgo package Source: https://docs.machbase.com/neo/tutorials/cli-go Complete Go example using the machgo package to connect to a Machbase database, create a tag table, insert sample data, and query it. Demonstrates the recommended workflow for Go developers, including configuration, connection with password, and error handling. ```go package main import ( "context" "fmt" "log" "time" "github.com/machbase/neo-server/v8/api" "github.com/machbase/neo-server/v8/api/machgo" ) func main() { // Configure database connection conf := &machgo.Config{ Host: "127.0.0.1", Port: 5656, MaxOpenConn: 10, MaxOpenQuery: 5, } db, err := machgo.NewDatabase(conf) if err != nil { panic(err) } ctx := context.Background() // Connect to database conn, err := db.Connect(ctx, api.WithPassword("sys", "manager")) if err != nil { log.Fatal(err) } defer conn.Close() // Create a sample table result := conn.Exec(ctx, ` CREATE TAG TABLE IF NOT EXISTS sample_data ( name VARCHAR(100) primary key, time DATETIME basetime, value DOUBLE ) `) if err := result.Err(); err != nil { log.Fatal(err) } // Insert sample data for i := 0; i < 5; i++ { result := conn.Exec(ctx, `INSERT INTO sample_data VALUES (?, ?, ?)`, fmt.Sprintf("sensor_%d", i), time.Now(), float64(i)*1.5) if err := result.Err(); err != nil { log.Fatal(err) } } // Query the data rows, err := conn.Query(ctx, `SELECT name, time, value FROM sample_data ORDER BY time`) if err != nil { log.Fatal(err) } defer rows.Close() fmt.Println("Retrieved data:") for rows.Next() { var name string var tm time.Time var value float64 if err := rows.Scan(&name, &tm, &value); err != nil { log.Fatal(err) } tm = tm.Local() fmt.Printf("Name: %s, Time: %s, Value: %.2f\n", name, tm.Format(time.RFC3339), value) } } ```