client

package
v0.9.0-rc19 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 2, 2015 License: MIT Imports: 9 Imported by: 0

README

InfluxDB Client

Description

A Go client library written and maintained by the InfluxDB team. This package provides convenience functions to read and write time series data. It uses the HTTP protocol to communicate with your InfluxDB cluster.

Getting Started

Connecting To Your Database

Connecting to an InfluxDB database is straightforward. You will need a host name, a port and the cluster user credentials if applicable. The default port is 8086. You can customize these settings to your specific installation via the InfluxDB configuration file.

Thought not necessary for experimentation, you may want to create a new user and authenticate the connection to your database.

For more information please check out the Cluster Admin Docs.

For the impatient, you can create a new admin user bubba by firing off the InfluxDB CLI.

influx
> create user bubba with password 'bumblebeetuna'
> grant all privileges to bubba

And now for good measure set the credentials in you shell environment. In the example below we will use $INFLUX_USER and $INFLUX_PWD

Now with the administrivia out of the way, let's connect to our database.

NOTE: If you've opted out of creating a user, you can omit Username and Password in the configuration below.

package main

import "github.com/influxdb/influxdb/client"

const (
	MyHost        = "localhost"
	MyPort        = 8086
	MyDB          = "square_holes"
	MyMeasurement = "shapes"
)

func main() {
	u, err := url.Parse(fmt.Sprintf("http://%s:%d", MyHost, MyPort))
	if err != nil {
		log.Fatal(err)
	}

	conf := client.Config{
		URL:      *u,
		Username: os.Getenv("INFLUX_USER"),
		Password: os.Getenv("INFLUX_PWD"),
	}

	con, err := client.NewClient(conf)
	if err != nil {
		log.Fatal(err)
	}

	dur, ver, err := con.Ping()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Happy as a Hippo! %v, %s", dur, ver)
}

Inserting Data

Time series data aka points are written to the database using batch inserts. The mechanism is to create one or more points and then create a batch aka batch points and write these to a given database and series. A series is a combination of a measurement (time/values) and a set of tags.

In this sample we will create a batch of a 1,000 points. Each point has a timestamp and a single value as well as 2 tags indicating a shape and color. We write these points to a database called square_holes using a measurement named shapes.

NOTE: In this example, we are specifically assigning timestamp, tags and precision to each point. Alternately, you can specify a timestamp, tags and precision at the batch point level that could be used as defaults if an associated point does not provide these metrics.

NOTE: You can specify a RetentionPolicy as part of the batch points. If not provided InfluxDB will use the database default retention policy. By default, the default retention policy never deletes any data it contains.

func writePoints(con *client.Client) {
	var (
		shapes     = []string{"circle", "rectangle", "square", "triangle"}
		colors     = []string{"red", "blue", "green"}
		sampleSize = 1000
		pts        = make([]client.Point, sampleSize)
	)

	rand.Seed(42)
	for i := 0; i < sampleSize; i++ {
		pts[i] = client.Point{
			Name: "shapes",
			Tags: map[string]string{
				"color": strconv.Itoa(rand.Intn(len(colors))),
				"shape": strconv.Itoa(rand.Intn(len(shapes))),
			},
			Fields: map[string]interface{}{
				"value": rand.Intn(sampleSize),
			},
			Timestamp: time.Now(),
			Precision: "s",
		}
	}

	bps := client.BatchPoints{
		Points:          pts,
		Database:        MyDB,
		RetentionPolicy: "default",
	}
	_, err := con.Write(bps)
	if err != nil {
		log.Fatal(err)
	}
}
Querying Data

One nice advantage of using InfluxDB the ability to query your data using familiar SQL constructs. In this example we can create a convenience function to query the database as follows:

// queryDB convenience function to query the database
func queryDB(con *client.Client, cmd string) (res []client.Result, err error) {
	q := client.Query{
		Command:  cmd,
		Database: MyDB,
	}
	if results, err := con.Query(q); err == nil {
		if results.Error() != nil {
			return res, results.Error()
		}
		res = results.Results
	}
	return
}
Creating a Database
_, err := queryDB(con, fmt.Sprintf("create database %s", MyDB))
if err != nil {
	log.Fatal(err)
}
Count Records
q := fmt.Sprintf("select count(%s) from %s", "value", MyMeasurement)
res, err := queryDB(con, q)
if err != nil {
	log.Fatal(err)
}
count := res[0].Series[0].Values[0][1]
log.Printf("Found a total of `%v records", count)

