How to Use Python to Manage InfluxDB 2.0

Jobin J
4 min readJul 2, 2024

--

InfluxDB 2.0 is a powerful time-series database that offers enhanced capabilities and a new query language called Flux. In this blog, we’ll walk through how to manage InfluxDB 2.0 using Python.

Prerequisites

1. InfluxDB 2.0: Ensure you have InfluxDB 2.0 installed : https://medium.com/@techworldthink/installing-influxdb-v2-with-docker-on-ubuntu-39a974c3cb40

2. Python Environment: Make sure you have Python installed. We will use the influxdb-client Python library.

Libraries Install

First, install the influxdb-client library which allows Python to interact with InfluxDB 2.0.

pip install influxdb-client

Comprehensive Walkthrough

1. Connect to InfluxDB

We’ll connect to InfluxDB running on localhost. If you are running InfluxDB on a different host, update the host address accordingly. Make sure you have the token, organization, and bucket details.

from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client .client.write_api import SYNCHRONOUS

# Define the connection details
url = "http://localhost:8086"
token = "your_token"
org = "your_org"
bucket = "example_bucket"

# Connect to InfluxDB
client = InfluxDBClient(url=url, token=token, org=org)

2. Create a Bucket

A bucket in InfluxDB 2.0 is similar to a database in InfluxDB 1.8. Here, we’ll create a bucket named example_bucket.

# Create a bucket
buckets_api = client.buckets_api()
bucket_object = buckets_api.create_bucket(bucket_name=bucket, org=org)

3. Write Data

Let’s write some sample data into a measurement called temperature.

# Prepare data to be written
write_api = client.write_api(write_options=SYNCHRONOUS)

data = [
Point("temperature").tag("location", "office").field("value", 23.5).time("2024-07-01T00:00:00Z", WritePrecision.NS),
Point("temperature").tag("location", "lab").field("value", 22.0).time("2024-07-01T01:00:00Z", WritePrecision.NS)
]

# Write data
write_api.write(bucket=bucket, org=org, record=data)

4. Query Data

Now, let’s query the data we just inserted using Flux.

# Query data
query_api = client.query_api()
query = f'from(bucket: "{bucket}") |> range(start: -10y) |> filter(fn: (r) => r._measurement == "temperature" and r.location == "office")'
result = query_api.query(org=org, query=query)

# Print results
for table in result:
for record in table.records:
print(record.values)

Output :

{'result': '_result', 'table': 0, '_start': datetime.datetime(2014, 7, 3, 4, 51, 6, 846536, tzinfo=datetime.timezone.utc), '_stop': datetime.datetime(2024, 7, 2, 16, 51, 6, 846536, tzinfo=datetime.timezone.utc), '_time': datetime.datetime(2023, 1, 1, 0, 0, tzinfo=datetime.timezone.utc), '_value': 23.5, '_field': 'value', '_measurement': 'temperature', 'location': 'office'}

5. Delete Data

Suppose we want to delete the temperature data from the lab location. We can do this with a delete API.

from influxdb_client.client.write_api import SYNCHRONOUS

# Delete data with condition
start = "2023-01-01T00:00:00Z"
stop = "2023-01-01T02:00:00Z"
delete_api = client.delete_api()
delete_api.delete(start, stop, '_measurement="temperature" AND location="lab"', bucket=bucket, org=org)

6. Verify Deletion

To ensure the data has been deleted, we can query the database again.

# Query data to verify deletion
result_after_deletion = query_api.query(org=org, query=query)
print("Result after deletion:")
for table in result_after_deletion:
for record in table.records:
print(record.values)

Output :

Result after deletion:
{'result': '_result', 'table': 0, '_start': datetime.datetime(2014, 7, 3, 5, 1, 13, 718405, tzinfo=datetime.timezone.utc), '_stop': datetime.datetime(2024, 7, 2, 17, 1, 13, 718405, tzinfo=datetime.timezone.utc), '_time': datetime.datetime(2024, 7, 1, 0, 0, tzinfo=datetime.timezone.utc), '_value': 23.5, '_field': 'value', '_measurement': 'temperature', 'location': 'office'}

7. Clean Up

After finishing our tasks, we can delete the temporary bucket we created for learning to keep things clean

# Delete the bucket using its ID
bucket_id = bucket_object.id
buckets_api.delete_bucket(bucket_id)

8. Close the Connection

Finally, always close the connection to the InfluxDB server when done.

# Close the connection
client.close()

Complete Code

Here is the complete code for managing InfluxDB 2.0 with Python

from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client .client.write_api import SYNCHRONOUS

# Define the connection details
url = "http://localhost:8086"
token = "your_token"
org = "your_org"
bucket = "example_bucket"

# Connect to InfluxDB
client = InfluxDBClient(url=url, token=token, org=org)

# Create a bucket
buckets_api = client.buckets_api()
bucket_object = buckets_api.create_bucket(bucket_name=bucket, org=org)

# Prepare data to be written
write_api = client.write_api(write_options=SYNCHRONOUS)
data = [
Point("temperature").tag("location", "office").field("value", 23.5).time("2024-07-01T00:00:00Z", WritePrecision.NS),
Point("temperature").tag("location", "lab").field("value", 22.0).time("2024-07-01T01:00:00Z", WritePrecision.NS)
]

# Write data
write_api.write(bucket=bucket, org=org, record=data)

# Query data
query_api = client.query_api()
query = f'from(bucket: "{bucket}") |> range(start: -10y) |> filter(fn: (r) => r._measurement == "temperature" and r.location == "office")'
result = query_api.query(org=org, query=query)

# Print results
print("Result:")
for table in result:
for record in table.records:
print(record.values)

# Delete data with condition
start = "2023-01-01T00:00:00Z"
stop = "2024-08-01T02:00:00Z"
delete_api = client.delete_api()
delete_api.delete(start, stop, '_measurement="temperature" AND location="lab"', bucket=bucket, org=org)

# Query data to verify deletion
result_after_deletion = query_api.query(org=org, query=query)
print("Result after deletion:")
for table in result_after_deletion:
for record in table.records:
print(record.values)

# Delete the bucket using its ID
bucket_id = bucket_object.id
buckets_api.delete_bucket(bucket_id)

# Close the connection
client.close()

Running the Script

Save the above code to a file, say influxdb2_manage.py, and run it using Python:

python influxdb2_manage.py

That’s it! You have now successfully managed InfluxDB 2.0 using Python. This guide covered connecting to InfluxDB, creating a bucket, writing data, querying data, deleting data, and finally cleaning up by removing the bucket. Happy coding!

--

--