InfluxDB 2 Go Client
This repository contains the Go client library for use with InfluxDB 2.x and Flux. InfluxDB 3.x users should instead use the lightweight v3 client library. InfluxDB 1.x users should use the v1 client library.
For ease of migration and a consistent query and write experience, v2 users should consider using InfluxQL and the v1 client library.
This section contains links to the client library documentation.
Examples for basic writing and querying data are shown below in this document
There are also other examples in the API docs:
Go 1.17 or later is required.
go get github.com/influxdata/influxdb-client-go/v2
github.com/influxdata/influxdb-client-go/v2 to your source code.go get github.com/influxdata/influxdb-client-go
Note: To have go get in the GOPATH mode, the environment variable GO111MODULE must have the off value.
The following example demonstrates how to write data to InfluxDB 2 and read them back using the Flux language:
…
The InfluxDBClient uses set of options to configure behavior. These are available in the Options object Creating a client instance using
client := influxdb2.NewClient("http://localhost:8086", "my-token")
will use the default options.
To set different configuration values, e.g. to set gzip compression and trust all server certificates, get default options and change what is needed:
client := influxdb2.NewClientWithOptions("http://localhost:8086", "my-token",
influxdb2.DefaultOptions().
SetUseGZip(true).
SetTLSConfig(&tls.Config{
InsecureSkipVerify: true,
}))
Client offers two ways of writing, non-blocking and blocking.
Non-blocking write client uses implicit batching. Data are asynchronously written to the underlying buffer and they are automatically sent to a server when the size of the write buffer reaches the batch size, default 5000, or the flush interval, default 1s, times out. Writes are automatically retried on server back pressure.
This write client also offers synchronous blocking method to ensure that write buffer is flushed and all pending writes are finished, see Flush() method. Always use Close() method of the client to stop all background processes.
Asynchronous write client is recommended for frequent periodic writes.
…
go package main
import ( "fmt" "math/rand" "time"
"github.com/influxdata/influxdb-client-go/v2"
)
func main() { // Create a new client using an InfluxDB server base URL and an authentication token client := influxdb2.NewClient("http://localhost:8086", "my-token") // Get non-blocking write client writeAPI := client.WriteAPI("my-org", "my-bucket") // Get errors channel errorsCh := writeAPI.Errors() // Create go proc for reading and logging errors go func() { for err := range errorsCh { fmt.Printf("write error: %s\n", err.Error()) } }() // write some points for i := 0; i range(start: -1h) |> filter(fn: (r) => r._measurement == "stat")`) if err == nil { // Iterate over query response for result.Next() { // Notice when group key has changed if result.TableChanged() { fmt.Printf("table: %s\n", result.TableMetadata().String()) } // Access data fmt.Printf("value: %v\n", result.Record().Value()) } // check for an error if result.Err() != nil { fmt.Printf("query parsing error: %s\n", result.Err().Error()) } } else { panic(err) } // Ensures background processes finishes client.Close() }
### Raw
[QueryRaw()](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api#QueryAPI.QueryRaw) returns raw, unparsed, query result string and process it on your own. Returned csv format
can be controlled by the third parameter, query dialect.
```go
package main
import (
"context"
"fmt"
"github.com/influxdata/influxdb-client-go/v2"
)
func main() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
// Get query client
queryAPI := client.QueryAPI("my-org")
// Query and get complete result as a string
// Use default dialect
result, err := queryAPI.QueryRaw(context.Background(), `from(bucket:"my-bucket")|> range(start: -1h) |> filter(fn: (r) => r._measurement == "stat")`, influxdb2.DefaultDialect())
if err == nil {
fmt.Println("QueryResult:")
fmt.Println(result)
} else {
panic(err)
}
// Ensures background processes finishes
client.Close()
}
…
go
package main
import (
"context"
"fmt"
"github.com/influxdata/influxdb-client-go/v2"
)
func main() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
// Get query client
queryAPI := client.QueryAPI("my-org")
// Define parameters
parameters := struct {
Start string `json:"start"`
Field string `json:"field"`
Value float64 `json:"value"`
}{
"-1h",
"temperature",
25,
}
// Query with parameters
query := `from(bucket:"my-bucket")
|> range(start: duration(params.start))
|> filter(fn: (r) => r._measurement == "stat")
|> filter(fn: (r) => r._field == params.field)
|> filter(fn: (r) => r._value > params.value)`
// Get result
result, err := queryAPI.QueryWithParams(context.Background(), query, parameters)
if err == nil {
// Iterate over query response
for result.Next() {
// Notice when group key has changed
if result.TableChanged() {
fmt.Printf("table: %s\n", result.TableMetadata().String())
}
// Access data
fmt.Printf("value: %v\n", result.Record().Value())
}
// check for an error
if result.Err() != nil {
fmt.Printf("query parsing error: %s\n", result.Err().Error())
}
} else {
panic(err)
}
// Ensures background processes finishes
client.Close()
}
InfluxDB Go Client can be used in a concurrent environment. All its functions are thread-safe.
The best practise is to use a single Client instance per server URL. This ensures optimized resources usage,
most importantly reusing HTTP connections.
For efficient reuse of HTTP resources among multiple clients, create an HTTP client and use Options.SetHTTPClient() for setting it to all clients:
// Create HTTP client
httpClient := &http.Client{
Timeout: time.Second * time.Duration(60),
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 5 * time.Second,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
},
}
// Client for server 1
client1 := influxdb2.NewClientWithOptions("https://server:8086", "my-token", influxdb2.DefaultOptions().SetHTTPClient(httpClient))
// Client for server 2
client2 := influxdb2.NewClientWithOptions("https://server:9999", "my-token2", influxdb2.DefaultOptions().SetHTTPClient(httpClient))
Client ensures that there is a single instance of each server API sub-client for the specific area. E.g. a single WriteAPI instance for each org/bucket pair,
a single QueryAPI for each org.
Such a single API sub-client instance can be used concurrently:
package main
import (
"math/rand"
"sync"
"time"
influxdb2 "github.com/influxdata/influxdb-client-go"
"github.com/influxdata/influxdb-client-go/v2/api/write"
)
func main() {
// Create client
client := influxdb2.NewClient("http://localhost:8086", "my-token")
// Ensure closing the client
defer client.Close()
// Get write client
writeApi := client.WriteAPI("my-org", "my-bucket")
// Create channel for points feeding
pointsCh := make(chan *write.Point, 200)
threads := 5
var wg sync.WaitGroup
go func(points int) {
for i := 0; i range(start: -1h) |> filter(fn: (r) => r._measurement == "stat")`)
if err == nil {
for result.Next() {
if result.TableChanged() {
fmt.Printf("table: %s\n", result.TableMetadata().String())
}
fmt.Printf("row: %s\n", result.Record().String())
}
if result.Err() != nil {
fmt.Printf("Query error: %s\n", result.Err().Error())
}
} else {
fmt.Printf("Query error: %s\n", err.Error())
}
// Close client
client.Close()
}
If you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the master branch.
The InfluxDB 2 Go Client is released under the MIT License.
No open issues yet, or sync has not completed.