InfluxDB Documentation
InfluxDB Documentation
Release 5.3.1
John Shahid
1 Contents 3
1.1 InfluxDB-Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 InfluxDB-Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 API Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2.1 InfluxDBClient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2.2 DataFrameClient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.2.3 SeriesHelper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.2.4 ResultSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.3 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.4 Query response object: ResultSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.4.1 Getting all points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.4.2 Filtering by measurement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.4.3 Filtering by tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.4.4 Filtering by measurement and tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.5 InfluxDB Python Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.5.1 Tutorials - Basic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.5.2 Tutorials - pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.5.3 Tutorials - SeriesHelper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.5.4 Tutorials - UDP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.5.5 Tutorials - Authorization by Token . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
i
ii
InfluxDB Documentation, Release 5.3.1
Release 5.3.1
Date Nov 15, 2022
Keywords python, time series, database
Contents 1
InfluxDB Documentation, Release 5.3.1
2 Contents
CHAPTER 1
Contents
1.1 InfluxDB-Python
The v1 client libraries for InfluxDB were typically developed and maintained by community members. They have
all now been succeeded by v2 client libraries. They are being archived it in favor of the v2 client library. See
https://github.com/influxdata/influxdb-python/issues/918.
If there are still users of this v1 client library, and they or somebody else are willing to keep them updated with security
fixes at a minimum please reach out on the [Community Forums](https://community.influxdata.com/) or [InfluxData
Slack](https://influxdata.com/slack).
1.1.1 InfluxDB-Python
This module is tested with InfluxDB versions: v1.2.4, v1.3.9, v1.4.3, v1.5.4, v1.6.4, and 1.7.4.
Those users still on InfluxDB v0.8.x users may still use the legacy client by importing from influxdb.
influxdb08 import InfluxDBClient.
3
InfluxDB Documentation, Release 5.3.1
Installation
Dependencies
The influxdb-python distribution is supported and tested on Python 2.7, 3.5, 3.6, 3.7, PyPy and PyPy3.
Note: Python <3.5 are currently untested. See .travis.yml.
Main dependency is:
• Requests: HTTP library for human beings (http://docs.python-requests.org/)
Additional dependencies are:
• pandas: for writing from and reading to DataFrames (http://pandas.pydata.org/)
• Sphinx: Tool to create and manage the documentation (http://sphinx-doc.org/)
• Nose: to auto-discover tests (http://nose.readthedocs.org/en/latest/)
• Mock: to mock tests (https://pypi.python.org/pypi/mock)
Documentation
$ tox -e docs
Examples
$ python
>>> json_body = [
{
"measurement": "cpu_load_short",
"tags": {
"host": "server01",
"region": "us-west"
4 Chapter 1. Contents
InfluxDB Documentation, Release 5.3.1
},
"time": "2009-11-10T23:00:00Z",
"fields": {
"value": 0.64
}
}
]
>>> client.create_database('example')
>>> client.write_points(json_body)
Testing
To test influxdb-python with multiple version of Python, you can use Tox:
$ tox
Support
For issues with, questions about, or feedback for InfluxDB, please look into our community page: http://influxdb.com/
community/.
We are also lurking on the following:
• #influxdb on irc.freenode.net
• #influxdb on gophers.slack.com
Development
All development is done on Github. Use Issues to report problems or submit contributions.
Please note that we WILL get to your questions/issues/concerns as quickly as possible. We maintain many software
repositories and sometimes things may get pushed to the backburner. Please don’t take offense, we will do our best to
reply as soon as possible!
Source code
1.1. InfluxDB-Python 5
InfluxDB Documentation, Release 5.3.1
TODO
To connect to a InfluxDB, you must create a InfluxDBClient object. The default configuration connects to
InfluxDB on localhost with the default ports. The below instantiation statements are all equivalent:
# using Http
client = InfluxDBClient(database='dbname')
client = InfluxDBClient(host='127.0.0.1', port=8086, database='dbname')
client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root',
˓→ database='dbname')
# using UDP
client = InfluxDBClient(host='127.0.0.1', database='dbname', use_udp=True, udp_
˓→port=4444)
To write pandas DataFrames or to read data into a pandas DataFrame, use a DataFrameClient object. These
clients are initiated in the same way as the InfluxDBClient:
1.2.1 InfluxDBClient
6 Chapter 1. Contents
InfluxDB Documentation, Release 5.3.1
Note: at least one of duration, replication, or default flag should be set. Otherwise the operation will fail.
close()
Close http session.
create_continuous_query(name, select, database=None, resample_opts=None)
Create a continuous query for a database.
Parameters
• name (str) – the name of continuous query to create
• select (str) – select statement for the continuous query
• database (str) – the database for which the continuous query is created. Defaults to
current client’s database
• resample_opts (str) – resample options
Example
create_database(dbname)
Create a new database in InfluxDB.
Parameters dbname (str) – the name of the database to create
create_retention_policy(name, duration, replication, database=None, default=False,
shard_duration=u‘0s’)
Create a retention policy for a database.
Parameters
• name (str) – the name of the new retention policy
• duration (str) – the duration of the new retention policy. Durations such as 1h, 90m,
12h, 7d, and 4w, are all supported and mean 1 hour, 90 minutes, 12 hours, 7 day, and 4
weeks, respectively. For infinite retention - meaning the data will never be deleted - use
‘INF’ for duration. The minimum retention period is 1 hour.
8 Chapter 1. Contents
InfluxDB Documentation, Release 5.3.1
Note: when using “udp+influxdb” the specified port (if any) will be used for the TCP connection; specify
the UDP port with the additional udp_port parameter (cf. examples).
get_list_continuous_queries()
Get the list of continuous queries in InfluxDB.
Returns all CQs in InfluxDB
Return type list of dictionaries
Example
10 Chapter 1. Contents
InfluxDB Documentation, Release 5.3.1
u'name': u'vampire',
u'query': u'CREATE CONTINUOUS QUERY vampire ON '
'mydb BEGIN SELECT count(dracula) INTO '
'mydb.autogen.all_of_them FROM '
'mydb.autogen.one GROUP BY time(5m) END'
}
]
}
]
get_list_database()
Get the list of databases in InfluxDB.
Returns all databases in InfluxDB
Return type list of dictionaries
Example
get_list_measurements()
Get the list of measurements in InfluxDB.
Returns all measurements in InfluxDB
Return type list of dictionaries
Example
get_list_privileges(username)
Get the list of all privileges granted to given user.
Parameters username (str) – the username to get privileges of
Returns all privileges granted to given user
Return type list of dictionaries
Example
get_list_retention_policies(database=None)
Get the list of retention policies for a database.
Parameters database (str) – the name of the database, defaults to the client’s current
database
Returns all retention policies for the database
grant_admin_privileges(username)
Grant cluster administration privileges to a user.
Parameters username (str) – the username to grant privileges to
Note: Only a cluster administrator can create/drop databases and manage users.
12 Chapter 1. Contents
InfluxDB Documentation, Release 5.3.1
Danger: In order to avoid injection vulnerabilities (similar to SQL injection vulnerabilities), do not
directly include untrusted data into the query parameter, use bind_params instead.
Parameters
• query (str) – the actual query string
• params (dict) – additional parameters for the request, defaults to {}
• bind_params (dict) – bind parameters for the query: any variable in the query written
as '$var_name' will be replaced with bind_params['var_name']. Only works
in the WHERE clause and takes precedence over params['params']
• epoch (str) – response timestamps to be in epoch format either ‘h’, ‘m’, ‘s’, ‘ms’, ‘u’,
or ‘ns’,defaults to None which is RFC3339 UTC format with nanosecond precision
• expected_response_code (int) – the expected status code of response, defaults to
200
• database (str) – database to query, defaults to None
• raise_errors (bool) – Whether or not to raise exceptions when InfluxDB returns
errors, defaults to True
• chunked (bool) – Enable to use chunked responses from InfluxDB. With chunked
enabled, one ResultSet is returned per chunk containing all results within that chunk
• chunk_size (int) – Size of each chunk to tell InfluxDB to use.
• method (str) – the HTTP method for the request, defaults to GET
Returns the queried data
Return type ResultSet
Raises
• InfluxDBServerError – if the response code is any server error code (5xx)
• InfluxDBClientError – if the response code is not the same as ex-
pected_response_code and is not a server error code
revoke_admin_privileges(username)
Revoke cluster administration privileges from a user.
Parameters username (str) – the username to revoke privileges from
Note: Only a cluster administrator can create/ drop databases and manage users.
14 Chapter 1. Contents
InfluxDB Documentation, Release 5.3.1
Note: if no retention policy is specified, the default retention policy for the database is used
1.2.2 DataFrameClient
Danger: In order to avoid injection vulnerabilities (similar to SQL injection vulnerabilities), do not
directly include untrusted data into the query parameter, use bind_params instead.
Parameters
• query – the actual query string
• params – additional parameters for the request, defaults to {}
• bind_params – bind parameters for the query: any variable in the query written as
'$var_name' will be replaced with bind_params['var_name']. Only works in
the WHERE clause and takes precedence over params['params']
• epoch – response timestamps to be in epoch format either ‘h’, ‘m’, ‘s’, ‘ms’, ‘u’, or
‘ns’,defaults to None which is RFC3339 UTC format with nanosecond precision
• expected_response_code – the expected status code of response, defaults to 200
• database – database to query, defaults to None
• raise_errors – Whether or not to raise exceptions when InfluxDB returns errors,
defaults to True
• chunked – Enable to use chunked responses from InfluxDB. With chunked enabled,
one ResultSet is returned per chunk containing all results within that chunk
• chunk_size – Size of each chunk to tell InfluxDB to use.
• dropna – drop columns where all values are missing
• data_frame_index – the list of columns that are used as DataFrame index
Returns the queried data
Return type ResultSet
16 Chapter 1. Contents
InfluxDB Documentation, Release 5.3.1
1.2.3 SeriesHelper
class influxdb.SeriesHelper(**kw)
Subclass this helper eases writing data points in bulk.
All data points are immutable, ensuring they do not get overwritten. Each subclass can write to its own database.
The time series names can also be based on one or more defined fields. The field “time” can be specified when
creating a point, and may be any of the time types supported by the client (i.e. str, datetime, int). If the time is
not specified, the current system time (utc) will be used.
Annotated example:
class MySeriesHelper(SeriesHelper):
class Meta:
# Meta class stores time series helper configuration.
series_name = 'events.stats.{server_name}'
# Series name must be a string, curly brackets for dynamic use.
fields = ['time', 'server_name']
# Defines all the fields in this time series.
### Following attributes are optional. ###
client = TestSeriesHelper.client
# Client should be an instance of InfluxDBClient.
:warning: Only used if autocommit is True.
bulk_size = 5
# Defines the number of data points to write simultaneously.
# Only applicable if autocommit is True.
autocommit = True
# If True and no bulk_size, then will set bulk_size to 1.
retention_policy = 'your_retention_policy'
# Specify the retention policy for the data points
time_precision = "h"|"m"|s"|"ms"|"u"|"ns"
# Default is ns (nanoseconds)
# Setting time precision while writing point
# You should also make sure time is set in the given precision
classmethod commit(client=None)
Commit everything from datapoints via the client.
Parameters client – InfluxDBClient instance for writing points to InfluxDB.
Attention any provided client will supersede the class client.
Returns result of client.write_points.
1.2.4 ResultSet
See the Query response object: ResultSet page for more information.
class influxdb.resultset.ResultSet(series, raise_errors=True)
A wrapper around a single InfluxDB query result.
error
Error returned by InfluxDB.
get_points(measurement=None, tags=None)
Return a generator for all the points that match the given filters.
Parameters
• measurement (str) – The measurement name
• tags (dict) – Tags to look for
Returns Points generator
items()
Return the set of items from the ResultSet.
Returns List of tuples, (key, generator)
keys()
Return the list of keys in the ResultSet.
Returns List of keys. Keys are tuples (series_name, tags)
static point_from_cols_vals(cols, vals)
Create a dict from columns and values lists.
Parameters
• cols – List of columns
• vals – List of values
Returns Dict where keys are columns.
raw
Raw JSON from InfluxDB.
1.3 Exceptions
Using rs.get_points() will return a generator for all the points in the ResultSet.
18 Chapter 1. Contents
InfluxDB Documentation, Release 5.3.1
Using rs.get_points('cpu') will return a generator for all the points that are in a series with measurement
name cpu, no matter the tags.
rs = cli.query("SELECT * from cpu")
cpu_points = list(rs.get_points(measurement='cpu'))
Using measurement name and tags will return a generator for all the points that are in a series with the specified
measurement name AND whose tags match the given tags.
rs = cli.query("SELECT * from cpu")
points = list(rs.get_points(measurement='cpu', tags={'host_name': 'influxdb.com'}))
4 import argparse
5
23 "host": "server01",
24 "region": "us-west"
25 },
26 "time": "2009-11-10T23:00:00Z",
27 "fields": {
28 "Float_value": 0.64,
29 "Int_value": 3,
30 "String_value": "Text",
31 "Bool_value": True
32 }
33 }
34 ]
35
53 print("Result: {0}".format(result))
54
58 print("Result: {0}".format(result))
59
66
67 def parse_args():
68 """Parse the args."""
69 parser = argparse.ArgumentParser(
70 description='example code to play with InfluxDB')
71 parser.add_argument('--host', type=str, required=False,
72 default='localhost',
73 help='hostname of InfluxDB http API')
74 parser.add_argument('--port', type=int, required=False, default=8086,
75 help='port of InfluxDB http API')
76 return parser.parse_args()
77
78
79 if __name__ == '__main__':
80 args = parse_args()
20 Chapter 1. Contents
InfluxDB Documentation, Release 5.3.1
81 main(host=args.host, port=args.port)
import argparse
import pandas as pd
print("Write DataFrame")
client.write_points(df, 'demo', protocol=protocol)
print("Read DataFrame")
client.query("select * from demo")
def parse_args():
"""Parse the args from main."""
parser = argparse.ArgumentParser(
description='example code to play with InfluxDB')
parser.add_argument('--host', type=str, required=False,
default='localhost',
help='hostname of InfluxDB http API')
parser.add_argument('--port', type=int, required=False, default=8086,
help='port of InfluxDB http API')
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
main(host=args.host, port=args.port)
class MySeriesHelper(SeriesHelper):
"""Instantiate SeriesHelper to write points to the backend."""
class Meta:
"""Meta class stores time series helper configuration."""
22 Chapter 1. Contents
InfluxDB Documentation, Release 5.3.1
# To manually submit data points which are not yet written, call commit:
MySeriesHelper.commit()
"""
INFO: In order to use UDP, one should enable the UDP service from the
`influxdb.conf` under section
[[udp]]
enabled = true
bind-address = ":8089" # port number for sending data via UDP
database = "udp1" # name of database to be stored
[[udp]]
enabled = true
bind-address = ":8090"
database = "udp2"
"""
import argparse
def main(uport):
"""Instantiate connection to the InfluxDB."""
# NOTE: structure of the UDP packet is different than that of information
# sent via HTTP
json_body = {
"tags": {
"host": "server01",
"region": "us-west"
},
"points": [{
"measurement": "cpu_load_short",
"fields": {
"value": 0.64
},
"time": "2009-11-10T23:00:00Z",
},
{
"measurement": "cpu_load_short",
"fields": {
"value": 0.67
},
"time": "2009-11-10T23:05:00Z"
}]
}
# make `use_udp` True and add `udp_port` number from `influxdb.conf` file
# no need to mention the database name since it is already configured
client = InfluxDBClient(use_udp=True, udp_port=uport)
def parse_args():
"""Parse the args."""
parser = argparse.ArgumentParser(
description='example code to play with InfluxDB along with UDP Port')
parser.add_argument('--uport', type=int, required=True,
help=' UDP port of InfluxDB')
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
main(uport=args.uport)
import argparse
from influxdb import InfluxDBClient
def main(token='my-token'):
"""Instantiate a connection to the InfluxDB."""
client = InfluxDBClient(username=None, password=None,
headers={"Authorization": token})
version = client.ping()
print("Successfully connected to InfluxDB: " + version)
pass
def parse_args():
"""Parse the args from main."""
parser = argparse.ArgumentParser(
description='example code to play with InfluxDB')
parser.add_argument('--token', type=str, required=False,
default='my-token',
help='Authorization token for the proxy that is ahead the
˓→InfluxDB.')
24 Chapter 1. Contents
InfluxDB Documentation, Release 5.3.1
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
main(token=args.token)
26 Chapter 1. Contents
CHAPTER 2
• genindex
• search
27
InfluxDB Documentation, Release 5.3.1
29
InfluxDB Documentation, Release 5.3.1
W
write() (influxdb.InfluxDBClient method), 14
write_points() (influxdb.DataFrameClient method), 16
write_points() (influxdb.InfluxDBClient method), 15
30 Index