文档说明

开始编写数据

本教程将向您介绍创建 行协议 数据并将其写入 InfluxDB 的基础知识。

InfluxDB 提供了许多不同的选项用于导入或写入数据,包括以下内容

  • InfluxDB HTTP API(v1 和 v2)
  • Telegraf
  • influxctl 命令行界面
  • influx3 数据命令行界面
  • InfluxDB 客户端库

如果使用 Telegraf 或 InfluxDB 客户端库等工具,它们可以为您构建行协议,但了解行协议的工作原理是很有帮助的。

行协议

所有写入 InfluxDB 的数据都是使用 行协议 编写的,这是一种基于文本的格式,允许您提供将数据点写入 InfluxDB 所需的信息。 本教程涵盖了行协议的基础知识,但有关详细信息,请参阅 行协议参考

行协议元素

行协议的每一行包含以下元素

* 必需的
  • * 测量:一个字符串,用于标识存储数据的
  • 标签集:由逗号分隔的关键值对列表,每个代表一个标签。标签键和值是无引号的字符串。 空格、逗号和等号必须转义。
  • * 字段集:以逗号分隔的键值对列表,每个键值对代表一个字段。字段键是不带引号的字符串。空格和逗号必须转义。字段值可以是 字符串(带引号)、浮点数整数无符号整数布尔值
  • 时间戳:与数据相关的 Unix 时间戳。InfluxDB 支持最高纳秒精度。如果时间戳的精度不是纳秒,必须在将数据写入 InfluxDB 时指定精度。

行协议元素解析

  • 测量值:在第一个空白前的所有内容。
  • 标签集:第一个空白前的第一个空白处的键值对。
  • 字段集:第一个和第二个空白之间的键值对。
  • 时间戳:第二个空白后的整数值。
  • 行之间由换行符(\n)分隔。行协议对空白敏感。

measurement,tag1=val1,tag2=val2 field1="v1",field2=1i 0000000000000000000


有关模式设计建议,请参阅 InfluxDB 模式设计

构造行协议

了解行协议的基础知识后,您现在可以构造行协议并将数据写入 InfluxDB。考虑一个从您家中的传感器收集数据的用例。每个传感器收集温度、湿度和一氧化碳读数。要收集这些数据,请使用以下模式

  • 测量值home
    • 标签
      • room:客厅或厨房
    • 字段
      • temp:温度(浮点数)°C
      • hum:湿度百分比(浮点数)
      • co:一氧化碳(整数)ppm
    • 时间戳:以 精度的 Unix 时间戳

以下行协议示例表示从 2022-01-01T08:00:00Z (UTC) 开始直到 2022-01-01T20:00:00Z (UTC) 每小时收集的数据。

家庭传感器数据行协议
home,room=Living\ Room temp=21.1,hum=35.9,co=0i 1641024000
home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641024000
home,room=Living\ Room temp=21.4,hum=35.9,co=0i 1641027600
home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641027600
home,room=Living\ Room temp=21.8,hum=36.0,co=0i 1641031200
home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641031200
home,room=Living\ Room temp=22.2,hum=36.0,co=0i 1641034800
home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641034800
home,room=Living\ Room temp=22.2,hum=35.9,co=0i 1641038400
home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641038400
home,room=Living\ Room temp=22.4,hum=36.0,co=0i 1641042000
home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641042000
home,room=Living\ Room temp=22.3,hum=36.1,co=0i 1641045600
home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641045600
home,room=Living\ Room temp=22.3,hum=36.1,co=1i 1641049200
home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641049200
home,room=Living\ Room temp=22.4,hum=36.0,co=4i 1641052800
home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641052800
home,room=Living\ Room temp=22.6,hum=35.9,co=5i 1641056400
home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641056400
home,room=Living\ Room temp=22.8,hum=36.2,co=9i 1641060000
home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641060000
home,room=Living\ Room temp=22.5,hum=36.3,co=14i 1641063600
home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641063600
home,room=Living\ Room temp=22.2,hum=36.4,co=17i 1641067200
home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200

将行协议写入 InfluxDB

以下示例显示了如何将前面 样本数据(已以行协议格式提供)写入 InfluxDB 集群数据库。

有关可用工具和选项的更多信息,请参阅 写入数据

本入门教程中的一些示例假设您的 InfluxDB 凭据(URL组织令牌)由 环境变量 提供。

使用 influxctl write 命令家庭传感器样本数据 写入您的 InfluxDB 集群。提供以下信息

influxctl write \
  --database 
get-started
\
--token $INFLUX_TOKEN \ --precision s \ 'home,room=Living\ Room temp=21.1,hum=35.9,co=0i 1641024000 home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641024000 home,room=Living\ Room temp=21.4,hum=35.9,co=0i 1641027600 home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641027600 home,room=Living\ Room temp=21.8,hum=36.0,co=0i 1641031200 home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641031200 home,room=Living\ Room temp=22.2,hum=36.0,co=0i 1641034800 home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641034800 home,room=Living\ Room temp=22.2,hum=35.9,co=0i 1641038400 home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641038400 home,room=Living\ Room temp=22.4,hum=36.0,co=0i 1641042000 home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641042000 home,room=Living\ Room temp=22.3,hum=36.1,co=0i 1641045600 home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641045600 home,room=Living\ Room temp=22.3,hum=36.1,co=1i 1641049200 home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641049200 home,room=Living\ Room temp=22.4,hum=36.0,co=4i 1641052800 home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641052800 home,room=Living\ Room temp=22.6,hum=35.9,co=5i 1641056400 home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641056400 home,room=Living\ Room temp=22.8,hum=36.2,co=9i 1641060000 home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641060000 home,room=Living\ Room temp=22.5,hum=36.3,co=14i 1641063600 home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641063600 home,room=Living\ Room temp=22.2,hum=36.4,co=17i 1641067200 home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200'

