influxdb时序库之Python操作

使用Python操作influxdb时序库

1. 安装三方库

注意区分版本,不同的 influxdb 版本对应安装不同的三方库。

influxdb V1:pip install influxdb

influxdb V2:pip install influxdb-client

以下代码都是基于 influxdb 2.4 版本进行操作。

2. 实例化client对象

python 复制代码
from datetime import datetime
from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS

token = "H9GXI_bvLHkbRWBR1bYZVZlm5_b282iSDU6EpfxL2tbux6Qp6jcpQqxLpp01KE6EZIdWGkpoMS_PoHe-I-jaDg=="
org = "influx_test"
bucket = "example_dbquery"

# 实例化influxdb client对象,建立连接
db_client = InfluxDBClient(url="http://192.168.1.6:8086", token=token, org=org)
# 写操作
write_api = db_client.write_api(write_options=SYNCHRONOUS)
# 读操作
query_api = db_client.query_api()

3. 写操作

Data Point 方式写数据时,要注意 field 对应的数据类型为int 还是 double.

python 复制代码
# 写操作
write_api = db_client.write_api(write_options=SYNCHRONOUS)

# 方式1. 行协议方式写数据
data = 'car,code=01 rate=38,temp=26'
write_api.write(bucket, org, data)

# 方式2. 数据点方式写数据
point = Point("car") \
    .tag("code", "01") \
    .field("rate", 39.2).field("temp", 28.5) \
    .time(datetime.utcnow(), WritePrecision.NS)
write_api.write(bucket, org, point)

# 方式3. 批量行协议方式写数据
sequence = [
    'car,code=01 rate=40,temp=25',
    'car,code=02 rate=45,temp=30',
]
write_api.write(bucket, org, sequence)

4. 查数据

influxdb版本不同,查询语句也不一样,以下基于 influxdb 2.4 实现。

python 复制代码
# 读操作
query_api = db_client.query_api()

query_info = 'from(bucket: "example_dbquery") |> range(start: -1h)'
tables = query_api.query(query_info, org=org)       # 相当于查到的所有序列,(_measurement + tag + _field 为一组series,即一组序列)

for tb in tables:
    print(f"---------tb: {tb}")
    for record in tb.records:           # 循环每个序列中的每条记录,即每个point
        print(record)

5. 关闭连接

db_client .close()

相关推荐
AIAdvocate1 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼1 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
高兴就好(石2 小时前
DB-GPT部署和试用
数据库·gpt
这孩子叫逆3 小时前
6. 什么是MySQL的事务?如何在Java中使用Connection接口管理事务?
数据库·mysql
Karoku0663 小时前
【网站架构部署与优化】web服务与http协议
linux·运维·服务器·数据库·http·架构
码农郁郁久居人下3 小时前
Redis的配置与优化
数据库·redis·缓存
FreakStudio3 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy
MuseLss4 小时前
Mycat搭建分库分表
数据库·mycat
redcocal4 小时前
地平线秋招
python·嵌入式硬件·算法·fpga开发·求职招聘
Hsu_kk5 小时前
Redis 主从复制配置教程
数据库·redis·缓存