OpenTSDB JSON 格式协议

协议介绍

OpenTSDB JSON 格式协议采用一个 JSON 字符串表示一行或多行数据。例如:

  1. [
  2. {
  3. "metric": "sys.cpu.nice",
  4. "timestamp": 1346846400,
  5. "value": 18,
  6. "tags": {
  7. "host": "web01",
  8. "dc": "lga"
  9. }
  10. },
  11. {
  12. "metric": "sys.cpu.nice",
  13. "timestamp": 1346846400,
  14. "value": 9,
  15. "tags": {
  16. "host": "web02",
  17. "dc": "lga"
  18. }
  19. }
  20. ]

与 OpenTSDB 行协议类似, metric 将作为超级表名, timestamp 表示时间戳,value 表示度量值, tags 表示标签集。

参考OpenTSDB HTTP API 文档

OpenTSDB JSON 格式协议 - 图1note
  • 对于 JSON 格式协议,TDengine 并不会自动把所有标签转成 NCHAR 类型, 字符串将将转为 NCHAR 类型, 数值将同样转换为 DOUBLE 类型。
  • 默认生成的子表名是根据规则生成的唯一 ID 值。用户也可以通过在 taos.cfg 里配置 smlChildTableName 参数来指定某个标签值作为子表名。该标签值应该具有全局唯一性。举例如下:假设有个标签名为tname, 配置 smlChildTableName=tname, 插入数据为 "tags": { "host": "web02","dc": "lga","tname":"cpu1"} 则创建的子表名为 cpu1。注意如果多行数据 tname 相同,但是后面的 tag_set 不同,则使用第一行自动建表时指定的 tag_set,其他的行会忽略)。

示例代码

  • Java
  • Python
  • Go
  • Node.js
  • C#
  • C
  1. package com.taos.example;
  2. import com.taosdata.jdbc.SchemalessWriter;
  3. import com.taosdata.jdbc.enums.SchemalessProtocolType;
  4. import com.taosdata.jdbc.enums.SchemalessTimestampType;
  5. import java.sql.Connection;
  6. import java.sql.DriverManager;
  7. import java.sql.SQLException;
  8. import java.sql.Statement;
  9. public class JSONProtocolExample {
  10. private static Connection getConnection() throws SQLException {
  11. String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
  12. return DriverManager.getConnection(jdbcUrl);
  13. }
  14. private static void createDatabase(Connection conn) throws SQLException {
  15. try (Statement stmt = conn.createStatement()) {
  16. stmt.execute("CREATE DATABASE IF NOT EXISTS test");
  17. stmt.execute("USE test");
  18. }
  19. }
  20. private static String getJSONData() {
  21. return "[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," +
  22. " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, \"value\": 219, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}, " +
  23. "{\"metric\": \"meters.current\", \"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," +
  24. " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}]";
  25. }
  26. public static void main(String[] args) throws SQLException {
  27. try (Connection conn = getConnection()) {
  28. createDatabase(conn);
  29. SchemalessWriter writer = new SchemalessWriter(conn);
  30. String jsonData = getJSONData();
  31. writer.write(jsonData, SchemalessProtocolType.JSON, SchemalessTimestampType.NOT_CONFIGURED);
  32. }
  33. }
  34. }

查看源码

  1. import json
  2. import taos
  3. from taos import SmlProtocol, SmlPrecision
  4. lines = [{"metric": "meters.current", "timestamp": 1648432611249, "value": 10.3, "tags": {"location": "California.SanFrancisco", "groupid": 2}},
  5. {"metric": "meters.voltage", "timestamp": 1648432611249, "value": 219,
  6. "tags": {"location": "California.LosAngeles", "groupid": 1}},
  7. {"metric": "meters.current", "timestamp": 1648432611250, "value": 12.6,
  8. "tags": {"location": "California.SanFrancisco", "groupid": 2}},
  9. {"metric": "meters.voltage", "timestamp": 1648432611250, "value": 221, "tags": {"location": "California.LosAngeles", "groupid": 1}}]
  10. def get_connection():
  11. return taos.connect()
  12. def create_database(conn):
  13. conn.execute("CREATE DATABASE test")
  14. conn.execute("USE test")
  15. def insert_lines(conn):
  16. global lines
  17. lines = json.dumps(lines)
  18. # note: the first parameter must be a list with only one element.
  19. affected_rows = conn.schemaless_insert(
  20. [lines], SmlProtocol.JSON_PROTOCOL, SmlPrecision.NOT_CONFIGURED)
  21. print(affected_rows) # 4
  22. if __name__ == '__main__':
  23. connection = get_connection()
  24. try:
  25. create_database(connection)
  26. insert_lines(connection)
  27. finally:
  28. connection.close()