如果成功,输出是成功消息;否则,错误详情和失败消息。

使用 Telegraf 消费行协议,并将其写入 InfluxDB 集群。

  1. 如果您尚未安装,请按照说明 下载并安装 Telegraf

  2. 家庭传感器数据样本 复制并保存在您本地系统上的文件中 - 例如,home.lp

    cat <<- EOF > home.lp
    home,room=Living\ Room temp=21.1,hum=35.9,co=0i 1641024000
    home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641024000
    home,room=Living\ Room temp=21.4,hum=35.9,co=0i 1641027600
    home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641027600
    home,room=Living\ Room temp=21.8,hum=36.0,co=0i 1641031200
    home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641031200
    home,room=Living\ Room temp=22.2,hum=36.0,co=0i 1641034800
    home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641034800
    home,room=Living\ Room temp=22.2,hum=35.9,co=0i 1641038400
    home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641038400
    home,room=Living\ Room temp=22.4,hum=36.0,co=0i 1641042000
    home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641042000
    home,room=Living\ Room temp=22.3,hum=36.1,co=0i 1641045600
    home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641045600
    home,room=Living\ Room temp=22.3,hum=36.1,co=1i 1641049200
    home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641049200
    home,room=Living\ Room temp=22.4,hum=36.0,co=4i 1641052800
    home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641052800
    home,room=Living\ Room temp=22.6,hum=35.9,co=5i 1641056400
    home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641056400
    home,room=Living\ Room temp=22.8,hum=36.2,co=9i 1641060000
    home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641060000
    home,room=Living\ Room temp=22.5,hum=36.3,co=14i 1641063600
    home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641063600
    home,room=Living\ Room temp=22.2,hum=36.4,co=17i 1641067200
    home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200
    EOF
    
  3. 运行以下命令以生成 Telegraf 配置文件(telegraf.conf),该文件启用了 inputs.fileoutputs.influxdb_v2 插件

    mkdir -p iot-project \
    && telegraf --sample-config \
      --input-filter file \
      --output-filter influxdb_v2 \
      > iot-project/telegraf.conf
    
  4. 在您的编辑器中打开 iot-project/telegraf.conf 并配置以下内容

    • 文件 输入插件:在 [[inputs.file]].files 列表中,将 "/tmp/metrics.out" 替换为您的样本数据文件名。如果 Telegraf 启动时找不到文件,则停止处理并退出。

      [[inputs.file]]
        ## Files to parse each interval.  Accept standard unix glob matching rules,
        ## as well as ** to match recursive files and directories.
        files = ["home.lp"]
        # Set the timestamp precision to the precision in your data.
        influx_timestamp_precision = '1s'
        ## Optionally, use the newer, more efficient line protocol parser
        influx_parser_type = 'upstream' 
      

使用已经使用 InfluxDB v1 /write API 端点的工作负载写入数据。

如果您正在从 InfluxDB 1.x 迁移数据,请参阅 从 InfluxDB 1.x 迁移数据到 InfluxDB 集群 指南。

要使用 InfluxDB v1 HTTP API 将数据写入 InfluxDB,请使用 POST 请求方法向 InfluxDB API /write 端点 发送请求。

POST https://cluster-host.com/write

在您的请求中包含以下内容

  • 头部:
    • Authorization:Bearer <INFLUX_TOKEN>
    • Content-Type:text/plain; charset=utf-8
    • Accept:application/json
  • 查询参数:
  • 请求正文:纯文本行协议

使用 InfluxDB 集群的 v1 API /write 端点Authorization: BearerAuthorization: Token 是等效的,您可以使用任一方案在请求中传递数据库令牌。有关 HTTP API 令牌方案的更多信息,请参阅如何 认证 API 请求

以下示例使用 cURL 和 InfluxDB v1 API 将行协议写入 InfluxDB

