### START XNODE TASK example Source: https://docs.taosdata.com/tdengine-sql/cluster-management/xnode Example of starting task with id 1. ```sql START XNODE TASK 1; ``` -------------------------------- ### Java: Native connection setup and subscription workflow Source: https://docs.taosdata.com/developer-guide/subscription-api Sets connection properties (locale, charset), creates a connection and statement, then runs subscription examples (poll, seek, commit, unsubscribe) in a single-thread executor. Includes error handling for connection and statement creation, and closes resources at the end. ```java properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "C"); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); try { connection = DriverManager.getConnection(url, properties); } catch (SQLException ex) { System.out.println("Failed to create connection, url:" + url + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); throw new SQLException("Failed to create connection", ex); } try { statement = connection.createStatement(); } catch (SQLException ex) { System.out.println("Failed to create statement, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); throw new SQLException("Failed to create statement", ex); } System.out.println("Connection created successfully."); } public static void closeConnection() throws SQLException { try { if (statement != null) { statement.close(); } } catch (SQLException ex) { System.out.println("Failed to close statement, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); throw new SQLException("Failed to close statement", ex); } try { if (connection != null) { connection.close(); } } catch (SQLException ex) { System.out.println("Failed to close connection, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); throw new SQLException("Failed to close connection", ex); } System.out.println("Connection closed Successfully."); } public static void main(String[] args) throws SQLException, InterruptedException { initConnection(); prepareMeta(); // create a single thread executor ExecutorService executor = Executors.newSingleThreadExecutor(); // submit a task executor.submit(() -> { try { prepareData(); } catch (SQLException ex) { System.out.println("Failed to prepare data, ErrCode:" + ex.getErrorCode() + ", ErrMessage: " + ex.getMessage()); return; } catch (Exception ex) { System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage()); return; } System.out.println("pollDataExample executed successfully."); }); try { TaosConsumer consumer = getConsumer(); pollExample(consumer); System.out.println("pollExample executed successfully."); consumer.unsubscribe(); seekExample(consumer); System.out.println("seekExample executed successfully."); consumer.unsubscribe(); commitExample(consumer); System.out.println("commitExample executed successfully."); consumer.unsubscribe(); unsubscribeExample(consumer); System.out.println("unsubscribeExample executed successfully"); } catch (SQLException ex) { System.out.println("Failed to poll data from topic_meters, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); return; } catch (Exception ex) { System.out.println("Failed to poll data from topic_meters, ErrMessage: " + ex.getMessage()); return; } stopThread = true; // close the executor, which will make the executor reject new tasks executor.shutdown(); try { // wait for the executor to terminate boolean result = executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); assert result; } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { e.printStackTrace(); System.out.println("Wait executor termination failed."); } closeConnection(); System.out.println("program end."); } } ``` -------------------------------- ### Start StatsD Source: https://docs.taosdata.com/operations-and-tooling/components/taosadapter Install dependencies and start StatsD with the modified configuration file (config.js). ```bash npm install node stats.js config.js & ``` -------------------------------- ### Create database and table and insert data Source: https://docs.taosdata.com/developer-guide/stmt Creates a database 'power', uses it, creates a stable table 'meters' with tags, and inserts data. This is part of the setup for the parameter binding example. ```java // create database and table executeSQL(taos, "CREATE DATABASE IF NOT EXISTS power"); executeSQL(taos, "USE power"); executeSQL(taos, "CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS " "(groupId INT, location BINARY(24))"); insertData(taos); taos_close(taos); taos_cleanup(); } ``` -------------------------------- ### Go: Consumer operations and environment setup Source: https://docs.taosdata.com/developer-guide/subscription-api This snippet shows a Go consumer workflow including committing offsets, handling errors, getting assignments, seeking to the beginning, unsubscribing, and closing the consumer. It also includes an initEnv function that creates a database, stable, topic, and inserts sample data. ```go _, err = consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition}) if err != nil { log.Fatalf( "Failed to commit offset, topic: %s, groupId: %s, clientId: %s, offset %s, ErrMessage: %s\n", topic, groupID, clientID, e.TopicPartition, err.Error(), ) } log.Println("Commit offset manually successfully.") case tmqcommon.Error: log.Fatalf( "Failed to poll data, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", topic, groupID, clientID, e.Error(), ) } } } // get assignment partitions, err := consumer.Assignment() if err != nil { log.Fatalf( "Failed to get assignment, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", topic, groupID, clientID, err.Error(), ) } fmt.Println("Now assignment:", partitions) for i := 0; i < len(partitions); i++ { // seek to the beginning err = consumer.Seek(tmqcommon.TopicPartition{ Topic: partitions[i].Topic, Partition: partitions[i].Partition, Offset: 0, }, 0) if err != nil { log.Fatalf( "Failed to seek offset, topic: %s, groupId: %s, clientId: %s, partition: %d, offset: %d, ErrMessage: %s\n", topic, groupID, clientID, partitions[i].Partition, 0, err.Error(), ) } } fmt.Println("Assignment seek to beginning successfully") // unsubscribe err = consumer.Unsubscribe() if err != nil { log.Fatalf( "Failed to unsubscribe consumer, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", topic, groupID, clientID, err.Error(), ) } fmt.Println("Consumer unsubscribed successfully.") // close consumer err = consumer.Close() if err != nil { log.Fatalf( "Failed to close consumer, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", topic, groupID, clientID, err.Error(), ) } fmt.Println("Consumer closed successfully.") <-done } func initEnv(conn *sql.DB) { _, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power") if err != nil { log.Fatal("Failed to create database, ErrMessage: " + err.Error()) } _, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") if err != nil { log.Fatal("Failed to create stable, ErrMessage: " + err.Error()) } _, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters") if err != nil { log.Fatal("Failed to create topic, ErrMessage: " + err.Error()) } go func() { for i := 0; i < 10; i++ { time.Sleep(time.Second) _, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)") if err != nil { log.Fatal("Failed to insert data, ErrMessage: " + err.Error()) } } done <- struct{}{} }() } ``` -------------------------------- ### Multi-level storage configuration example Source: https://docs.taosdata.com/operations-and-tooling/operations/multi Example configuration with three levels and multiple mount points. Level 0 has one primary and one secondary mount point; levels 1 and 2 have two mount points each. This setup is valid because it includes all levels 0, 1, and 2. ```plaintext dataDir /mnt/data1 0 1 dataDir /mnt/data2 0 0 dataDir /mnt/data3 1 0 dataDir /mnt/data4 1 0 dataDir /mnt/data5 2 0 dataDir /mnt/data6 2 0 ``` -------------------------------- ### Show tokens example Source: https://docs.taosdata.com/tdengine-sql/user-and-privilege/user Example output of SHOW TOKENS, listing tokens with their attributes. ```sql taos> SHOW TOKENS; name | user | provider | enable | create_time | expire_time | extra_info | ========================================================================================================= root_token | root | | 1 | 2025-12-25 10:02:28.000 | 1970-01-01 08:00:00.000 | | test_token | test | | 1 | 2025-12-25 10:01:47.000 | 1970-01-01 08:00:00.000 | | Query OK, 2 row(s) in set (0.003313s) ``` -------------------------------- ### MD5 examples Source: https://docs.taosdata.com/tdengine-sql/data-query/function Example queries for MD5: selecting the checksum and inserting it into a table. ```sql taos> select md5('mytext')\G; *************************** 1.row *************************** md5('mytext'): 947ef8c8db156a568d5974d71f7638f4 Query OK, 1 row(s) in set (0.000522s) taos> insert into db.tb values(now, md5('mytext')); Insert OK, 1 row(s) affected (0.005111s) ``` -------------------------------- ### 进入项目目录并编辑工程文件 Source: https://docs.taosdata.com/cloud/programming/connect/csharp 进入 example 目录并使用 vim 编辑 example.csproj 文件,以便添加 TDengine.Connector 包引用和构建任务。 ```bash cd example vim example.csproj ``` -------------------------------- ### Go: Native consumer subscription lifecycle Source: https://docs.taosdata.com/developer-guide/subscription-api This example shows how to create a native consumer, subscribe to a topic, poll for data messages, commit offsets manually, seek to the beginning of partitions, unsubscribe, and close the consumer. It also initializes the environment by creating a database, stable, and topic. The consumer uses auto-commit enabled with a 1-second interval, but manual commit is performed after each data message. ```go package main import ( "database/sql" "fmt" "log" "time" "github.com/taosdata/driver-go/v3/af/tmq" tmqcommon "github.com/taosdata/driver-go/v3/common/tmq" _ "github.com/taosdata/driver-go/v3/taosSql" ) var done = make(chan struct{}) var groupID string var clientID string var host string var topic string func main() { // init env taosDSN := "root:taosdata@tcp(127.0.0.1:6030)/" conn, err := sql.Open("taosSql", taosDSN) if err != nil { log.Fatalln("Failed to connect to " + taosDSN + ", ErrMessage: " + err.Error()) } defer func() { conn.Close() }() initEnv(conn) // create consumer groupID = "group1" clientID = "client1" host = "127.0.0.1" consumer, err := tmq.NewConsumer(&tmqcommon.ConfigMap{ "td.connect.user": "root", "td.connect.pass": "taosdata", "auto.offset.reset": "latest", "msg.with.table.name": "true", "enable.auto.commit": "true", "auto.commit.interval.ms": "1000", "group.id": groupID, "client.id": clientID, }) if err != nil { log.Fatalf( "Failed to create native consumer, host: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", host, groupID, clientID, err.Error(), ) } log.Printf("Create consumer successfully, host: %s, groupId: %s, clientId: %s\n", host, groupID, clientID) topic = "topic_meters" err = consumer.Subscribe(topic, nil) if err != nil { log.Fatalf( "Failed to subscribe topic_meters, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", topic, groupID, clientID, err.Error(), ) } log.Println("Subscribe topics successfully") for i := 0; i < 50; i++ { ev := consumer.Poll(100) if ev != nil { switch e := ev.(type) { case *tmqcommon.DataMessage: // process your data here fmt.Printf("data:%v\n", e) // commit offset _, err = consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition}) if err != nil { log.Fatalf( "Failed to commit offset, topic: %s, groupId: %s, clientId: %s, offset %s, ErrMessage: %s\n", topic, groupID, clientID, e.TopicPartition, err.Error(), ) } log.Println("Commit offset manually successfully.") case tmqcommon.Error: log.Fatalf("Failed to poll data, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", topic, groupID, clientID, e.Error()) } } } // get assignment partitions, err := consumer.Assignment() if err != nil { log.Fatalf("Failed to get assignment, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", topic, groupID, clientID, err.Error()) } fmt.Println("Now assignment:", partitions) for i := 0; i < len(partitions); i++ { // seek to the beginning err = consumer.Seek(tmqcommon.TopicPartition{ Topic: partitions[i].Topic, Partition: partitions[i].Partition, Offset: 0, }, 0) if err != nil { log.Fatalf( "Failed to execute seek offset, topic: %s, groupId: %s, clientId: %s, partition: %d, offset: %d, ErrMessage: %s\n", topic, groupID, clientID, partitions[i].Partition, 0, err.Error(), ) } } fmt.Println("Assignment seek to beginning successfully") // unsubscribe err = consumer.Unsubscribe() if err != nil { log.Fatalf( "Failed to unsubscribe consumer, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", topic, groupID, clientID, err.Error(), ) } fmt.Println("Consumer unsubscribed successfully.") // close consumer err = consumer.Close() if err != nil { log.Fatalf( "Failed to close consumer, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", topic, groupID, clientID, err.Error(), ) } fmt.Println("Consumer closed successfully.") <-done } func initEnv(conn *sql.DB) { _, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power") if err != nil { log.Fatal("Failed to create database, ErrMessage: " + err.Error()) } _, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") if err != nil { log.Fatal("Failed to create stable, ErrMessage: " + err.Error()) } _, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters") if err != nil { log.Fatal("Failed to create topic, ErrMessage: " + err.Error()) } go func() { for i := 0; i < 10; i++ { time.Sleep(time.Second) ``` -------------------------------- ### Time input format example Source: https://docs.taosdata.com/cloud/tools/gds Example of the time input format for the connector's start and end time fields. The format is "YYYY-MM-DD HH:MM:SS". ```text 2022-05-12 18:24:15 ``` -------------------------------- ### GET /record_sql status response Source: https://docs.taosdata.com/operations-and-tooling/components/taosadapter Example response from GET /record_sql. Fields include code, desc, exists, running, start_time, end_time, and current_concurrent. Times are in the taosAdapter server timezone. ```json { "code": 0, "desc": "", "exists": true, "running": true, "start_time": "2025-07-16 17:00:00", "end_time": "2025-07-16 18:00:00", "current_concurrent": 100 } ``` -------------------------------- ### Main entry point (init_env, pthread_create) Source: https://docs.taosdata.com/developer-guide/subscription-api Initializes the environment, creates a thread, and likely starts the consumer. The snippet is incomplete as it ends abruptly. ```c int main(int argc, char* argv[]) { int32_t code; pthread_t thread_id; TAOS* pConn = init_env(); if (pConn == NULL) { ``` -------------------------------- ### Get REST connection with Properties Source: https://docs.taosdata.com/cloud/programming/client-libraries/java Get a REST connection using a Properties object to set client parameters. Client parameters are process-level and only take effect on the first set; this example is based on taos-jdbcdriver-3.0.0. ```java public Connection getRestConn() throws Exception{ Class.forName("com.taosdata.jdbc.rs.RestfulDriver"); String jdbcUrl = System.getenv("TDENGINE_JDBC_URL"); Properties connProps = new Properties(); connProps.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); Connection conn = DriverManager.getConnection(jdbcUrl, connProps); return conn; } ``` -------------------------------- ### Go connector: create database, stable, and insert Source: https://docs.taosdata.com/cloud/programming/insert Go example using taos.Exec to drop and create the database, create the meters stable, and insert multiple rows. Includes error handling for each step and prints the number of affected rows. Expects 'RowsAffected 4'. ```go _, err = taos.Exec("DROP DATABASE IF EXISTS power") if err != nil { fmt.Println("failed to drop database, err:", err) return } _, err = taos.Exec("CREATE DATABASE power") if err != nil { fmt.Println("failed to create database, err:", err) return } _, err = taos.Exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)") if err != nil { fmt.Println("failed to create stable, err:", err) return } result, err := taos.Exec("INSERT INTO power.d1001 USING power.meters TAGS(California.SanFrancisco, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) power.d1002 USING power.meters TAGS(California.SanFrancisco, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)") if err != nil { fmt.Println("failed to insert, err:", err) return } rowsAffected, err := result.RowsAffected() if err != nil { fmt.Println("failed to get affected rows, err:", err) return } fmt.Println("RowsAffected", rowsAffected) // RowsAffected 4 ``` -------------------------------- ### Java WebSocket Consumer Full Example Source: https://docs.taosdata.com/developer-guide/subscription-api Complete Java example for WebSocket consumer using TaosConsumer. It shows configuration setup, creating a consumer, polling data, and seeking to the beginning. Includes error handling with SQLException details. ```Java public class WsConsumerLoopFull { static private Connection connection; static private Statement statement; static private volatile boolean stopThread = false; static private String groupId = "group1"; static private String clientId = "client1"; public static TaosConsumer getConsumer() throws Exception { Properties config = new Properties(); config.setProperty("td.connect.type", "ws"); config.setProperty("bootstrap.servers", "localhost:6041"); config.setProperty("auto.offset.reset", "latest"); config.setProperty("msg.with.table.name", "true"); config.setProperty("enable.auto.commit", "true"); config.setProperty("auto.commit.interval.ms", "1000"); config.setProperty("group.id", "group1"); config.setProperty("client.id", "client1"); config.setProperty("td.connect.user", "root"); config.setProperty("td.connect.pass", "taosdata"); config.setProperty("value.deserializer", "com.taos.example.WsConsumerLoopFull$ResultDeserializer"); config.setProperty("value.deserializer.encoding", "UTF-8"); try { TaosConsumer consumer= new TaosConsumer<>(config); System.out.printf("Create consumer successfully, host: %s, groupId: %s, clientId: %s%n", config.getProperty("bootstrap.servers"), config.getProperty("group.id"), config.getProperty("client.id")); return consumer; } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info System.out.printf("Failed to create websocket consumer, host: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", config.getProperty("bootstrap.servers"), config.getProperty("group.id"), config.getProperty("client.id"), ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. ex.printStackTrace(); throw ex; } } public static void pollExample(TaosConsumer consumer) throws SQLException, JsonProcessingException { List topics = Collections.singletonList("topic_meters"); try { // subscribe to the topics consumer.subscribe(topics); System.out.println("Subscribe topics successfully."); for (int i = 0; i < 50; i++) { // poll data ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord record : records) { ResultBean bean = record.value(); // Add your data processing logic here System.out.println("data: " + JsonUtil.getObjectMapper().writeValueAsString(bean)); } } } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info System.out.printf("Failed to poll data, topic: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", topics.get(0), groupId, clientId, ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. ex.printStackTrace(); throw ex; } } public static void seekExample(TaosConsumer consumer) throws SQLException, JsonProcessingException { List topics = Collections.singletonList("topic_meters"); try { // subscribe to the topics consumer.subscribe(topics); System.out.println("Subscribe topics successfully."); Set assignment = consumer.assignment(); System.out.println("Now assignment: " + JsonUtil.getObjectMapper().writeValueAsString(assignment)); ConsumerRecords records = ConsumerRecords.emptyRecord(); // make sure we have got some data while (records.isEmpty()) { records = consumer.poll(Duration.ofMillis(100)); } consumer.seekToBeginning(assignment); System.out.println("Assignment seek to beginning successfully."); } catch (Exception ex) { ``` -------------------------------- ### Manage all TDengine services with start-all.bat Source: https://docs.taosdata.com/operations-and-tooling/operations/install Starts, checks status, or stops all TDengine services on Windows. Run from the installation directory in an administrator cmd window. Use start-all.bat -S to start services without connectivity checks and Snode/Xnode initialization. ```batch start-all.bat start-all.bat status start-all.bat stop ``` -------------------------------- ### 创建 .NET 控制台项目 Source: https://docs.taosdata.com/cloud/programming/connect/csharp 使用 dotnet CLI 创建新的控制台项目,项目名为 example。 ```bash dotnet new console -o example ``` -------------------------------- ### Get Seeq data storage location Source: https://docs.taosdata.com/ecosystem-integrations/bi/seeq Run this command to view the data storage folder, which is needed to install the JDBC driver. ```bash sudo seeq config get Folders/Data ``` -------------------------------- ### Parquet full configuration example Source: https://docs.taosdata.com/operations-and-tooling/components/taosx Command to import data from a Parquet file with all parameters configured: batch size, projection, and unprocessed batches. ```bash taosx run -f 'parquet:/data/sensors.parquet?batch_size=2000&projection=ts,device_id,temperature&unprocessed_batches=100' \ -t taos:///iot_db -v ``` -------------------------------- ### Run Grafana container with TDengine plugin Source: https://docs.taosdata.com/third-party/visual/grafana Starts a Grafana container and automatically installs the TDengine plugin via the GF_INSTALL_PLUGINS environment variable. ```bash docker run -d \ -p 3000:3000 \ --name=grafana \ -e "GF_INSTALL_PLUGINS=https://downloads.taosdata.com/tdengine-tsdb-datasource/tdengine-datasource.zip;tdengine-datasource" \ grafana/grafana ``` -------------------------------- ### Create user example Source: https://docs.taosdata.com/tdengine-sql/user-and-privilege/user Example creating a user named test with password abc123!@# and SYSINFO privilege. Shows the expected output. ```sql taos> CREATE USER test PASS 'abc123!@#' SYSINFO 1; Query OK, 0 of 0 rows affected (0.001254s) ``` -------------------------------- ### Initialize Go module Source: https://docs.taosdata.com/cloud/programming/connect/go Initializes a new Go module for the example project. Run this command in your terminal before adding dependencies. ```bash go mod init tdengine.com/example ``` -------------------------------- ### Java connector: create database, stable, and insert Source: https://docs.taosdata.com/cloud/programming/insert Java example using 'stmt.execute' to drop and create the 'power' database, create the meters stable, and insert multiple rows into two subtables. Tags are provided without quotes. The example expects 4 affected rows. ```java stmt.execute("DROP DATABASE IF EXISTS power"); stmt.execute("CREATE DATABASE power"); stmt.execute("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"); stmt.execute("INSERT INTO power.d1001 USING power.meters TAGS(California.SanFrancisco, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) power.d1002 USING power.meters TAGS(California.SanFrancisco, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)"); ``` -------------------------------- ### Configure StatsD repeater Source: https://docs.taosdata.com/operations-and-tooling/components/taosadapter Configure StatsD's exampleConfig.js to forward metrics to taosAdapter. The first block shows the required additions; the second is a concrete example configuration. After saving as config.js, run 'npm install' and 'node stats.js config.js &'. ```javascript backends 部分添加 "./backends/repeater" repeater 部分添加 { host:'', port: } ``` ```javascript { port: 8125 , backends: ["./backends/repeater"] , repeater: [{ host: '127.0.0.1', port: 6044}] } ``` -------------------------------- ### Initialize environment and create database and super table Source: https://docs.taosdata.com/developer-guide/subscription-api Connects to TDengine, drops existing topic and database, creates a database with precision 'ms' and WAL retention, and creates a super table 'meters' with tags. Returns the connection handle or NULL on failure. ```c TAOS* init_env() { const char* host = "localhost"; const char* user = "root"; const char* password = "taosdata"; uint16_t port = 6030; int code = 0; TAOS* pConn = taos_connect(host, user, password, NULL, port); if (pConn == NULL) { fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); taos_cleanup(); return NULL; } TAOS_RES* pRes; // drop database if exists pRes = taos_query(pConn, "DROP TOPIC IF EXISTS topic_meters"); code = taos_errno(pRes); if (code != 0) { fprintf(stderr, "Failed to drop topic_meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); goto END; } taos_free_result(pRes); pRes = taos_query(pConn, "DROP DATABASE IF EXISTS power"); code = taos_errno(pRes); if (code != 0) { fprintf(stderr, "Failed to drop database power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); goto END; } taos_free_result(pRes); // create database pRes = taos_query(pConn, "CREATE DATABASE power PRECISION 'ms' WAL_RETENTION_PERIOD 3600"); code = taos_errno(pRes); if (code != 0) { fprintf(stderr, "Failed to create power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); goto END; } taos_free_result(pRes); // create super table pRes = taos_query( pConn, "CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS " "(groupId INT, location BINARY(24))"); code = taos_errno(pRes); if (code != 0) { fprintf(stderr, "Failed to create super table meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); goto END; } taos_free_result(pRes); return pConn; END: taos_free_result(pRes); taos_close(pConn); return NULL; } void deinit_env(TAOS* pConn) { if (pConn) taos_close(pConn); } ``` -------------------------------- ### Query TDengine via taos shell and show dnodes Source: https://docs.taosdata.com/operations-and-tooling/operations/deployment/docker After starting TDengine in host network mode, use the taos shell to verify the service. This example shows connecting to the shell and running 'show dnodes' to display node information. ```bash $ taos taos> show dnodes; id | endpoint | vnodes | support_vnodes | status | create_time | note | ================================================================================================================================================= 1 | vm98:6030 | 0 | 32 | ready | 2022-08-19 14:50:05.337 | | Query OK, 1 rows in database (0.010654s) ``` -------------------------------- ### SQL query with time range filter Source: https://docs.taosdata.com/cloud/tools/gds SQL query example showing how the start and end time conditions are applied using a WHERE clause. The commented line shows the general pattern, and the actual query filters data from the test.demo table between the specified timestamps. ```sql -- select * from table_name where ts >= start_date and ts <= end_date select * from test.demo where ts >= '2022-05-10 18:24:15' and ts<='2022-05-12 18:24:15' ``` -------------------------------- ### Query data with JDBC (Java) Source: https://docs.taosdata.com/developer-guide/execute-sql Uses JDBC to execute a SELECT query on power.meters and prints each row. Column indexes start at 1; the example recommends using column names for clarity. The catch block prints error code and message, then rethrows the exception. ```java String sql = "SELECT ts, current, location FROM power.meters limit 100"; try (Connection connection = DriverManager.getConnection(jdbcUrl, properties); Statement stmt = connection.createStatement(); // query data, make sure the database and table are created before ResultSet resultSet = stmt.executeQuery(sql)) { Timestamp ts; float current; String location; while (resultSet.next()) { // we recommend using the column index to get the value for better performance ts = resultSet.getTimestamp(1); current = resultSet.getFloat(2); // you can also use the column name to get the value location = resultSet.getString("location"); // you can check data here System.out.printf("ts: %s, current: %f, location: %s %n", ts, current, location); } } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info System.out.printf("Failed to query data from power.meters, sql: %s, %sErrMessage: %s%n", sql, ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. ex.printStackTrace(); throw ex; } ``` -------------------------------- ### Command-line arguments for FastWriteExample Source: https://docs.taosdata.com/developer-guide/high-throughput Lists the command-line options for the FastWriteExample program, including batch size, cache size, database name, Kafka usage, thread counts, and more. Defaults are provided for each option. ```text -b,--batchSizeByRow 指定高效写入的 batchSizeByRow 参数,默认 1000 -c,--cacheSizeByRow 指定高效写入的 cacheSizeByRow 参数,默认 10000 -d,--dbName 指定数据库名, 默认 `test` --help 打印帮助信息 -K,--useKafka 使用 Kafka,采用创建生产者发送消息,消费者接收消息写入 TDengine 方式。否则采用工作线程订阅模拟器生成数据写入 TDengine 方式 -r,--readThreadCount 指定工作线程数,默认 5,当 Kafka 模式,此参数同时决定生产者和消费者线程数 -R,--rowsPerSubTable 指定每子表写入行数,默认 100 -s,--subTableNum 指定子表总数,默认 1000000 -w,--writeThreadPerReadThread 指定每工作线程对应写入线程数,默认 5 ``` -------------------------------- ### FastWriteExample main program Source: https://docs.taosdata.com/developer-guide/high-throughput The main program class for the high-throughput example. It parses command-line arguments, creates sub-tables, starts worker threads or Kafka producer/consumer, monitors write speed, and waits for completion. It uses a thread pool for sub-table creation and manages shutdown. ```java package com.taos.example.highvolume; import org.apache.commons.cli.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicInteger; public class FastWriteExample { static final Logger logger = LoggerFactory.getLogger(FastWriteExample.class); static ThreadPoolExecutor writerThreads; static ThreadPoolExecutor producerThreads; static final ThreadPoolExecutor statThread = (ThreadPoolExecutor) Executors.newFixedThreadPool(1); private static final List allTasks = new ArrayList<>(); private static int readThreadCount = 5; private static int writeThreadPerReadThread = 5; private static int batchSizeByRow = 1000; private static int cacheSizeByRow = 10000; private static int subTableNum = 1000000; private static int rowsPerSubTable = 100; private static String dbName = "test"; public static void forceStopAll() { logger.info("shutting down"); for (Stoppable task : allTasks) { task.stop(); } if (producerThreads != null) { producerThreads.shutdown(); } if (writerThreads != null) { writerThreads.shutdown(); } statThread.shutdown(); } private static void createSubTables(){ writerThreads = (ThreadPoolExecutor) Executors.newFixedThreadPool(readThreadCount, getNamedThreadFactory("FW-CreateSubTable-thread-")); int range = (subTableNum + readThreadCount - 1) / readThreadCount; for (int i = 0; i < readThreadCount; i++) { int startIndex = i * range; int endIndex; if (i == readThreadCount - 1) { endIndex = subTableNum - 1; } else { endIndex = startIndex + range - 1; } logger.debug("create sub table task {} {} {}", i, startIndex, endIndex); CreateSubTableTask createSubTableTask = new CreateSubTableTask(i, startIndex, endIndex, dbName); writerThreads.submit(createSubTableTask); } logger.info("create sub table task started."); while (writerThreads.getActiveCount() != 0) { try { Thread.sleep(1); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } } } } ``` -------------------------------- ### 解压后脚本目录结构 Source: https://docs.taosdata.com/operations-and-tooling/components/license-center/deploy-and-activate 解压安装包后可见的部署相关脚本目录结构,包含 install.sh、start.sh、status.sh、stop.sh、uninstall.sh。 ```text scripts/ ├── install.sh ├── start.sh ├── status.sh ├── stop.sh └── uninstall.sh ``` -------------------------------- ### TDgpt forecast SQL example Source: https://docs.taosdata.com/cloud/dbmarts Run this SQL in the data browser of the public database '时序数据预测分析数据集' to try TDgpt's forecasting feature. It selects the forecasted values for the electricity_demand_sub table using the tdtsfm_1 algorithm, starting at timestamp 1324915200000 and generating 300 rows. ```sql select _FROWTS, forecast(val, 'algo=tdtsfm_1,start=1324915200000,rows=300') from forecast.electricity_demand_sub; ``` -------------------------------- ### Full taosRestful connection example Source: https://docs.taosdata.com/cloud/programming/client-libraries/go Complete example using the taosRestful driver to connect, create database/table, insert data, and query. Note that REST is stateless, so the database name must be included in the DSN or SQL statements; otherwise error [0x217] Database not specified or available occurs. ```go package main import ( "database/sql" "fmt" "time" _ "github.com/taosdata/driver-go/v3/taosRestful" ) func main() { var taosDSN = "root:taosdata@http(localhost:6041)/test" taos, err := sql.Open("taosRestful", taosDSN) if err != nil { fmt.Println("failed to connect TDengine, err:", err) return } defer taos.Close() taos.Exec("create database if not exists test") taos.Exec("create table if not exists tb1 (ts timestamp, a int)") _, err = taos.Exec("insert into tb1 values(now, 0)(now+1s,1)(now+2s,2)(now+3s,3)") if err != nil { fmt.Println("failed to insert, err:", err) return } rows, err := taos.Query("select * from tb1") if err != nil { fmt.Println("failed to select from table, err:", err) return } defer rows.Close() for rows.Next() { var r struct { ts time.Time a int } err := rows.Scan(&r.ts, &r.a) if err != nil { fmt.Println("scan error:\n", err) return } fmt.Println(r.ts, r.a) } } ``` -------------------------------- ### Install promql-cli Source: https://docs.taosdata.com/ecosystem-integrations/collection/prometheus Install the promql-cli tool using go install to query Prometheus data via remote_read. ```shell go install github.com/nalbury/promql-cli@latest ```