package client
import "github.com/influxdata/influxdb1-client/v2"
Package client (v2) is the current official Go client for InfluxDB.
Index ¶
- Constants
- type BatchPoints
- type BatchPointsConfig
- type BooleanValue
- type ChunkedResponse
- func NewChunkedResponse(r io.Reader) *ChunkedResponse
- func (r *ChunkedResponse) Close() error
- func (r *ChunkedResponse) NextResponse() (*Response, error)
- type Client
- func NewHTTPClient(conf HTTPConfig) (Client, error)
- func NewUDPClient(conf UDPConfig) (Client, error)
- type ContentEncoding
- type DurationValue
- type HTTPConfig
- type Identifier
- type IntegerValue
- type Message
- type NumberValue
- type Params
- type Point
- func NewPoint( name string, tags map[string]string, fields map[string]interface{}, t ...time.Time, ) (*Point, error)
- func NewPointFrom(pt models.Point) *Point
- func (p *Point) Fields() (map[string]interface{}, error)
- func (p *Point) Name() string
- func (p *Point) PrecisionString(precision string) string
- func (p *Point) String() string
- func (p *Point) Tags() map[string]string
- func (p *Point) Time() time.Time
- func (p *Point) UnixNano() int64
- type Query
- func NewQuery(command, database, precision string) Query
- func NewQueryWithParameters(command, database, precision string, parameters map[string]interface{}) Query
- func NewQueryWithRP(command, database, retentionPolicy, precision string) Query
- type RegexValue
- type Response
- type Result
- type StringValue
- type TimeValue
- type UDPConfig
Examples ¶
- BatchPoints
- BatchPoints (Setters)
- Client
- Client (CreateDatabase)
- Client (Query)
- Client (QueryWithParams)
- Client (UDP)
- Client (Write)
- Client (Write1000)
- Point
- Point (WithoutTime)
Constants ¶
const ( // UDPPayloadSize is a reasonable default payload size for UDP packets that // could be travelling over the internet. UDPPayloadSize = 512 )
Types ¶
type BatchPoints ¶
type BatchPoints interface { // AddPoint adds the given point to the Batch of points. AddPoint(p *Point) // AddPoints adds the given points to the Batch of points. AddPoints(ps []*Point) // Points lists the points in the Batch. Points() []*Point // Precision returns the currently set precision of this Batch. Precision() string // SetPrecision sets the precision of this batch. SetPrecision(s string) error // Database returns the currently set database of this Batch. Database() string // SetDatabase sets the database of this Batch. SetDatabase(s string) // WriteConsistency returns the currently set write consistency of this Batch. WriteConsistency() string // SetWriteConsistency sets the write consistency of this Batch. SetWriteConsistency(s string) // RetentionPolicy returns the currently set retention policy of this Batch. RetentionPolicy() string // SetRetentionPolicy sets the retention policy of this Batch. SetRetentionPolicy(s string) }
BatchPoints is an interface into a batched grouping of points to write into
InfluxDB together. BatchPoints is NOT thread-safe, you must create a separate
batch for each goroutine.
Create a batch and add a point
Code:
Using the BatchPoints setter functions
Code:
Example¶
{
// Create a new point batch
bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
Database: "BumbleBeeTuna",
Precision: "s",
})
// Create a point and add to batch
tags := map[string]string{"cpu": "cpu-total"}
fields := map[string]interface{}{
"idle": 10.1,
"system": 53.3,
"user": 46.6,
}
pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())
if err != nil {
fmt.Println("Error: ", err.Error())
}
bp.AddPoint(pt)
}
Example (Setters)¶
{
// Create a new point batch
bp, _ := client.NewBatchPoints(client.BatchPointsConfig{})
bp.SetDatabase("BumbleBeeTuna")
bp.SetPrecision("ms")
// Create a point and add to batch
tags := map[string]string{"cpu": "cpu-total"}
fields := map[string]interface{}{
"idle": 10.1,
"system": 53.3,
"user": 46.6,
}
pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())
if err != nil {
fmt.Println("Error: ", err.Error())
}
bp.AddPoint(pt)
}
func NewBatchPoints ¶
func NewBatchPoints(conf BatchPointsConfig) (BatchPoints, error)
NewBatchPoints returns a BatchPoints interface based on the given config.
type BatchPointsConfig ¶
type BatchPointsConfig struct { // Precision is the write precision of the points, defaults to "ns". Precision string // Database is the database to write points to. Database string // RetentionPolicy is the retention policy of the points. RetentionPolicy string // Write consistency is the number of servers required to confirm write. WriteConsistency string }
BatchPointsConfig is the config data needed to create an instance of the BatchPoints struct.
type BooleanValue ¶
type BooleanValue bool
BooleanValue is a boolean literal.
func (BooleanValue) MarshalJSON ¶
func (v BooleanValue) MarshalJSON() ([]byte, error)
type ChunkedResponse ¶
type ChunkedResponse struct {
// contains filtered or unexported fields
}
ChunkedResponse represents a response from the server that uses chunking to stream the output.
func NewChunkedResponse ¶
func NewChunkedResponse(r io.Reader) *ChunkedResponse
NewChunkedResponse reads a stream and produces responses from the stream.
func (*ChunkedResponse) Close ¶
func (r *ChunkedResponse) Close() error
Close closes the response.
func (*ChunkedResponse) NextResponse ¶
func (r *ChunkedResponse) NextResponse() (*Response, error)
NextResponse reads the next line of the stream and returns a response.
type Client ¶
type Client interface { // Ping checks that status of cluster, and will always return 0 time and no // error for UDP clients. Ping(timeout time.Duration) (time.Duration, string, error) // Write takes a BatchPoints object and writes all Points to InfluxDB. Write(bp BatchPoints) error // Query makes an InfluxDB Query on the database. This will fail if using // the UDP client. Query(q Query) (*Response, error) // QueryAsChunk makes an InfluxDB Query on the database. This will fail if using // the UDP client. QueryAsChunk(q Query) (*ChunkedResponse, error) // Close releases any resources a Client may be using. Close() error }
Client is a client interface for writing & querying the database.
Create a new client
Code:
Create a Database with a query
Code:
Make a Query
Code:
Code:
Write a point using the UDP client
Code:
Write a point using the HTTP client
Code:
Write 1000 points
Code:
Example¶
{
// NOTE: this assumes you've setup a user and have setup shell env variables,
// namely INFLUX_USER/INFLUX_PWD. If not just omit Username/Password below.
_, err := client.NewHTTPClient(client.HTTPConfig{
Addr: "http://localhost:8086",
Username: os.Getenv("INFLUX_USER"),
Password: os.Getenv("INFLUX_PWD"),
})
if err != nil {
fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
}
Example (CreateDatabase)¶
{
// Make client
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: "http://localhost:8086",
})
if err != nil {
fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
defer c.Close()
q := client.NewQuery("CREATE DATABASE telegraf", "", "")
if response, err := c.Query(q); err == nil && response.Error() == nil {
fmt.Println(response.Results)
}
}
Example (Query)¶
{
// Make client
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: "http://localhost:8086",
})
if err != nil {
fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
defer c.Close()
q := client.NewQuery("SELECT count(value) FROM shapes", "square_holes", "ns")
if response, err := c.Query(q); err == nil && response.Error() == nil {
fmt.Println(response.Results)
}
}
Example (QueryWithParams)¶
{
// Make client
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: "http://localhost:8086",
})
if err != nil {
fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
defer c.Close()
q := client.NewQueryWithParameters("SELECT $fn($value) FROM $m", "square_holes", "ns", client.Params{
"fn": client.Identifier("count"),
"value": client.Identifier("value"),
"m": client.Identifier("shapes"),
})
if response, err := c.Query(q); err == nil && response.Error() == nil {
fmt.Println(response.Results)
}
}
Example (UDP)¶
{
// Make client
config := client.UDPConfig{Addr: "localhost:8089"}
c, err := client.NewUDPClient(config)
if err != nil {
fmt.Println("Error: ", err.Error())
}
defer c.Close()
// Create a new point batch
bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
Precision: "s",
})
// Create a point and add to batch
tags := map[string]string{"cpu": "cpu-total"}
fields := map[string]interface{}{
"idle": 10.1,
"system": 53.3,
"user": 46.6,
}
pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())
if err != nil {
fmt.Println("Error: ", err.Error())
}
bp.AddPoint(pt)
// Write the batch
c.Write(bp)
}
Example (Write)¶
{
// Make client
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: "http://localhost:8086",
})
if err != nil {
fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
defer c.Close()
// Create a new point batch
bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
Database: "BumbleBeeTuna",
Precision: "s",
})
// Create a point and add to batch
tags := map[string]string{"cpu": "cpu-total"}
fields := map[string]interface{}{
"idle": 10.1,
"system": 53.3,
"user": 46.6,
}
pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())
if err != nil {
fmt.Println("Error: ", err.Error())
}
bp.AddPoint(pt)
// Write the batch
c.Write(bp)
}
Example (Write1000)¶
{
sampleSize := 1000
// Make client
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: "http://localhost:8086",
})
if err != nil {
fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
defer c.Close()
rand.Seed(42)
bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
Database: "systemstats",
Precision: "us",
})
for i := 0; i < sampleSize; i++ {
regions := []string{"us-west1", "us-west2", "us-west3", "us-east1"}
tags := map[string]string{
"cpu": "cpu-total",
"host": fmt.Sprintf("host%d", rand.Intn(1000)),
"region": regions[rand.Intn(len(regions))],
}
idle := rand.Float64() * 100.0
fields := map[string]interface{}{
"idle": idle,
"busy": 100.0 - idle,
}
pt, err := client.NewPoint(
"cpu_usage",
tags,
fields,
time.Now(),
)
if err != nil {
println("Error:", err.Error())
continue
}
bp.AddPoint(pt)
}
err = c.Write(bp)
if err != nil {
fmt.Println("Error: ", err.Error())
}
}
func NewHTTPClient ¶
func NewHTTPClient(conf HTTPConfig) (Client, error)
NewHTTPClient returns a new Client from the provided config. Client is safe for concurrent use by multiple goroutines.
func NewUDPClient ¶
NewUDPClient returns a client interface for writing to an InfluxDB UDP service from the given config.
type ContentEncoding ¶
type ContentEncoding string
const ( DefaultEncoding ContentEncoding = "" GzipEncoding ContentEncoding = "gzip" )
type DurationValue ¶
DurationValue is a duration literal.
func (DurationValue) MarshalJSON ¶
func (v DurationValue) MarshalJSON() ([]byte, error)
type HTTPConfig ¶
type HTTPConfig struct { // Addr should be of the form "http://host:port" // or "http://[ipv6-host%zone]:port". Addr string // Username is the influxdb username, optional. Username string // Password is the influxdb password, optional. Password string // UserAgent is the http User Agent, defaults to "InfluxDBClient". UserAgent string // Timeout for influxdb writes, defaults to no timeout. Timeout time.Duration // InsecureSkipVerify gets passed to the http client, if true, it will // skip https certificate verification. Defaults to false. InsecureSkipVerify bool // TLSConfig allows the user to set their own TLS config for the HTTP // Client. If set, this option overrides InsecureSkipVerify. TLSConfig *tls.Config // Proxy configures the Proxy function on the HTTP client. Proxy func(req *http.Request) (*url.URL, error) // WriteEncoding specifies the encoding of write request WriteEncoding ContentEncoding }
HTTPConfig is the config data needed to create an HTTP Client.
type Identifier ¶
type Identifier string
Identifier is an identifier value.
func (Identifier) MarshalJSON ¶
func (v Identifier) MarshalJSON() ([]byte, error)
type IntegerValue ¶
type IntegerValue int64
IntegerValue is an integer literal.
func (IntegerValue) MarshalJSON ¶
func (v IntegerValue) MarshalJSON() ([]byte, error)
type Message ¶
Message represents a user message.
type NumberValue ¶
type NumberValue float64
NumberValue is a number literal.
func (NumberValue) MarshalJSON ¶
func (v NumberValue) MarshalJSON() ([]byte, error)
type Params ¶
type Params map[string]interface{}
Params is a type alias to the query parameters.
type Point ¶
type Point struct {
// contains filtered or unexported fields
}
Point represents a single data point.
Create a new point with a timestamp
Code:
Create a new point without a timestamp
Code:
Example¶
{
tags := map[string]string{"cpu": "cpu-total"}
fields := map[string]interface{}{
"idle": 10.1,
"system": 53.3,
"user": 46.6,
}
pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())
if err == nil {
fmt.Println("We created a point: ", pt.String())
}
}
Example (WithoutTime)¶
{
tags := map[string]string{"cpu": "cpu-total"}
fields := map[string]interface{}{
"idle": 10.1,
"system": 53.3,
"user": 46.6,
}
pt, err := client.NewPoint("cpu_usage", tags, fields)
if err == nil {
fmt.Println("We created a point w/o time: ", pt.String())
}
}
func NewPoint ¶
func NewPoint( name string, tags map[string]string, fields map[string]interface{}, t ...time.Time, ) (*Point, error)
NewPoint returns a point with the given timestamp. If a timestamp is not given, then data is sent to the database without a timestamp, in which case the server will assign local time upon reception. NOTE: it is recommended to send data with a timestamp.
func NewPointFrom ¶
NewPointFrom returns a point from the provided models.Point.
func (*Point) Fields ¶
Fields returns the fields for the point.
func (*Point) Name ¶
Name returns the measurement name of the point.
func (*Point) PrecisionString ¶
PrecisionString returns a line-protocol string of the Point, with the timestamp formatted for the given precision.
func (*Point) String ¶
String returns a line-protocol string of the Point.
func (*Point) Tags ¶
Tags returns the tags associated with the point.
func (*Point) Time ¶
Time return the timestamp for the point.
func (*Point) UnixNano ¶
UnixNano returns timestamp of the point in nanoseconds since Unix epoch.
type Query ¶
type Query struct { Command string Database string RetentionPolicy string Precision string Chunked bool ChunkSize int Parameters map[string]interface{} }
Query defines a query to send to the server.
func NewQuery ¶
NewQuery returns a query object. The database and precision arguments can be empty strings if they are not needed for the query.
func NewQueryWithParameters ¶
func NewQueryWithParameters(command, database, precision string, parameters map[string]interface{}) Query
NewQueryWithParameters returns a query object. The database and precision arguments can be empty strings if they are not needed for the query. parameters is a map of the parameter names used in the command to their values.
func NewQueryWithRP ¶
NewQueryWithRP returns a query object. The database, retention policy, and precision arguments can be empty strings if they are not needed for the query. Setting the retention policy only works on InfluxDB versions 1.6 or greater.
type RegexValue ¶
type RegexValue string
RegexValue is a regexp literal.
func (RegexValue) MarshalJSON ¶
func (v RegexValue) MarshalJSON() ([]byte, error)
type Response ¶
Response represents a list of statement results.
func (*Response) Error ¶
Error returns the first error from any statement. It returns nil if no errors occurred on any statements.
type Result ¶
type Result struct { StatementId int `json:"statement_id"` Series []models.Row Messages []*Message Err string `json:"error,omitempty"` }
Result represents a resultset returned from a single statement.
type StringValue ¶
type StringValue string
StringValue is a string literal.
func (StringValue) MarshalJSON ¶
func (v StringValue) MarshalJSON() ([]byte, error)
type TimeValue ¶
TimeValue is a time literal.
func (TimeValue) MarshalJSON ¶
type UDPConfig ¶
type UDPConfig struct { // Addr should be of the form "host:port" // or "[ipv6-host%zone]:port". Addr string // PayloadSize is the maximum size of a UDP client message, optional // Tune this based on your network. Defaults to UDPPayloadSize. PayloadSize int }
UDPConfig is the config data needed to create a UDP Client.
Source Files ¶
- Version
- v0.0.0-20220302092344-a9ab5670611c (latest)
- Published
- Mar 2, 2022
- Platform
- linux/amd64
- Imports
- 17 packages
- Last checked
- 1 month ago –
Tools for package owners.