查看源码

  1. package main
  2. import (
  3. "log"
  4. "github.com/taosdata/driver-go/v3/af"
  5. )
  6. func prepareDatabase(conn *af.Connector) {
  7. _, err := conn.Exec("CREATE DATABASE test")
  8. if err != nil {
  9. panic(err)
  10. }
  11. _, err = conn.Exec("USE test")
  12. if err != nil {
  13. panic(err)
  14. }
  15. }
  16. func main() {
  17. conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
  18. if err != nil {
  19. log.Fatalln("fail to connect, err:", err)
  20. }
  21. defer conn.Close()
  22. prepareDatabase(conn)
  23. payload := `[{"metric": "meters.current", "timestamp": 1648432611249, "value": 10.3, "tags": {"location": "California.SanFrancisco", "groupid": 2}},
  24. {"metric": "meters.voltage", "timestamp": 1648432611249, "value": 219, "tags": {"location": "California.LosAngeles", "groupid": 1}},
  25. {"metric": "meters.current", "timestamp": 1648432611250, "value": 12.6, "tags": {"location": "California.SanFrancisco", "groupid": 2}},
  26. {"metric": "meters.voltage", "timestamp": 1648432611250, "value": 221, "tags": {"location": "California.LosAngeles", "groupid": 1}}]`
  27. err = conn.OpenTSDBInsertJsonPayload(payload)
  28. if err != nil {
  29. log.Fatalln("insert error:", err)
  30. }
  31. }

查看源码

  1. const taos = require("@tdengine/client");
  2. const conn = taos.connect({
  3. host: "localhost",
  4. });
  5. const cursor = conn.cursor();
  6. function createDatabase() {
  7. cursor.execute("CREATE DATABASE test");
  8. cursor.execute("USE test");
  9. }
  10. function insertData() {
  11. const lines = [
  12. {
  13. metric: "meters.current",
  14. timestamp: 1648432611249,
  15. value: 10.3,
  16. tags: { location: "California.SanFrancisco", groupid: 2 },
  17. },
  18. {
  19. metric: "meters.voltage",
  20. timestamp: 1648432611249,
  21. value: 219,
  22. tags: { location: "California.LosAngeles", groupid: 1 },
  23. },
  24. {
  25. metric: "meters.current",
  26. timestamp: 1648432611250,
  27. value: 12.6,
  28. tags: { location: "California.SanFrancisco", groupid: 2 },
  29. },
  30. {
  31. metric: "meters.voltage",
  32. timestamp: 1648432611250,
  33. value: 221,
  34. tags: { location: "California.LosAngeles", groupid: 1 },
  35. },
  36. ];
  37. cursor.schemalessInsert(
  38. [JSON.stringify(lines)],
  39. taos.SCHEMALESS_PROTOCOL.TSDB_SML_JSON_PROTOCOL,
  40. taos.SCHEMALESS_PRECISION.TSDB_SML_TIMESTAMP_NOT_CONFIGURED
  41. );
  42. }
  43. try {
  44. createDatabase();
  45. insertData();
  46. } finally {
  47. cursor.close();
  48. conn.close();
  49. }