Find the last 10 shapes records
q := fmt.Sprintf("select * from %s limit %d", MyMeasurement, 20)
res, err = queryDB(con, q)
if err != nil {
	log.Fatal(err)
}

for i, row := range res[0].Series[0].Values {
	t, err := time.Parse(time.RFC3339, row[0].(string))
	if err != nil {
		log.Fatal(err)
	}
	val, err := row[1].(json.Number).Int64()
	log.Printf("[%2d] %s: %03d\n", i, t.Format(time.Stamp), val)
}

Go Docs

Please refer to http://godoc.org/github.com/influxdb/influxdb/client for documentation.

See Also

You can also examine how the client library is used by the InfluxDB CLI.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func EpochToTime added in v0.9.0

func EpochToTime(epoch int64, precision string) (time.Time, error)

EpochToTime takes a unix epoch time and uses precision to return back a time.Time

func SetPrecision added in v0.9.0

func SetPrecision(t time.Time, precision string) time.Time

SetPrecision will round a time to the specified precision

Types

type BatchPoints added in v0.9.0

type BatchPoints struct {
	Points          []Point           `json:"points,omitempty"`
	Database        string            `json:"database,omitempty"`
	RetentionPolicy string            `json:"retentionPolicy,omitempty"`
	Tags            map[string]string `json:"tags,omitempty"`
	Timestamp       time.Time         `json:"timestamp,omitempty"`
	Precision       string            `json:"precision,omitempty"`
}

BatchPoints is used to send batched data in a single write. Database and Points are required If no retention policy is specified, it will use the databases default retention policy. If tags are specified, they will be "merged" with all points. If a point already has that tag, it is ignored. If timestamp is specified, it will be applied to any point with an empty timestamp. Precision can be specified if the timestamp is in epoch format (integer). Valid values for Precision are n, u, ms, s, m, and h

func (*BatchPoints) UnmarshalJSON added in v0.9.0

func (bp *BatchPoints) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the data into the BatchPoints struct

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is used to make calls to the server.

func NewClient

func NewClient(c Config) (*Client, error)

NewClient will instantiate and return a connected client to issue commands to the server.

Example
package main

import (
	"fmt"
	"log"
	"net/url"
	"os"

	"github.com/influxdb/influxdb/client"
)

func main() {
	host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086))
	if err != nil {
		log.Fatal(err)
	}

	// NOTE: this assumes you've setup a user and have setup shell env variables,
	// namely INFLUX_USER/INFLUX_PWD. If not just ommit Username/Password below.
	conf := client.Config{
		URL:      *host,
		Username: os.Getenv("INFLUX_USER"),
		Password: os.Getenv("INFLUX_PWD"),
	}
	con, err := client.NewClient(conf)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Connection", con)
}
Output:

func (*Client) Addr added in v0.9.0

func (c *Client) Addr() string

Addr provides the current url as a string of the server the client is connected to.

func (*Client) Dump added in v0.9.0

func (c *Client) Dump(db string) (io.ReadCloser, error)

Dump connects to server and retrieves all data stored for specified database. If successful, Dump returns the entire response body, which is an io.ReadCloser

func (*Client) Ping

func (c *Client) Ping() (time.Duration, string, error)

Ping will check to see if the server is up Ping returns how long the requeset took, the version of the server it connected to, and an error if one occured.

Example
package main

import (
	"fmt"
	"log"
	"net/url"

	"github.com/influxdb/influxdb/client"
)

func main() {
	host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086))
	if err != nil {
		log.Fatal(err)
	}
	con, err := client.NewClient(client.Config{URL: *host})
	if err != nil {
		log.Fatal(err)
	}

	dur, ver, err := con.Ping()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Happy as a hippo! %v, %s", dur, ver)
}
Output:

func (*Client) Query

func (c *Client) Query(q Query) (*Results, error)

Query sends a command to the server and returns the Results