response=$(curl --silent --write-out "%{response_code}:-%{errormsg}" \
  "https://cluster-host.com/write?db=get-started&precision=s" \
  --header "Authorization: Bearer 
DATABASE_TOKEN
"
\
--header "Content-type: text/plain; charset=utf-8" \ --header "Accept: application/json" \ --data-binary " home,room=Living\ Room temp=21.1,hum=35.9,co=0i 1641024000 home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641024000 home,room=Living\ Room temp=21.4,hum=35.9,co=0i 1641027600 home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641027600 home,room=Living\ Room temp=21.8,hum=36.0,co=0i 1641031200 home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641031200 home,room=Living\ Room temp=22.2,hum=36.0,co=0i 1641034800 home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641034800 home,room=Living\ Room temp=22.2,hum=35.9,co=0i 1641038400 home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641038400 home,room=Living\ Room temp=22.4,hum=36.0,co=0i 1641042000 home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641042000 home,room=Living\ Room temp=22.3,hum=36.1,co=0i 1641045600 home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641045600 home,room=Living\ Room temp=22.3,hum=36.1,co=1i 1641049200 home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641049200 home,room=Living\ Room temp=22.4,hum=36.0,co=4i 1641052800 home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641052800 home,room=Living\ Room temp=22.6,hum=35.9,co=5i 1641056400 home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641056400 home,room=Living\ Room temp=22.8,hum=36.2,co=9i 1641060000 home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641060000 home,room=Living\ Room temp=22.5,hum=36.3,co=14i 1641063600 home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641063600 home,room=Living\ Room temp=22.2,hum=36.4,co=17i 1641067200 home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200 ") # Format the response code and error message output. response_code=${response%%:-*} errormsg=${response#*:-} # Remove leading and trailing whitespace from errormsg errormsg=$(echo "${errormsg}" | tr -d '[:space:]') echo "$response_code" if [[ $errormsg ]]; then echo "$errormsg" fi

替换以下内容

  • DATABASE_TOKEN:一个 数据库令牌,具有对指定数据库的足够权限

如果成功,输出是 HTTP 204 No Content 状态代码;否则,错误状态代码和错误消息。

204

要使用 InfluxDB v2 HTTP API 将数据写入 InfluxDB,请使用 POST 请求方法向 InfluxDB API /api/v2/write 端点发送请求。

POST https://cluster-host.com/api/v2/write

