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()

相关推荐
CodexDave12 小时前
Python 自动化接单实战(一):把 CSV 需求做成配置驱动解析器
java·python·自动化·json·数据清洗·python自动化·csv处理
Y38153266212 小时前
2026 年 7 月,SERP API 调用的稳定性实战:超时、重试、降级
开发语言·数据库·人工智能·php
sugar__salt12 小时前
向量数据库从零到实战:用 Milvus + Zilliz 构建 AI 日记语义检索系统
数据库·人工智能·embedding·milvus·rag·zilliz
m沐沐12 小时前
【深度学习】循环神经网络RNN——结构、原理与长期依赖问题解析
人工智能·pytorch·python·rnn·深度学习·算法·机器学习
风吹心凉12 小时前
python3基础2026.7.28
开发语言·python
Gauss松鼠会12 小时前
Prometheus 实现 openGauss 的指标监控(二)Prometheus 中添加 openGauss指标
网络·数据库·oracle·prometheus·opengauss·经验总结
曲无忆12 小时前
LLMs赋能依赖类型证明自动化
python
Cloud云卷云舒13 小时前
PolarDB(阿里云)VS HaishanDB(海山数据库,移动云)的AI能力全面对比
数据库·阿里云·ai-native·polardb·haishandb
一次旅行13 小时前
act本地预跑GitHub Actions:Python项目完整CI/CD流水线实战
python·ci/cd·github
玉鸯13 小时前
RAG 全链路调优指南:从 Chunking 到 Reranker
python·llm·agent