InfluxDB 行协议

协议介绍

InfluxDB Line 协议采用一行字符串来表示一行数据。分为四部分:

  1. measurement,tag_set field_set timestamp
  • measurement 将作为超级表名。它与 tag_set 之间使用一个英文逗号来分隔。
  • tag_set 将作为标签数据,其格式形如 <tag_key>=<tag_value>,<tag_key>=<tag_value>,也即可以使用英文逗号来分隔多个标签数据。它与 field_set 之间使用一个半角空格来分隔。
  • field_set 将作为普通列数据,其格式形如 <field_key>=<field_value>,<field_key>=<field_value>,同样是使用英文逗号来分隔多个普通列的数据。它与 timestamp 之间使用一个半角空格来分隔。
  • timestamp 即本行数据对应的主键时间戳。

例如:

  1. meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611249500
InfluxDB 行协议 - 图1note
  • tag_set 中的所有的数据自动转化为 NCHAR 数据类型;
  • field_set 中的每个数据项都需要对自身的数据类型进行描述, 比如 1.2f32 代表 FLOAT 类型的数值 1.2, 如果不带类型后缀会被当作 DOUBLE 处理;
  • timestamp 支持多种时间精度。写入数据的时候需要用参数指定时间精度,支持从小时到纳秒的 6 种时间精度。
  • 为了提高写入的效率,默认假设同一个超级表中 field_set 的顺序是一样的(第一条数据包含所有的 field,后面的数据按照这个顺序),如果顺序不一样,需要配置参数 smlDataFormat 为 false,否则,数据写入按照相同顺序写入,库中数据会异常。(3.0.1.3 之后的版本 smlDataFormat 默认为 false,从3.0.3.0开始,该配置废弃) TDengine 无模式写入参考指南
  • 默认产生的子表名是根据规则生成的唯一 ID 值。用户也可以通过在 taos.cfg 里配置 smlChildTableName 参数来指定某个标签值作为子表名。该标签值应该具有全局唯一性。举例如下:假设有个标签名为tname, 配置 smlChildTableName=tname, 插入数据为 st,tname=cpu1,t1=4 c1=3 1626006833639000000 则创建的子表名为 cpu1。注意如果多行数据 tname 相同,但是后面的 tag_set 不同,则使用第一行自动建表时指定的 tag_set,其他的行会忽略)。TDengine 无模式写入参考指南

要了解更多可参考:InfluxDB Line 协议官方文档TDengine 无模式写入参考指南

示例代码

  • 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 LineProtocolExample {
  10. // format: measurement,tag_set field_set timestamp
  11. private static String[] lines = {
  12. "meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249000", // micro
  13. // seconds
  14. "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611249500",
  15. "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249300",
  16. "meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611249800",
  17. };
  18. private static Connection getConnection() throws SQLException {
  19. String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
  20. return DriverManager.getConnection(jdbcUrl);
  21. }
  22. private static void createDatabase(Connection conn) throws SQLException {
  23. try (Statement stmt = conn.createStatement()) {
  24. // the default precision is ms (millisecond), but we use us(microsecond) here.
  25. stmt.execute("CREATE DATABASE IF NOT EXISTS test PRECISION 'us'");
  26. stmt.execute("USE test");
  27. }
  28. }
  29. public static void main(String[] args) throws SQLException {
  30. try (Connection conn = getConnection()) {
  31. createDatabase(conn);
  32. SchemalessWriter writer = new SchemalessWriter(conn);
  33. writer.write(lines, SchemalessProtocolType.LINE, SchemalessTimestampType.MICRO_SECONDS);
  34. }
  35. }
  36. }

查看源码

  1. import taos
  2. from taos import SmlProtocol, SmlPrecision
  3. lines = ["meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249000",
  4. "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611249500",
  5. "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249300",
  6. "meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611249800",
  7. ]
  8. def get_connection():
  9. # create connection use firstEP in taos.cfg.
  10. return taos.connect()
  11. def create_database(conn):
  12. # the default precision is ms (microsecond), but we use us(microsecond) here.
  13. conn.execute("CREATE DATABASE test precision 'us'")
  14. conn.execute("USE test")
  15. def insert_lines(conn):
  16. affected_rows = conn.schemaless_insert(
  17. lines, SmlProtocol.LINE_PROTOCOL, SmlPrecision.MICRO_SECONDS)
  18. print(affected_rows) # 8
  19. if __name__ == '__main__':
  20. connection = get_connection()
  21. try:
  22. create_database(connection)
  23. insert_lines(connection)
  24. finally:
  25. connection.close()

查看源码

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "github.com/taosdata/driver-go/v3/af"
  6. )
  7. func prepareDatabase(conn *af.Connector) {
  8. _, err := conn.Exec("CREATE DATABASE test")
  9. if err != nil {
  10. panic(err)
  11. }
  12. _, err = conn.Exec("USE test")
  13. if err != nil {
  14. panic(err)
  15. }
  16. }
  17. func main() {
  18. conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
  19. if err != nil {
  20. fmt.Println("fail to connect, err:", err)
  21. }
  22. defer conn.Close()
  23. prepareDatabase(conn)
  24. var lines = []string{
  25. "meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249",
  26. "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250",
  27. "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249",
  28. "meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250",
  29. }
  30. err = conn.InfluxDBInsertLines(lines, "ms")
  31. if err != nil {
  32. log.Fatalln("insert error:", err)
  33. }
  34. }

查看源码

  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. "meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249",
  13. "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250",
  14. "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249",
  15. "meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250",
  16. ];
  17. cursor.schemalessInsert(
  18. lines,
  19. taos.SCHEMALESS_PROTOCOL.TSDB_SML_LINE_PROTOCOL,
  20. taos.SCHEMALESS_PRECISION.TSDB_SML_TIMESTAMP_MILLI_SECONDS
  21. );
  22. }
  23. try {
  24. createDatabase();
  25. insertData();
  26. } finally {
  27. cursor.close();
  28. conn.close();
  29. }

查看源码

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

查看源码

  1. int main() {
  2. TAOS *taos = taos_connect("localhost", "root", "taosdata", "", 0);
  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 *lines[] = {"meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249",
  11. "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250",
  12. "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249",
  13. "meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250"};
  14. TAOS_RES *res = taos_schemaless_insert(taos, lines, 4, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS);
  15. if (taos_errno(res) != 0) {
  16. printf("failed to insert schema-less data, reason: %s\n", taos_errstr(res));
  17. } else {
  18. int affectedRows = taos_affected_rows(res);
  19. printf("successfully inserted %d rows\n", affectedRows);
  20. }
  21. taos_free_result(res);
  22. taos_close(taos);
  23. taos_cleanup();
  24. }
  25. // output:
  26. // successfully inserted 4 rows

查看源码

SQL 查询示例

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

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

  1. SELECT * FROM meters WHERE location = "California.LosAngeles" AND groupid = 2;