Example
package main

import (
	"fmt"
	"log"
	"net/url"

	"github.com/influxdb/influxdb/client"
)

func main() {
	host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086))
	if err != nil {
		log.Fatal(err)
	}
	con, err := client.NewClient(client.Config{URL: *host})
	if err != nil {
		log.Fatal(err)
	}

	q := client.Query{
		Command:  "select count(value) from shapes",
		Database: "square_holes",
	}
	if results, err := con.Query(q); err == nil && results.Error() == nil {
		log.Println(results.Results)
	}
}
Output:

func (*Client) Write added in v0.9.0

func (c *Client) Write(bp BatchPoints) (*Results, error)

Write takes BatchPoints and allows for writing of multiple points with defaults If successful, error is nil and Results is nil If an error occurs, Results may contain additional information if populated.

Example
package main

import (
	"fmt"
	"log"
	"math/rand"
	"net/url"
	"strconv"
	"time"

	"github.com/influxdb/influxdb/client"
)

func main() {
	host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086))
	if err != nil {
		log.Fatal(err)
	}
	con, err := client.NewClient(client.Config{URL: *host})
	if err != nil {
		log.Fatal(err)
	}

	var (
		shapes     = []string{"circle", "rectangle", "square", "triangle"}
		colors     = []string{"red", "blue", "green"}
		sampleSize = 1000
		pts        = make([]client.Point, sampleSize)
	)

	rand.Seed(42)
	for i := 0; i < sampleSize; i++ {
		pts[i] = client.Point{
			Name: "shapes",
			Tags: map[string]string{
				"color": strconv.Itoa(rand.Intn(len(colors))),
				"shape": strconv.Itoa(rand.Intn(len(shapes))),
			},
			Fields: map[string]interface{}{
				"value": rand.Intn(sampleSize),
			},
			Timestamp: time.Now(),
			Precision: "s",
		}
	}

	bps := client.BatchPoints{
		Points:          pts,
		Database:        "BumbeBeeTuna",
		RetentionPolicy: "default",
	}
	_, err = con.Write(bps)
	if err != nil {
		log.Fatal(err)
	}
}
Output:

type Config added in v0.9.0

type Config struct {
	URL       url.URL
	Username  string
	Password  string
	UserAgent string
}

Config is used to specify what server to connect to. URL: The URL of the server connecting to. Username/Password are optional. They will be passed via basic auth if provided. UserAgent: If not provided, will default "InfluxDBClient",

type Point added in v0.9.0

type Point struct {
	Name      string
	Tags      map[string]string
	Timestamp time.Time
	Fields    map[string]interface{}
	Precision string
}

Point defines the fields that will be written to the database Name, Timestamp, and Fields are required Precision can be specified if the timestamp is in epoch format (integer). Valid values for Precision are n, u, ms, s, m, and h

func (*Point) MarshalJSON added in v0.9.0

func (p *Point) MarshalJSON() ([]byte, error)

MarshalJSON will format the time in RFC3339Nano Precision is also ignored as it is only used for writing, not reading Or another way to say it is we always send back in nanosecond precision

func (*Point) UnmarshalJSON added in v0.9.0

func (p *Point) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the data into the Point struct

type Query added in v0.9.0

type Query struct {
	Command  string
	Database string
}

Query is used to send a command to the server. Both Command and Database are required.

type Result added in v0.9.0

type Result struct {
	Series []influxql.Row
	Err    error
}

Result represents a resultset returned from a single statement.

func (*Result) MarshalJSON added in v0.9.0

func (r *Result) MarshalJSON() ([]byte, error)

MarshalJSON encodes the result into JSON.

func (*Result) UnmarshalJSON added in v0.9.0

func (r *Result) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the data into the Result struct

type Results

type Results struct {
	Results []Result
	Err     error
}

Results represents a list of statement results.

func (Results) Error

func (r Results) Error() error

Error returns the first error from any statement. Returns nil if no errors occurred on any statements.

func (*Results) MarshalJSON

func (r *Results) MarshalJSON() ([]byte, error)

MarshalJSON encodes the result into JSON.

func (*Results) UnmarshalJSON

func (r *Results) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the data into the Results struct

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL