美文网首页
influxdb使用笔记

influxdb使用笔记

作者: 魂狩 | 来源:发表于2019-11-22 11:31 被阅读0次

安装方式

#ubuntu下
curl -sL https://repos.influxdata.com/influxdb.key | sudo apt-key add -
source /etc/lsb-release
echo "deb https://repos.influxdata.com/${DISTRIB_ID,,} ${DISTRIB_CODENAME} stable" | sudo tee /etc/apt/sources.list.d/influxdb.list
apt update
apt-get install influxdb

配置文件位于/etc/influxdb/influxdb.conf

重要语句:

  • CREATE USER admin WITH PASSWORD 'admin' WITH ALL PRIVILEGES
  • create database test

笔记

  • 在服务器端创建数据库后,表(measurement)不需要手动添加,添加数据时会自动处理。
  • 表字段可以动态添加,添加字段后原有数据也会自动加上这个字段,值为空。
  • 请求基本和sql一致,没有between关键字,有ordersum等方法。
  • 时间相关:influxdb时间字段格式为ISO 8601。php中使用date("c")来获取时间,python3不能直接获取,datetime.datetime.utcnow().isoformat()获取时间后,最后还需要添加Z表明时区(必须是大写的Z)。
  • 请求语句中单引号为分隔符,双引号为普通字符,不能作为字符串标识。字符串、日期等只能用单引号包裹。
  • count语句和sql语句不一样。因为字段是动态的,所以count(*)返回的是每个字段的统计,如SELECT count(*) FROM hello where time >= '2019-11-18T00:00:00+08:00' and time < '2019-11-23T00:00:00+08:00' group by time(1d)返回的22号当天结果是{'time': '2019-11-22T00:00:00+08:00', 'count_age': 8, 'count_name': 8, 'count_test': 1}。原始数据我只有一条添加了test字段。没有数据的日期,数据都是0。
  • sum语句,如果对应时间段没有数据,返回的结果是空而不是0。

简单demo:

from influxdb import InfluxDBClient
import datetime
client = InfluxDBClient('10.10.10.10', 8086, 'admin', 'admin', 'test') # ip 端口 用户名 密码 数据库名
body = [
    {
        "measurement": "hello",
        "tags": {
            "class": 1
        },
        "fields": {
            "name": "Hyc",
            "age": 3
        },
    }
]
client.write_points(body)
t=datetime.datetime.utcnow().isoformat()+'z'
result = client.query("select * from hello where time < '%s' order by time desc"%t)
t=result.get_points()
for x in t:
    print(x)
 #聚合时可以选择按天,中国时区,这样可以避免结果多一天的情况
result = client.query("SELECT count(age) FROM hello where time >= '2019-10-18T00:00:00+08:00' and time < '2019-10-23T00:00:00+08:00' group by time(1d) TZ('Asia/Shanghai')")
t=result.get_points()
for x in t:
    print(x)

相关文章

网友评论

      本文标题:influxdb使用笔记

      本文链接:https://www.haomeiwen.com/subject/ekbfwctx.html