Documentation

开始编写数据

本教程将指导您创建行协议数据并将其写入InfluxDB的基本知识。

InfluxDB 提供多种不同的方法来摄取或写入数据,包括以下内容:

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

如果使用像Telegraf或InfluxDB客户端库这样的工具,它们可以为您构建行协议,但了解行协议是如何工作的很好。

行协议

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

行协议元素

每行行协议包含以下元素:

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

行协议元素解析

  • measurement: 在第一个未转义的逗号之前的第一个空格之前的所有内容。
  • 标签集: 在第一个未转义的逗号第一个未转义的空白字符之间的键值对。
  • 字段集: 在第一个和第二个未转义的空白字符之间的键值对。
  • timestamp: 在第二个未转义空格之后的整数值。
  • 行由换行符分隔 (\n)。行协议对空格敏感。

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


有关架构设计建议,请参阅 InfluxDB 架构设计

构建行协议

通过对行协议的基本理解,您现在可以构建行协议并将数据写入InfluxDB。考虑一个使用案例,您从家中的传感器收集数据。每个传感器收集温度、湿度和一氧化碳读数。要收集这些数据,请使用以下模式:

  • 测量: home
    • 标签
      • room: 客厅或厨房
    • 字段
      • temp: 摄氏度中的温度 (浮点数)
      • hum: 湿度百分比 (浮点数)
      • co: 一百万分之一的空气中一氧化碳含量 (整数)
    • 时间戳: 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

以下示例展示如何将前面的 sample data,已经是行协议格式, 写入到一个InfluxDB集群数据库中。

要了解更多可用的工具和选项,请参阅 Write data

本入门教程中的一些示例假设您的 InfluxDB 凭据(URLorganizationtoken)是通过 环境变量 提供的。

使用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 并配置以下内容:

    • file 输入插件: 在 [[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 集群 指南。

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

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

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

  • 请求头:
    • 授权: Bearer
    • 内容类型: text/plain; charset=utf-8
    • 接受: 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

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

  • 头部:
    • 授权: Bearer
    • 内容类型: text/plain; charset=utf-8
    • 接受: 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 模块,并且还安装了 pyarrow 用于处理从查询返回的 Arrow 数据。

  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 3 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/v2/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: influxdb3.WriteOptions 用于写入 到 InfluxDB 的选项。

          因为示例行协议中的时间戳精度为秒,示例传递了 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}: 一个 WriteOptions 对象,用于设置 precision 值。

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

    5. 调用 Promise.allSettled() 与 promises 数组来暂停执行,直到 promises 完成,然后将包含成功和失败消息的数组分配给 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 3 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 创建了 目录 (./influxdb_java_client),该目录包含一个 pom.xml 和用于你的 com.influxdbv3.influxdb_java_client Java 应用程序的构建框架。

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

    cd ./influxdb_java_client
    
  4. 在你的编辑器中,打开pom.xml Maven配置文件,并将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 3.
        */
        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. 在你的编辑器中,打开 App.java 文件(由 Maven 创建)并用以下示例代码替换其内容:

    // 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 3.
            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 3 开源版本现已公开Alpha测试

InfluxDB 3 Open Source is now available for alpha testing, licensed under MIT or Apache 2 licensing.

我们将发布两个产品作为测试版的一部分。

InfluxDB 3 核心,是我们新的开源产品。 它是一个用于时间序列和事件数据的实时数据引擎。 InfluxDB 3 企业版是建立在核心基础之上的商业版本,增加了历史查询能力、读取副本、高可用性、可扩展性和细粒度安全性。

有关如何开始的更多信息,请查看: