如何在 QuestDB 上使用 Influx 行协议避免乱序插入

How do I avoid out of order inserts using Influx line protocol on QuestDB

我正在测试物联网传感器,每个传感器都将温度读数发送到 QuestDB 实例,我在 Python 中使用基本的 TCP 套接字连接来发送它,如下所示:

import datetime as dt
import socket
import Adafruit_DHT

HOST = '127.0.0.1'
PORT = 9009

sensor = Adafruit_DHT.DHT22
pin = 23
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

def now():
  return int((dt.datetime.utcnow() - dt.datetime(1970, 1, 1)).total_seconds() * 1000) * 1000000

while True:
  humidity, temp = Adafruit_DHT.read_retry(sensor, pin)
  if temp is not None:
    try:    
      sock.sendto(('readings,sensor=%s temp=%s %s' % (sensor_name,temp,now())).encode(), (HOST, PORT))
    except socket.error as e:
      print("Got error: %s" % (e))

sock.close()

这可以将数据插入 readings table,但似乎缺少一些读数,我看到了

cannot insert records out of order

您可以在客户端省略时间戳,让服务器分配一个服务器的系统时间。这意味着您可以在示例中摆脱调用 now() 函数:

import socket
import Adafruit_DHT

# maybe an environment variable can identify the IoT device
sensor_name="My sensor"

HOST = '127.0.0.1'
PORT = 9009
sensor = Adafruit_DHT.DHT22
pin = 23

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

while True:
  humidity, temp = Adafruit_DHT.read_retry(sensor, pin)
  if temp is not None:
    try:    
      sock.sendto(('readings,sensor=%s temp=%s' % (sensor_name,temp)).encode(), (HOST, PORT))
    except socket.error as e:
      print("Got error: %s" % (e))

sock.close()