在您的请求中包含以下内容

  • 头部:
    • Authorization:Bearer <INFLUX_TOKEN>
    • Content-Type:text/plain; charset=utf-8
    • Accept:application/json
  • 查询参数:
    • bucket:InfluxDB 数据库名
    • precision时间戳精度(默认为 ns
  • 请求正文:纯文本行协议

InfluxDB 集群的 v2 API /api/v2/write 端点支持 BearerToken 授权方案,您可以使用任一方案在请求中传递数据库令牌。有关 HTTP API 令牌方案的更多信息,请参阅如何 认证 API 请求

以下示例使用 cURL 和 InfluxDB v2 API 将行协议写入 InfluxDB

response=$(curl --silent --write-out "%{response_code}:-%{errormsg}" \
  "https://cluster-host.com/api/v2/write?bucket=get-started&precision=s" \
  --header "Authorization: Bearer 
DATABASE_TOKEN
"
\
--header "Content-Type: text/plain; charset=utf-8" \ --header "Accept: application/json" \ --data-binary " home,room=Living\ Room temp=21.1,hum=35.9,co=0i 1641024000 home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641024000 home,room=Living\ Room temp=21.4,hum=35.9,co=0i 1641027600 home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641027600 home,room=Living\ Room temp=21.8,hum=36.0,co=0i 1641031200 home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641031200 home,room=Living\ Room temp=22.2,hum=36.0,co=0i 1641034800 home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641034800 home,room=Living\ Room temp=22.2,hum=35.9,co=0i 1641038400 home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641038400 home,room=Living\ Room temp=22.4,hum=36.0,co=0i 1641042000 home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641042000 home,room=Living\ Room temp=22.3,hum=36.1,co=0i 1641045600 home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641045600 home,room=Living\ Room temp=22.3,hum=36.1,co=1i 1641049200 home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641049200 home,room=Living\ Room temp=22.4,hum=36.0,co=4i 1641052800 home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641052800 home,room=Living\ Room temp=22.6,hum=35.9,co=5i 1641056400 home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641056400 home,room=Living\ Room temp=22.8,hum=36.2,co=9i 1641060000 home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641060000 home,room=Living\ Room temp=22.5,hum=36.3,co=14i 1641063600 home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641063600 home,room=Living\ Room temp=22.2,hum=36.4,co=17i 1641067200 home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200 ") # Format the response code and error message output. response_code=${response%%:-*} errormsg=${response#*:-} # Remove leading and trailing whitespace from errormsg errormsg=$(echo "${errormsg}" | tr -d '[:space:]') echo "$response_code" if [[ $errormsg ]]; then echo "$errormsg" fi

替换以下内容

  • DATABASE_TOKEN:一个 数据库令牌,具有对指定数据库的足够权限

如果成功,输出是 HTTP 204 No Content 状态代码;否则,错误状态代码和错误消息。

204

要使用 Python 将数据写入 InfluxDB 集群,请使用 influxdb_client_3 模块。以下步骤包括设置 Python 虚拟环境,以将依赖项限定在当前项目范围内。

  1. 创建一个模块目录并进入该目录——例如:

    mkdir -p influxdb_py_client && cd influxdb_py_client
    
  2. 设置您的Python虚拟环境。在模块目录中,输入以下命令:

    python -m venv envs/virtual-env
    
  3. 激活虚拟环境。

    source ./envs/virtual-env/bin/activate
    
  4. 安装客户端库包

    pip install influxdb3-python
    

    influxdb3-python 包提供了 influxdb_client_3 模块,并安装了用于处理查询返回的 Arrow 数据的 pyarrow

  5. 在终端或编辑器中,为您的代码创建一个新文件——例如:write.py

    touch write.py
    
  6. write.py 中,输入以下示例代码

    from influxdb_client_3 import InfluxDBClient3
    import os
    
    # INFLUX_TOKEN is an environment variable you assigned to your
    # database WRITE token value.
    token = os.getenv('INFLUX_TOKEN')
    
    # host is the URL hostname without protocol or trailing slash
    client = InfluxDBClient3(
        host='cluster-host.com',
        org='',
        token=token,
        database='get-started'
    )
    
    lines = [
        "home,room=Living\ Room temp=21.1,hum=35.9,co=0i 1641024000",
        "home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641024000",
        "home,room=Living\ Room temp=21.4,hum=35.9,co=0i 1641027600",
        "home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641027600",
        "home,room=Living\ Room temp=21.8,hum=36.0,co=0i 1641031200",
        "home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641031200",
        "home,room=Living\ Room temp=22.2,hum=36.0,co=0i 1641034800",
        "home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641034800",
        "home,room=Living\ Room temp=22.2,hum=35.9,co=0i 1641038400",
        "home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641038400",
        "home,room=Living\ Room temp=22.4,hum=36.0,co=0i 1641042000",
        "home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641042000",
        "home,room=Living\ Room temp=22.3,hum=36.1,co=0i 1641045600",
        "home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641045600",
        "home,room=Living\ Room temp=22.3,hum=36.1,co=1i 1641049200",
        "home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641049200",
        "home,room=Living\ Room temp=22.4,hum=36.0,co=4i 1641052800",
        "home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641052800",
        "home,room=Living\ Room temp=22.6,hum=35.9,co=5i 1641056400",
        "home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641056400",
        "home,room=Living\ Room temp=22.8,hum=36.2,co=9i 1641060000",
        "home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641060000",
        "home,room=Living\ Room temp=22.5,hum=36.3,co=14i 1641063600",
        "home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641063600",
        "home,room=Living\ Room temp=22.2,hum=36.4,co=17i 1641067200",
        "home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200"
    ]
    
    client.write(lines,write_precision='s')
    

    示例执行以下操作

    1. influxdb_client_3 模块导入 InfluxDBClient3 对象。

    2. 调用 InfluxDBClient3() 构造函数来实例化一个配置了以下凭据的 InfluxDB 客户端

      • host:InfluxDB 集群主机名(不带协议或尾斜杠的 URL)
      • org:一个空字符串或任意字符串(InfluxDB 会忽略此参数)
      • token:一个具有对指定数据库写入访问权限的 数据库令牌将其存储在秘密存储或环境变量中,以避免暴露原始令牌字符串。
      • database:要写入的 InfluxDB 集群数据库的名称
    3. 定义了一个表示数据记录的行协议字符串列表。

    4. 调用 client.write() 方法,传入行协议记录列表和写入选项。

      由于示例行协议中的时间戳以秒为精度,示例通过传递 write_precision='s' 选项将 时间戳精度 设置为秒。

  7. 要在终端中执行模块并将行协议写入您的 InfluxDB 集群数据库,输入以下命令

    python write.py
    

如果成功,输出是成功消息;否则,错误详情和失败消息。

要使用 Go 写入 InfluxDB 集群,请使用 InfluxDB v3 influxdb3-go 客户端库包

  1. 在您的项目目录中,创建一个新模块目录并进入该目录。

    mkdir -p influxdb_go_client && cd influxdb_go_client
    
  2. 在该目录中初始化一个新的 Go 模块。

    go mod init influxdb_go_client
    
  3. 在终端或编辑器中,为您的代码创建一个新文件——例如:write.go

    touch write.go
    
  4. write.go 中,输入以下示例代码

    package main
    
    import (
      "context"
      "os"
      "fmt"
      "log"
    
      "github.com/InfluxCommunity/influxdb3-go/influxdb3"
    )
    
    // Write line protocol data to InfluxDB
    func WriteLineProtocol() error {
      // INFLUX_TOKEN is an environment variable you assigned to your
      // database WRITE token value.
      token := os.Getenv("INFLUX_TOKEN")
      database := os.Getenv("INFLUX_DATABASE")
    
      // Initialize a client with URL and token,
      // and set the timestamp precision for writes.
      client, err := influxdb3.New(influxdb3.ClientConfig{
        Host:     "https://cluster-host.com",
        Token:    token,
        Database: database,
        WriteOptions: &influxdb3.WriteOptions{Precision: lineprotocol.Second},
      })
    
      // Close the client when the function returns.
      defer func(client *influxdb3.Client) {
        err := client.Close()
        if err != nil {
          panic(err)
        }
      }(client)
    
      // Define line protocol records to write.
      // Use a raw string literal (denoted by backticks)
      // to preserve backslashes and prevent interpretation
      // of escape sequences--for example, escaped spaces in tag values.
      lines := [...]string{
        `home,room=Living\ Room temp=21.1,hum=35.9,co=0i 1641124000`,
        `home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641124000`,
        `home,room=Living\ Room temp=21.4,hum=35.9,co=0i 1641127600`,
        `home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641127600`,
        `home,room=Living\ Room temp=21.8,hum=36.0,co=0i 1641131200`,
        `home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641131200`,
        `home,room=Living\ Room temp=22.2,hum=36.0,co=0i 1641134800`,
        `home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641134800`,
        `home,room=Living\ Room temp=22.2,hum=35.9,co=0i 1641138400`,
        `home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641138400`,
        `home,room=Living\ Room temp=22.4,hum=36.0,co=0i 1641142000`,
        `home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641142000`,
        `home,room=Living\ Room temp=22.3,hum=36.1,co=0i 1641145600`,
        `home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641145600`,
        `home,room=Living\ Room temp=22.3,hum=36.1,co=1i 1641149200`,
        `home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641149200`,
        `home,room=Living\ Room temp=22.4,hum=36.0,co=4i 1641152800`,
        `home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641152800`,
        `home,room=Living\ Room temp=22.6,hum=35.9,co=5i 1641156400`,
        `home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641156400`,
        `home,room=Living\ Room temp=22.8,hum=36.2,co=9i 1641160000`,
        `home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641160000`,
        `home,room=Living\ Room temp=22.5,hum=36.3,co=14i 1641163600`,
        `home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641163600`,
        `home,room=Living\ Room temp=22.2,hum=36.4,co=17i 1641167200`,
        `home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641167200`,
      }
    
      // Iterate over the lines array and write each line
      // separately to InfluxDB
      for _, record := range lines {
        err = client.Write(context.Background(), []byte(record))
        if err != nil {
          log.Fatalf("Error writing line protocol: %v", err)
        }
      }
    
      if err != nil {
        panic(err)
      }
    
      fmt.Println("Data has been written successfully.")
      return nil
    }
    

    示例执行以下操作

    1. 导入所需的包。

    2. 定义一个 WriteLineProtocol() 函数,执行以下操作

      1. 要实例化客户端,调用 influxdb3.New(influxdb3.ClientConfig) 函数,并传递以下内容

        • Host:InfluxDB 集群 URL

        • Database:您的 InfluxDB 集群数据库的名称

        • Token:一个具有 写入 访问权限的 数据库令牌将其存储在秘密存储或环境变量中,以避免暴露原始令牌字符串。

        • WriteOptions:写入 InfluxDB 的 influxdb3.WriteOptions 选项

          由于示例行协议中的时间戳以秒为精度,示例通过传递 Precision: lineprotocol.Second 选项将 时间戳精度 设置为秒。

      2. 定义一个延迟函数,在函数返回时关闭客户端。

      3. 定义了一个表示数据记录的行协议字符串数组。

      4. 遍历行协议数组,并调用写客户端的 Write() 方法将每行行协议单独写入 InfluxDB。

  5. 在您的编辑器中创建一个 main.go 文件,并输入以下示例代码,该代码调用 WriteLineProtocol() 函数

    package main
    
    // Module main function
    func main() {
      WriteLineProtocol()
    }
    
  6. 要安装依赖关系并将数据写入您的 InfluxDB 集群数据库,在终端中输入以下命令

    go mod tidy && go run influxdb_go_client
    

如果成功,输出是成功消息;否则,错误详情和失败消息。

  1. 如果您还没有安装,请按照 下载和安装 Node.js 和 npm 的说明 进行操作。

  2. 在终端中,输入以下命令以创建您的项目的 influxdb_js_client 目录

    mkdir influxdb_js_client && cd influxdb_js_client
    
  3. influxdb_js_client 内部,输入以下命令以初始化一个包。此示例配置包使用 ECMAScript 模块 (ESM)

    npm init -y; npm pkg set type="module"
    
  4. @influxdata/influxdb3-client JavaScript 客户端库作为依赖项安装到您的项目中。

    npm install --save @influxdata/influxdb3-client
    
  5. 在您的终端或编辑器中,创建一个 write.js 文件。

    touch write.js
    
  6. write.js 内部,输入以下示例代码

    // write.js
    import { InfluxDBClient } from '@influxdata/influxdb3-client';
    
    /**
     * Set InfluxDB credentials.
     */
    const host = 'cluster-host.com';
    const database = 'get-started';
    /**
     * INFLUX_TOKEN is an environment variable you assigned to your
     * WRITE token value.
     */
    const token = process.env.INFLUX_TOKEN;
    
    /**
     * Write line protocol to InfluxDB using the JavaScript client library.
     */
    export async function writeLineProtocol() {
      /**
       * Instantiate an InfluxDBClient
       */
      const client = new InfluxDBClient({ host, token });
    
      /**
       * Define line protocol records to write.
       */
      const records = [
        `home,room=Living\\ Room temp=21.1,hum=35.9,co=0i 1641124000`,
        `home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641124000`,
        `home,room=Living\\ Room temp=21.4,hum=35.9,co=0i 1641127600`,
        `home,room=Kitchen temp=23.0,hum=36.2,co=0 1641127600`,
        `home,room=Living\\ Room temp=21.8,hum=36.0,co=0i 1641131200`,
        `home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641131200`,
        `home,room=Living\\ Room temp=22.2,hum=36.0,co=0i 1641134800`,
        `home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641134800`,
        `home,room=Living\\ Room temp=22.2,hum=35.9,co=0i 1641138400`,
        `home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641138400`,
        `home,room=Living\\ Room temp=22.4,hum=36.0,co=0i 1641142000`,
        `home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641142000`,
        `home,room=Living\\ Room temp=22.3,hum=36.1,co=0i 1641145600`,
        `home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641145600`,
        `home,room=Living\\ Room temp=22.3,hum=36.1,co=1i 1641149200`,
        `home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641149200`,
        `home,room=Living\\ Room temp=22.4,hum=36.0,co=4i 1641152800`,
        `home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641152800`,
        `home,room=Living\\ Room temp=22.6,hum=35.9,co=5i 1641156400`,
        `home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641156400`,
        `home,room=Living\\ Room temp=22.8,hum=36.2,co=9i 1641160000`,
        `home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641160000`,
        `home,room=Living\\ Room temp=22.5,hum=36.3,co=14i 1641163600`,
        `home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641163600`,
        `home,room=Living\\ Room temp=22.2,hum=36.4,co=17i 1641167200`,
        `home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641167200`,
      ];
    
      /**
       * Creates an array that contains separate write request promises
       * for all the records.
       */
      const writePromises = records.map((record) => {
        return client.write(record, database, '', { precision: 's' }).then(
          () => `Data has been written successfully: ${record}`,
          () => `Failed writing data: ${record}`
        );
      });
    
      /**
       * Wait for all the write promises to settle, and then output the results.
       */
      const writeResults = await Promise.allSettled(writePromises);
      writeResults.forEach((write) => console.log(write.value));
    
      /** Close the client to release resources. */
      await client.close();
    }
    

    示例代码执行以下操作

    1. 导入 InfluxDBClient 类。

    2. 调用 new InfluxDBClient() 构造函数,并将 ClientOptions 对象传递给它以实例化一个配置有 InfluxDB 凭据的客户端。

      • host:您的 InfluxDB 集群 URL
      • token:一个具有 访问指定数据库的 数据库令牌将其存储在密钥存储或环境变量中,以避免暴露原始令牌字符串。
    3. 定义了一个表示数据记录的行协议字符串列表。

    4. 对每条记录调用客户端的 write() 方法,定义要返回的成功或失败消息,并将挂起的承诺收集到 writePromises 数组中。每次调用 write() 都传递以下参数

      • record:行协议记录
      • database:要写入的 InfluxDB 集群数据库的名称
      • {precision}:一个设置 precision 值的 WriteOptions 对象。

      因为示例行协议中的时间戳是秒精度,所以示例传递 s 作为 precision 值,将写入的 时间戳精度 设置为秒。

    5. 使用承诺数组调用 Promise.allSettled() 以暂停执行,直到承诺完成,然后将包含成功和失败消息的数组赋值给 writeResults 常量。

    6. 遍历并打印 writeResults 中的消息。

    7. 关闭客户端以释放资源。

  7. 在您的终端或编辑器中,创建一个 index.js 文件。

  8. index.js 内部,输入以下示例代码以导入并调用 writeLineProtocol()

    // index.js
    import { writeLineProtocol } from './write.js';
    
    /**
     * Execute the client functions.
     */
    async function main() {
      /** Write line protocol data to InfluxDB. */
      await writeLineProtocol();
    }
    
    main();
    
  9. 在您的终端中,执行 index.js 以写入 InfluxDB 集群

    node index.js
    

如果成功,输出是成功消息;否则,错误详情和失败消息。

  1. 如果您还没有,请遵循 Microsoft.com 下载说明 安装 .NET 和 dotnet CLI。

  2. 在您的终端中,使用 .NET 控制台 模板创建一个可执行 C# 项目。

    dotnet new console --name influxdb_csharp_client
    
  3. 切换到生成的 influxdb_csharp_client 目录。

    cd influxdb_csharp_client
    
  4. 运行以下命令以安装 InfluxDB v3 C# 客户端库的最新版本。

    dotnet add package InfluxDB3.Client
    
  5. 在您的编辑器中,创建一个 Write.cs 文件并输入以下示例代码

    // Write.cs
    
    using System;
    using System.Threading.Tasks;
    using InfluxDB3.Client;
    using InfluxDB3.Client.Query;
    
    namespace InfluxDBv3;
    
    public class Write
    {
      /**
        * Writes line protocol to InfluxDB using the C# .NET client
        * library.
        */
      public static async Task WriteLines()
      {
        // Set InfluxDB credentials
        const string host = "https://cluster-host.com";
        string? database = "get-started";
    
        /**
          * INFLUX_TOKEN is an environment variable you assigned to your
          * WRITE token value.
          */
        string? token = System.Environment
            .GetEnvironmentVariable("INFLUX_TOKEN");
    
        // Instantiate the InfluxDB client with credentials.
        using var client = new InfluxDBClient(
            host, token: token, database: database);
    
        /**
          * Define an array of line protocol strings to write.
          * Include an additional backslash to preserve backslashes
          * and prevent interpretation of escape sequences---for example,
          * escaped spaces in tag values.
          */
        string[] lines = new string[] {
              "home,room=Living\\ Room temp=21.1,hum=35.9,co=0i 1641024000",
              "home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641024000",
              "home,room=Living\\ Room temp=21.4,hum=35.9,co=0i 1641027600",
              "home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641027600",
              "home,room=Living\\ Room temp=21.8,hum=36.0,co=0i 1641031200",
              "home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641031200",
              "home,room=Living\\ Room temp=22.2,hum=36.0,co=0i 1641034800",
              "home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641034800",
              "home,room=Living\\ Room temp=22.2,hum=35.9,co=0i 1641038400",
              "home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641038400",
              "home,room=Living\\ Room temp=22.4,hum=36.0,co=0i 1641042000",
              "home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641042000",
              "home,room=Living\\ Room temp=22.3,hum=36.1,co=0i 1641045600",
              "home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641045600",
              "home,room=Living\\ Room temp=22.3,hum=36.1,co=1i 1641049200",
              "home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641049200",
              "home,room=Living\\ Room temp=22.4,hum=36.0,co=4i 1641052800",
              "home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641052800",
              "home,room=Living\\ Room temp=22.6,hum=35.9,co=5i 1641056400",
              "home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641056400",
              "home,room=Living\\ Room temp=22.8,hum=36.2,co=9i 1641060000",
              "home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641060000",
              "home,room=Living\\ Room temp=22.5,hum=36.3,co=14i 1641063600",
              "home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641063600",
              "home,room=Living\\ Room temp=22.2,hum=36.4,co=17i 1641067200",
              "home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200"
        };
    
        // Write each record separately.
        foreach (string line in lines)
        {
          // Write the record to InfluxDB with timestamp precision in seconds.
          await client.WriteRecordAsync(
              record: line, precision: WritePrecision.S);
          Console.WriteLine(
              "Data has been written successfully: {0,-30}", line);
        }
      }
    }
    

    示例执行以下操作

    1. 调用 new InfluxDBClient() 构造函数以实例化一个配置有 InfluxDB 凭据的客户端。

      • host:您的 InfluxDB 集群 URL
      • database:要写入的 InfluxDB 集群数据库的名称
      • token:一个具有 访问指定数据库的 数据库令牌将其存储在密钥存储或环境变量中,以避免暴露原始令牌字符串。

      using 语句确保程序在不再需要客户端时释放它。

    2. 定义了一个表示数据记录的行协议字符串数组。

    3. 调用客户端的 WriteRecordAsync() 方法以将每行协议记录写入 InfluxDB。

      因为示例行协议中的时间戳是秒精度,所以示例将 WritePrecision.S 枚举值 传递给 precision: 选项,以将 时间戳精度 设置为秒。

  6. 在您的编辑器中打开 Program.cs 文件,并用以下内容替换其内容

    // Program.cs
    
    using System;
    using System.Threading.Tasks;
    
    namespace InfluxDBv3;
    
    public class Program
    {
      public static async Task Main()
      {
        await Write.WriteLineProtocol();
      }
    }
    

    Program 类与您在上一步骤中定义的 Write 类共享相同的 InfluxDBv3 命名空间,并定义了一个 Main() 函数,该函数调用 Write.WriteLineProtocol()dotnet CLI 识别 Program.Main() 为您的程序入口点。

  7. 要在终端中构建和执行程序并将行协议写入您的 InfluxDB 集群数据库,请输入以下命令

    dotnet run
    

如果成功,输出是成功消息;否则,错误详情和失败消息。

本教程假定使用 Maven 版本 3.9 和 Java 版本 >= 15。

  1. 如果您尚未安装,请按照说明下载和安装适用于您的系统的 Java JDKMaven

  2. 在您的终端或编辑器中,使用 Maven 生成一个项目——例如

    mvn org.apache.maven.plugins:maven-archetype-plugin:3.1.2:generate \
    -DarchetypeArtifactId="maven-archetype-quickstart" \
    -DarchetypeGroupId="org.apache.maven.archetypes" -DarchetypeVersion="1.4" \
    -DgroupId="com.influxdbv3" -DartifactId="influxdb_java_client"
    -Dversion="1.0"
    

    Maven 创建了 <artifactId> 目录(./influxdb_java_client),其中包含一个 pom.xml 文件以及为您的 com.influxdbv3.influxdb_java_client Java 应用程序搭建的框架。

  3. 在您的终端或编辑器中,切换到 ./influxdb_java_client 目录——例如

    cd ./influxdb_java_client
    
  4. 在您的编辑器中,打开 Maven 配置文件 pom.xml 并将 com.influxdb.influxdb3-java 客户端库添加到 dependencies 中。

    ...
    <dependencies>
      ...
      <dependency>
      <groupId>com.influxdb</groupId>
      <artifactId>influxdb3-java</artifactId>
      <version>0.1.0</version>
      </dependency>
      ...
    </dependencies>
    
  5. 为了检查您的 pom.xml 文件是否存在问题,运行 Maven 的 validate 命令——例如,在您的终端中输入以下内容

    mvn validate
    
  6. 在您的编辑器中,导航到 ./influxdb_java_client/src/main/java/com/influxdbv3 目录并创建一个 Write.java 文件。

  7. Write.java 中,输入以下示例代码

    // Write.java
    package com.influxdbv3;
    
    import java.util.List;
    import com.influxdb.v3.client.InfluxDBClient;
    import com.influxdb.v3.client.write.WriteOptions;
    import com.influxdb.v3.client.write.WritePrecision;
    
    /**
      * Writes line protocol to InfluxDB using the Java client
      * library.
      */
    public final class Write {
        /**
        * Write data to InfluxDB v3.
        */
        private Write() {
            //not called
        }
    
        /**
          * @throws Exception
          */
        public static void writeLineProtocol() throws Exception {
    
            // Set InfluxDB credentials
            final String host = "https://cluster-host.com";
            final String database = "get-started";
    
            /**
              * INFLUX_TOKEN is an environment variable you assigned to your
              * WRITE token value.
              */
            final char[] token = (System.getenv("INFLUX_TOKEN")).
            toCharArray();
    
            // Instantiate the InfluxDB client.
            try (InfluxDBClient client = InfluxDBClient.getInstance(host,
            token, database)) {
                // Create a list of line protocol records.
                final List<String> records = List.of(
                  "home,room=Living\\ Room temp=21.1,hum=35.9,co=0i 1641024000",
                  "home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641024000",
                  "home,room=Living\\ Room temp=21.4,hum=35.9,co=0i 1641027600",
                  "home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641027600",
                  "home,room=Living\\ Room temp=21.8,hum=36.0,co=0i 1641031200",
                  "home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641031200",
                  "home,room=Living\\ Room temp=22.2,hum=36.0,co=0i 1641034800",
                  "home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641034800",
                  "home,room=Living\\ Room temp=22.2,hum=35.9,co=0i 1641038400",
                  "home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641038400",
                  "home,room=Living\\ Room temp=22.4,hum=36.0,co=0i 1641042000",
                  "home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641042000",
                  "home,room=Living\\ Room temp=22.3,hum=36.1,co=0i 1641045600",
                  "home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641045600",
                  "home,room=Living\\ Room temp=22.3,hum=36.1,co=1i 1641049200",
                  "home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641049200",
                  "home,room=Living\\ Room temp=22.4,hum=36.0,co=4i 1641052800",
                  "home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641052800",
                  "home,room=Living\\ Room temp=22.6,hum=35.9,co=5i 1641056400",
                  "home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641056400",
                  "home,room=Living\\ Room temp=22.8,hum=36.2,co=9i 1641060000",
                  "home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641060000",
                  "home,room=Living\\ Room temp=22.5,hum=36.3,co=14i 1641063600",
                  "home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641063600",
                  "home,room=Living\\ Room temp=22.2,hum=36.4,co=17i 1641067200",
                  "home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200"
                );
    
                /**
                 * Write each record separately to InfluxDB with timestamp
                 * precision in seconds.
                 * If no error occurs, print a success message.
                 * */
                for (String record : records) {
                    client.writeRecord(record, new WriteOptions(null, null,
                    WritePrecision.S));
                    System.out.printf("Data has been written successfully:
                    %s%n", record);
                }
            }
        }
    }
    

    示例代码执行以下操作

    1. 导入以下类

      • java.util.List;
      • com.influxdb.v3.client.InfluxDBClient
      • com.influxdb.v3.client.write.WriteParameters
      • com.influxdb.v3.client.write.WritePrecision
    2. 调用 InfluxDBClient.getInstance() 以实例化一个配置了 InfluxDB 凭证的客户端。

      • host:您的 InfluxDB 集群 URL
      • database:要写入的 InfluxDB 集群数据库的名称
      • token:一个具有 访问指定数据库的 数据库令牌将其存储在密钥存储或环境变量中,以避免暴露原始令牌字符串。
    3. 定义了一个表示数据记录的行协议字符串列表。

    4. 调用客户端的 writeRecord() 方法将每个记录单独写入 InfluxDB。

      由于示例行协议中的时间戳为秒精度,示例传递了 WritePrecision.S 枚举值 作为 precision 参数,以将写入时间戳的精度设置为秒。

  8. 在您的编辑器中,打开由 Maven 创建的 App.java 文件并替换其内容为以下示例代码

    // App.java
    
    package com.influxdbv3;
    
    /**
    * Execute the client functions.
    *
    */
    public class App {
    
        /**
        * @param args
        * @throws Exception
        */
        public static void main(final String[] args) throws Exception {
            // Write data to InfluxDB v3.
            Write.writeLineProtocol();
        }
    }
    
    • App 类和 Write 类属于同一 com.influxdbv3 包(您的项目 groupId)。
    • App 定义了一个 main() 函数,该函数调用 Write.writeLineProtocol()
  9. 在您的终端或编辑器中,使用 Maven 安装依赖项并编译项目代码——例如

    mvn compile
    
  10. 在您的终端或编辑器中,执行 App.main() 以写入 InfluxDB——例如,使用 Maven

    mvn exec:java -Dexec.mainClass="com.influxdbv3.App"
    

如果成功,输出是成功消息;否则,错误详情和失败消息。

查看已写入的数据

恭喜! 您已将数据写入 InfluxDB。接下来,学习如何查询您的数据。


这个页面有帮助吗?

感谢您的反馈!


Flux 的未来

Flux 正在进入维护模式。您可以继续像现在这样使用它,而无需对您的代码进行任何更改。

阅读更多

InfluxDB v3 增强功能和 InfluxDB 集群现在已公开发布

新功能包括更快的查询性能和管理工具,推动了 InfluxDB v3 产品线的进步。InfluxDB 集群现在已公开发布。

InfluxDB v3 性能和功能

InfluxDB v3 产品线在查询性能方面取得了显著提升,并提供了新的管理工具。这些增强包括一个用于监控 InfluxDB 集群健康状况的操作仪表板、InfluxDB 云专用版中的单点登录 (SSO) 支持,以及用于令牌和数据库的新管理 API。

了解新的 v3 增强功能


InfluxDB 集群公开发布

InfluxDB 集群现在已公开发布,并为您在自管理堆栈中提供了 InfluxDB v3 的功能。

与我们讨论 InfluxDB 集群