writeApi.writeRecords 和writeApi.writePoints 怎么使用
时间: 2023-12-13 11:03:55 浏览: 45
`writeApi.writeRecords` 和 `writeApi.writePoints` 是InfluxDB 2.x中用于向InfluxDB写入数据的API方法。
`writeApi.writeRecords` 方法是将记录作为JSON数组写入InfluxDB。每个JSON对象都表示一个记录,其中可以包含多个字段和标记。
`writeApi.writePoints` 方法是将记录作为InfluxDB Line Protocol格式写入。每个记录都表示为单行字符串,其中包含测量名称、标记、字段和时间戳等信息。
下面是使用这两个方法向InfluxDB写入数据的示例:
```python
from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS
# 创建InfluxDB客户端
client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org")
# 获取写API
write_api = client.write_api(write_options=SYNCHRONOUS)
# 使用 writeRecords 方法写入数据
records = [
{"measurement": "temperature", "tags": {"location": "room1"}, "fields": {"value": 20.5}},
{"measurement": "temperature", "tags": {"location": "room2"}, "fields": {"value": 21.2}},
{"measurement": "humidity", "tags": {"location": "room1"}, "fields": {"value": 55}},
{"measurement": "humidity", "tags": {"location": "room2"}, "fields": {"value": 50.6}},
]
write_api.write_records(bucket="my-bucket", org="my-org", record=records)
# 使用 writePoints 方法写入数据
point1 = Point("temperature").tag("location", "room1").field("value", 20.5).time(1626123019000000000, WritePrecision.NS)
point2 = Point("temperature").tag("location", "room2").field("value", 21.2).time(1626123020000000000, WritePrecision.NS)
point3 = Point("humidity").tag("location", "room1").field("value", 55).time(1626123019000000000, WritePrecision.NS)
point4 = Point("humidity").tag("location", "room2").field("value", 50.6).time(1626123020000000000, WritePrecision.NS)
write_api.write(bucket="my-bucket", org="my-org", record=[point1, point2, point3, point4])
```
注意,`writeApi.writePoints` 方法需要使用 `Point` 对象来表示每个记录,并在创建 `Point` 对象时指定测量名称、标记、字段和时间戳等信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)