InfluxDB 3 的 Go 客户端库
InfluxDB 3 influxdb3-go Go 客户端库 与 Go 脚本和应用程序集成,以写入和查询存储在 InfluxDB 集群数据库中的数据。
安装
go get github.com/InfluxCommunity/influxdb3-go/v2
导入包
该 influxdb3-go 客户端库模块提供了 influxdb3 包。
导入包:
import (
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
API 参考
函数 New
创建一个客户端以与 InfluxDB 交互。
语法
New(config ClientConfig)
初始化并返回一个 influxdb3.Client 实例,包含以下内容:
- 用于写入数据库的配置和函数。
- A
*flight.Client和用于查询数据库的函数。
参数
config: 一个ClientConfig结构体,具有以下配置属性:Host(string): the InfluxDB Clustered server URLToken(string): a database token stringDatabase(string): the database to use for writing and querying.Organization(string): Optional. The organization name or ID.HTTPClient(*http.Client): Optional. Specifies a custom HTTP client, TLS configuration, or timeout to use.WriteOptions(*WriteOptions): Optional. Options passed to the write client for writing to the database.Headers(http.Header): Optional. Headers to include in all requests.
示例
创建一个 InfluxDB 客户端
package main
import (
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
)
func main() {
client, err := influxdb3.New(influxdb3.ClientConfig{
Host: "https://cluster-host.com",
Token: "DATABASE_TOKEN",
Database: "DATABASE_NAME",
})
defer func(client *influxdb3.Client) {
err := client.Close()
if err != nil {
panic(err)
}
}(client)
if(err != nil) {
panic(err)
}
}
替换以下配置值:
类 influxdb3.Client
函数 Client.Query()
使用SQL从InfluxDB 3查询数据。
语法
client.Query(ctx context.Context, query string)
向InfluxDB发送带有SQL的航班查询请求。
返回以下内容:
- 一个自定义迭代器 (*QueryIterator),用于访问查询结果数据和元数据。
- 如果有错误。
参数
ctx(context.Context): 请求使用的上下文query(字符串):要执行的 SQL 查询。
示例
使用SQL查询
query := `SELECT *
FROM home
WHERE time >= '2022-01-02T08:00:00Z'
AND time <= '2022-01-02T20:00:00Z'`
iterator, err := client.Query(context.Background(), query)
函数 Client.QueryWithOptions()
从 InfluxDB 3 查询数据,带有查询选项,例如 查询类型 用于使用 InfluxQL 查询。
语法
client.QueryWithOptions(ctx context.Context, options *QueryOptions, query string)
向InfluxDB发送带有指定查询选项的查询请求。
返回以下内容:
- 一个自定义迭代器 (*QueryIterator),用于访问查询结果数据和元数据。
- 如果有错误的话。
参数
ctx(context.Context): 请求所使用的上下文options: 查询选项(查询类型, 可选数据库)query(string): 要执行的 SQL 或 InfluxQL 查询。
示例
使用 InfluxQL 查询
query := `SELECT *
FROM home
WHERE time >= 1641124000s
AND time <= 1641124000s + 8h`
queryOptions := influxdb3.QueryOptions{QueryType: influxdb3.InfluxQL}
iterator, err := client.QueryWithOptions(context.Background(), &queryOptions, query)