首页 > 解决方案 > httr POST 错误:“数字文字中的无效字符 '-'”

问题描述

我是 Influx 和 R 的新手,我正在尝试在 R Studio 中从 InfluxDB 1.8.4(启用 Flux)查询数据。我无法弄清楚我的代码有什么问题:

dburl <- "http://localhost:8086/api/v2/query"

influxquery <- sprintf(
  'from(bucket: "plcview/autogen")
    |> range(start: 2017-06-27T04:16:58.278Z, stop: now())
    |> filter(fn: (r) => r._measurement == "MONITORING")
    |> map(fn:(r) => ({ r with _time: uint(v:r._time) }))'
)

httr::POST(url=dburl,
           add_headers('Content-Type: application/vnd.flux',
                       'Accept: application/csv',
                       'Accept-Encoding: application/gzip'),
           body=list(q=influxquery))

我试图获取的数据如下所示:

time                     MONITORING equipmentNumber workplace
----                     ---------- --------------- ---------
2017-06-27T02:16:58.599Z 1          L4212M1017      3
2017-06-27T02:16:58.6Z   1          L4212M1017      4
2017-06-27T02:16:58.6Z   1          L4212M1017      1
2017-06-27T02:16:58.6Z   1          L4212M1017      2
2017-06-27T02:17:03.14Z  0          L4212M1017      1
2017-06-27T02:17:03.14Z  0          L4212M1017      2
2017-06-27T02:17:03.14Z  0          L4212M1017      4
2017-06-27T02:17:20.007Z 1          L4212M1017      1
2017-06-27T02:17:36.988Z 1          L4212M1017      4
2017-06-27T02:17:36.988Z 1          L4212M1017      2

我总是收到此错误消息

Response [http://localhost:8086/api/v2/query]
  Date: 2021-04-08 14:19
  Status: 400
  Content-Type: application/json
  Size: 53 B
{"error":"invalid character '-' in numeric literal"}

我可以使用 Postman 推送相同的请求(使用所有这些参数)。为什么它在 R 中不起作用?R存储数据的方式可能有问题吗?我认为它可能是时间戳形式的时间序列数据,格式为 rfc339(其中有“-”来分隔日期。

有任何想法吗?感谢你们!

标签: rinfluxdbhttrinfluxdb-2flux-influxdb

解决方案


由于我将数据库查询作为原始文本发送,但httr::POST函数中没有此参数,因此您需要添加content_type()参数。这确保可以理解查询。它在 POST 请求的正文中指定接下来会发生什么。

这是我的代码:

my_raw_result <- httr::POST(url=dburl,
                            add_headers('Content-Type: application/vnd.flux',
                                        'Accept: application/csv',
                                        'Accept-Encoding: gzip'),
                            content_type("application/vnd.flux"),
                            body=influxquery)

您也不必在请求正文中添加q作为密钥。influxquery仅当您尝试使用 InfluxQL 而不是 Flux 从 InfluxDB v1x 查询数据时才会出现这种情况


推荐阅读