查看源码

  1. using TDengineDriver;
  2. namespace TDengineExample
  3. {
  4. internal class OptsJsonExample
  5. {
  6. static void Main()
  7. {
  8. IntPtr conn = GetConnection();
  9. try
  10. {
  11. PrepareDatabase(conn);
  12. string[] lines = { "[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," +
  13. " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, \"value\": 219, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}, " +
  14. "{\"metric\": \"meters.current\", \"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," +
  15. " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}]"
  16. };
  17. IntPtr res = TDengine.SchemalessInsert(conn, lines, 1, (int)TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED);
  18. if (TDengine.ErrorNo(res) != 0)
  19. {
  20. throw new Exception("SchemalessInsert failed since " + TDengine.Error(res));
  21. }
  22. else
  23. {
  24. int affectedRows = TDengine.AffectRows(res);
  25. Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows");
  26. }
  27. TDengine.FreeResult(res);
  28. }
  29. finally
  30. {
  31. TDengine.Close(conn);
  32. }
  33. }
  34. static IntPtr GetConnection()
  35. {
  36. string host = "localhost";
  37. short port = 6030;
  38. string username = "root";
  39. string password = "taosdata";
  40. string dbname = "";
  41. var conn = TDengine.Connect(host, username, password, dbname, port);
  42. if (conn == IntPtr.Zero)
  43. {
  44. throw new Exception("Connect to TDengine failed");
  45. }
  46. else
  47. {
  48. Console.WriteLine("Connect to TDengine success");
  49. }
  50. return conn;
  51. }
  52. static void PrepareDatabase(IntPtr conn)
  53. {
  54. IntPtr res = TDengine.Query(conn, "CREATE DATABASE test");
  55. if (TDengine.ErrorNo(res) != 0)
  56. {
  57. throw new Exception("failed to create database, reason: " + TDengine.Error(res));
  58. }
  59. res = TDengine.Query(conn, "USE test");
  60. if (TDengine.ErrorNo(res) != 0)
  61. {
  62. throw new Exception("failed to change database, reason: " + TDengine.Error(res));
  63. }
  64. }
  65. }
  66. }

查看源码

  1. int main() {
  2. TAOS *taos = taos_connect("localhost", "root", "taosdata", "", 6030);
  3. if (taos == NULL) {
  4. printf("failed to connect to server\n");
  5. exit(EXIT_FAILURE);
  6. }
  7. executeSQL(taos, "DROP DATABASE IF EXISTS test");
  8. executeSQL(taos, "CREATE DATABASE test");
  9. executeSQL(taos, "USE test");
  10. char *line =
  11. "[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": "
  12. "\"California.SanFrancisco\", \"groupid\": 2}},{\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, "
  13. "\"value\": 219, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}},{\"metric\": \"meters.current\", "
  14. "\"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": "
  15. "2}},{\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": "
  16. "\"California.LosAngeles\", \"groupid\": 1}}]";
  17. char *lines[] = {line};
  18. TAOS_RES *res = taos_schemaless_insert(taos, lines, 1, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED);
  19. if (taos_errno(res) != 0) {
  20. printf("failed to insert schema-less data, reason: %s\n", taos_errstr(res));
  21. } else {
  22. int affectedRow = taos_affected_rows(res);
  23. printf("successfully inserted %d rows\n", affectedRow);
  24. }
  25. taos_free_result(res);
  26. taos_close(taos);
  27. taos_cleanup();
  28. }
  29. // output:
  30. // successfully inserted 4 rows

查看源码

以上示例代码会自动创建 2 个超级表, 每个超级表有 2 条数据。

  1. taos> USE test;
  2. Database changed.
  3. taos> SHOW STABLES;
  4. name |
  5. =================================
  6. meters.current |
  7. meters.voltage |
  8. Query OK, 2 row(s) in set (0.001954s)
  9. taos> SELECT * FROM `meters.current`;
  10. _ts | _value | groupid | location |
  11. ===================================================================================================================
  12. 2022-03-28 09:56:51.249 | 10.300000000 | 2.000000000 | California.SanFrancisco |
  13. 2022-03-28 09:56:51.250 | 12.600000000 | 2.000000000 | California.SanFrancisco |
  14. Query OK, 2 row(s) in set (0.004076s)

SQL 查询示例

meters.voltage 是插入数据的超级表名。

可以通过超级表的 TAG 来过滤数据,比如查询 location=California.LosAngeles groupid=1 可以通过如下 SQL:

  1. SELECT * FROM `meters.current` WHERE location = "California.LosAngeles" AND groupid = 3;