feat: python, go, js client
parent
9532535945
commit
0f9f58052f
|
@ -1,12 +1,183 @@
|
|||
---
|
||||
title: InfluxDB Go client library
|
||||
title: Go client library
|
||||
list_title: Go
|
||||
description: Use the Go client library to interact with InfluxDB.
|
||||
external_url: https://github.com/influxdata/influxdb-client-go
|
||||
description: >
|
||||
Use the Go client library to interact with InfluxDB.
|
||||
menu:
|
||||
influxdb_2_0_ref:
|
||||
name: Go
|
||||
parent: Client libraries
|
||||
url: https://github.com/influxdata/influxdb-client-go
|
||||
v2.0/tags: [client libraries, Go]
|
||||
aliases:
|
||||
- /v2.0/reference/api/client-libraries/go-cl-guide/
|
||||
weight: 201
|
||||
---
|
||||
|
||||
Use the [InfluxDB Go client library](https://github.com/influxdata/influxdb-client-go) to integrate InfluxDB into Go scripts and applications.
|
||||
|
||||
This guide presumes some familiarity with Go and InfluxDB.
|
||||
If just getting started, see [Getting started with InfluxDB](/v2.0/get-started/).
|
||||
|
||||
## Before you begin
|
||||
|
||||
1. Go 1.3 or later is required.
|
||||
2. Run ```go get github.com/influxdata/influxdb-client-go``` to download the client package in your $GOPATH, followed by ```go build``to build the package.
|
||||
3. Ensure that InfluxDB is running.
|
||||
If running InfluxDB locally, visit http://localhost:9999.
|
||||
(If using InfluxDB Cloud, visit the URL of your InfluxDB Cloud UI.
|
||||
For example: https://us-west-2-1.aws.cloud2.influxdata.com.)
|
||||
|
||||
## Write data to InfluxDB with Go
|
||||
|
||||
We are going to write some data as a point using the Go library.
|
||||
|
||||
In your Go program, import necessary packages and specify the entry point of our executable program.
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
influxdb2 "github.com/influxdata/influxdb-client-go"
|
||||
)
|
||||
```
|
||||
|
||||
Next, define a few variables with the name of your [bucket](/v2.0/organizations/buckets/), [organization](/v2.0/organizations/), and [token](/v2.0/security/tokens/).
|
||||
|
||||
```go
|
||||
bucket = "<my-bucket>"
|
||||
org = "<my-org>"
|
||||
token = "<my-token>"
|
||||
```
|
||||
|
||||
In order to write data, we need to create the the InfluxDB Go Client and pass in our named parameters: `url` and `token`.
|
||||
|
||||
```go
|
||||
client := influxdb2.NewClient("http://localhost:9999", "my-token")
|
||||
```
|
||||
|
||||
We create a write client with the `WriteApiBlocking` method and pass in our other named parameters: `org` and `bucket`.
|
||||
|
||||
```go
|
||||
writeApi := client.WriteApiBlocking("my-org", "my-bucket")
|
||||
```
|
||||
|
||||
We need three more lines for our program to write data.
|
||||
Create a [point](/v2.0/reference/glossary/#point) and write it to InfluxDB using the `WritePoint` method of the API writer struct.
|
||||
Close the client to flush all pending writes and finish.
|
||||
|
||||
```go
|
||||
p := influxdb2.NewPoint("stat",
|
||||
map[string]string{"unit": "temperature"},
|
||||
map[string]interface{}{"avg": 24.5, "max": 45},
|
||||
time.Now())
|
||||
writeApi.WritePoint(context.Background(), p)
|
||||
client.Close()
|
||||
```
|
||||
|
||||
### Complete example write script
|
||||
```go
|
||||
func main() {
|
||||
bucket := "<my-bucket>"
|
||||
org := "<my-org>"
|
||||
token := "<my-token>"
|
||||
// Create new client with default option for server url authenticate by token
|
||||
client := influxdb2.NewClient("http://localhost:9999", token)
|
||||
// User blocking write client for writes to desired bucket
|
||||
writeApi := client.WriteApiBlocking(org, bucket)
|
||||
// Create point using full params constructor
|
||||
p := influxdb2.NewPoint("stat",
|
||||
map[string]string{"unit": "temperature"},
|
||||
map[string]interface{}{"avg": 24.5, "max": 45},
|
||||
time.Now())
|
||||
// Write point immediately
|
||||
writeApi.WritePoint(context.Background(), p)
|
||||
// Ensures background processes finishes
|
||||
client.Close()
|
||||
}
|
||||
```
|
||||
## Query data from InfluxDB with Go
|
||||
|
||||
In order to query data, we to create the client and the query client, similarly to to the write example above.
|
||||
|
||||
```go
|
||||
client := influxdb2.NewClient("http://localhost:9999", "my-token")
|
||||
queryApi := client.QueryApi("my-org")
|
||||
```
|
||||
|
||||
Next, we create a flux query and supply our `bucket` parameter.
|
||||
|
||||
```flux
|
||||
from(bucket:"<bucket>")
|
||||
|> range(start: -1h)
|
||||
|> filter(fn: (r) => r._measurement == "stat"
|
||||
```
|
||||
|
||||
We query the InfluxDB server with our flux query. The query client returns the results as a FluxRecord object with a table structure. The `Query` method takes our flux query.
|
||||
The `Next` method iterates over our query response. The `TableChanged` method notices whe the group key has changed.
|
||||
The `Record` method returns last parsed FluxRecord and gives access to value and row properties. The `Value` method returns the actual field value.
|
||||
|
||||
```go
|
||||
result, err := queryApi.Query(context.Background(), `from(bucket:"<bucket>")|> 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("value: %v\n", result.Record().Value())
|
||||
}
|
||||
if result.Err() != nil {
|
||||
fmt.Printf("query parsing error: %s\n", result.Err().Error())
|
||||
}
|
||||
} else {
|
||||
panic(err)
|
||||
}
|
||||
```
|
||||
|
||||
The FluxRecord object has the following methods for accessing your data:
|
||||
- ```Table()```: Returns index of the table record belongs to.
|
||||
- ```Start()```: Returns the inclusive lower time bound of all records in the current table.
|
||||
- ```Stop()```: Returns the exclusive upper time bound of all records in the current table.
|
||||
- ```Time()```: Returns the time of the record.
|
||||
- ```Value() ```: Returns the actual field value.
|
||||
- ```Field()```: Returns the field name.
|
||||
- ```Measurement()```: Returns the measurement name of the record.
|
||||
- ```Values()```: Returns map of the values where key is the column name.
|
||||
- ```ValueByKey(<your_tags>)```: Returns value for given column key for the record.
|
||||
|
||||
|
||||
### Complete example query script
|
||||
|
||||
```
|
||||
func main() {
|
||||
// Create client
|
||||
client := influxdb2.NewClient("http://localhost:9999", "my-token")
|
||||
// Get query client
|
||||
queryApi := client.QueryApi("my-org")
|
||||
// Get QueryTableResult
|
||||
result, err := queryApi.Query(context.Background(), `from(bucket:"my-bucket")|> 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()
|
||||
}
|
||||
```
|
||||
|
||||
For more information, see the [Go client README on GitHub](https://github.com/influxdata/influxdb-client-go).
|
|
@ -1,12 +1,167 @@
|
|||
---
|
||||
title: InfluxDB JavaScript client library
|
||||
title: JavaScript client library
|
||||
list_title: JavaScript
|
||||
description: Use the JavaScript client library to interact with InfluxDB.
|
||||
external_url: https://github.com/influxdata/influxdb-client-js
|
||||
description: >
|
||||
Use the JavaScript client library to interact with InfluxDB.
|
||||
menu:
|
||||
influxdb_2_0_ref:
|
||||
name: JavaScript
|
||||
parent: Client libraries
|
||||
url: https://github.com/influxdata/influxdb-client-js
|
||||
v2.0/tags: [client libraries, JavaScript]
|
||||
aliases:
|
||||
- /v2.0/reference/api/client-libraries/js-cl-guide/
|
||||
weight: 201
|
||||
---
|
||||
|
||||
Use the [InfluxDB JavaScript client library](https://github.com/influxdata/influxdb-client-js) to integrate InfluxDB into JavaScript scripts and applications.This client supports both browser environments and NodeJS environments.
|
||||
|
||||
This guide presumes some familiarity with JavaScript, browser environments, and InfluxDB.
|
||||
If just getting started, see [Getting started with InfluxDB](/v2.0/get-started/).
|
||||
|
||||
## Before you begin
|
||||
|
||||
1. Install NodeJS:
|
||||
|
||||
```sh
|
||||
brew install node
|
||||
```
|
||||
2. Ensure that InfluxDB is running.
|
||||
If running InfluxDB locally, visit http://localhost:9999.
|
||||
(If using InfluxDB Cloud, visit the URL of your InfluxDB Cloud UI.
|
||||
For example: https://us-west-2-1.aws.cloud2.influxdata.com.)
|
||||
|
||||
## Easiest way to get started
|
||||
1. clone the [examples directory](https://github.com/influxdata/influxdb-client-js/tree/master/examples) in the [influxdb-client-js](https://github.com/influxdata/influxdb-client-js) repo.
|
||||
2. Navigate to examples directory and install NPM
|
||||
```sh
|
||||
cd examples
|
||||
npm install
|
||||
```
|
||||
3. Update your `./env` and `index.html` with the name of your [bucket](/v2.0/organizations/buckets/), [organization](/v2.0/organizations/), [token](/v2.0/security/tokens/), and `url` which relies upon proxy to forward requests to the target InfluxDB.
|
||||
4. Run the following command to run the application at [http://localhost:3001/examples/index.html]()
|
||||
```sh
|
||||
npm run browser
|
||||
```
|
||||
|
||||
|
||||
## Write data to InfluxDB with JavaScript
|
||||
|
||||
We are going to write some data as a point using the JavaScript library.
|
||||
|
||||
In your JavaScript script, import the latest release from the NPM repository.
|
||||
```js
|
||||
import {InfluxDB, Point} from 'https://unpkg.com/@influxdata/influxdb-client/dist/index.browser.mjs'
|
||||
```
|
||||
|
||||
Next, define a few constant variables with the name of your [bucket](/v2.0/organizations/buckets/), [organization](/v2.0/organizations/), [token](/v2.0/security/tokens/), and `url` which relies upon proxy to forward requests to the target InfluxDB.
|
||||
|
||||
```js
|
||||
const url = '/influx'
|
||||
const token = 'my-token'
|
||||
const org = 'my-org'
|
||||
const bucket = 'my-bucket'
|
||||
```
|
||||
|
||||
In order to write data, we need to instantiate the InfluxDB JavaScript Client and pass in our named parameters: `url` and `token`.
|
||||
|
||||
```js
|
||||
const influxDB = new InfluxDB({url, token})
|
||||
```
|
||||
|
||||
We get a write client with the `getWriteApi` method and pass in our other named parameters: `org` and `bucket`.
|
||||
|
||||
```js
|
||||
const writeApi = influxDB.getWriteApi(org, bucket)
|
||||
```
|
||||
|
||||
We need three more lines for our program to write data.
|
||||
The `useDefaultTags` method instructs the write api to use default tags when writing points. Create a [point](/v2.0/reference/glossary/#point) and write it to InfluxDB using the `writePoint` method. The `tag` and `floatField` methods add key value pairs for the tags and fields, respectively. Close the client to flush all pending writes and finish.
|
||||
|
||||
```js
|
||||
writeApi.useDefaultTags({location: 'browser'})
|
||||
const point1 = new Point('temperature')
|
||||
.tag('example', 'index.html')
|
||||
.floatField('value', 24)
|
||||
writeApi.writePoint(point1)
|
||||
console.log(`${point1}`)
|
||||
writeApi.close()
|
||||
```
|
||||
|
||||
### Complete example write script
|
||||
|
||||
```js
|
||||
const writeApi = new InfluxDB({url, token})
|
||||
const writeApi = influxDB.getWriteApi(org, bucket)
|
||||
// setup default tags for all writes through this API
|
||||
writeApi.useDefaultTags({location: 'browser'})
|
||||
const point1 = new Point('temperature')
|
||||
.tag('example', 'index.html')
|
||||
.floatField('value', 24)
|
||||
writeApi.writePoint(point1)
|
||||
console.log(` ${point1}`)
|
||||
// flush pending writes and close writeApi
|
||||
writeApi
|
||||
.close()
|
||||
.then(() => {
|
||||
console.log('WRITE FINISHED')
|
||||
})
|
||||
```
|
||||
|
||||
## Query data from InfluxDB with JavaScript
|
||||
|
||||
We get a query client with the `getQueryApi` method and pass in our named parameter `org`.
|
||||
|
||||
```js
|
||||
const queryApi = influxDB.getQueryApi(org)
|
||||
```
|
||||
|
||||
Next, we create a flux query and supply our `bucket` parameter.
|
||||
|
||||
```js
|
||||
const fluxQuery =
|
||||
'from(bucket:"<my-bucket>")
|
||||
|> range(start: 0)
|
||||
|> filter(fn: (r) => r._measurement == "temperature")'
|
||||
```
|
||||
|
||||
The query client performs the api and returns line table metadata and rows.
|
||||
The `next` method iterates over the rows.
|
||||
|
||||
```js
|
||||
queryApi.queryRows(fluxQuery, {
|
||||
next(row: string[], tableMeta: FluxTableMetaData) {
|
||||
const o = tableMeta.toObject(row)
|
||||
// console.log(JSON.stringify(o, null, 2))
|
||||
console.log(
|
||||
`${o._time} ${o._measurement} in '${o.location}' (${o.example}): ${o._field}=${o._value}`
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Complete example query script
|
||||
|
||||
```js
|
||||
// performs query and receive line table metadata and rows
|
||||
// https://v2.docs.influxdata.com/v2.0/reference/syntax/annotated-csv/
|
||||
queryApi.queryRows(fluxQuery, {
|
||||
next(row: string[], tableMeta: FluxTableMetaData) {
|
||||
const o = tableMeta.toObject(row)
|
||||
// console.log(JSON.stringify(o, null, 2))
|
||||
console.log(
|
||||
`${o._time} ${o._measurement} in '${o.location}' (${o.example}): ${o._field}=${o._value}`
|
||||
)
|
||||
},
|
||||
error(error: Error) {
|
||||
console.error(error)
|
||||
console.log('\nFinished ERROR')
|
||||
},
|
||||
complete() {
|
||||
console.log('\nFinished SUCCESS')
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
```
|
||||
|
||||
For more information, see the [JavaScript client README on GitHub](https://github.com/influxdata/influxdb-client-js).
|
|
@ -51,9 +51,7 @@ org = "<my-org>"
|
|||
token = "<my-token>"
|
||||
```
|
||||
|
||||
In order to write data, we need to create a few objects: a client, and a writer.
|
||||
The InfluxDBClient object takes three named parameters: `url`, `org`, and `token`.
|
||||
Here, we simply pass the three variables we have already defined.
|
||||
In order to write data, we need to instantiate the client. The `InfluxDBClient` object takes three named parameters: `url`, `org`, and `token`. Pass in the named parameters.
|
||||
|
||||
```python
|
||||
client = InfluxDBClient(
|
||||
|
@ -80,8 +78,6 @@ p = influxdb_client.Point("my_measurement").tag("location", "Prague").field("tem
|
|||
write_api.write(bucket=bucket, org=org, record=p)
|
||||
```
|
||||
|
||||
For more information, see the [Python client README on GitHub](https://github.com/influxdata/influxdb-client-python).
|
||||
|
||||
### Complete example write script
|
||||
|
||||
```python
|
||||
|
@ -103,3 +99,70 @@ write_api = client.write_api(write_options=SYNCHRONOUS)
|
|||
p = influxdb_client.Point("my_measurement").tag("location", "Prague").field("temperature", 25.3)
|
||||
write_api.write(bucket=bucket, org=org, record=p)
|
||||
```
|
||||
## Query data from InfluxDB with Python
|
||||
|
||||
In order to query data, we need to instantiate the query client.
|
||||
|
||||
```python
|
||||
query_api = client.query_api()
|
||||
```
|
||||
|
||||
Next, we create a flux query.
|
||||
|
||||
```python
|
||||
query = ‘ from(bucket:"my-bucket")\
|
||||
|> range(start: -10m)\
|
||||
|> filter(fn:(r) => r._measurement == “my_measurement”)\
|
||||
|> filter(fn: (r) => r.location == Prague")\
|
||||
|> filter(fn:(r) => r._field == "temperature" )‘
|
||||
```
|
||||
|
||||
We query the InfluxDB server with our flux query. The query client returns the results as a Flux Object with a table structure. The query() method takes two parameters: `org` and `query`.
|
||||
|
||||
```python
|
||||
result = client.query_api().query(org=org, query=query)
|
||||
```
|
||||
|
||||
We iterate through the tables and records in the Flux Object to return our values and fields using the `get_value()` and `get_field()` methods, respectively.
|
||||
```python
|
||||
results = []
|
||||
for table in result:
|
||||
for record in table.records:
|
||||
results.append((record.get_field(), record.get_value()))
|
||||
|
||||
print(results)
|
||||
[(temperature, 25.3)]
|
||||
```
|
||||
|
||||
The Flux Object has the following methods for accessing your data:
|
||||
- ```get_measurement()```: Returns the measurement name of the record.
|
||||
- ```get_field()```: Returns the field name.
|
||||
- ```get_values()```: Returns the actual field value.
|
||||
- ```values()```: Returns map of the values where key is the column name.
|
||||
- ```values.get(“<your tags>”)```: Returns value for given column key for the record.
|
||||
- ```get_time()```: Returns the time of the record.
|
||||
- ```get_start()```: Returns the inclusive lower time bound of all records in the current table.
|
||||
- ```get_stop()```: Returns the exclusive upper time bound of all records in the current table.
|
||||
|
||||
|
||||
|
||||
### Complete example query script
|
||||
|
||||
```python
|
||||
query_api = client.query_api()
|
||||
query = ‘ from(bucket:"my-bucket")\
|
||||
|> range(start: -10m)\
|
||||
|> filter(fn:(r) => r._measurement == “my_measurement”)\
|
||||
|> filter(fn: (r) => r.location == Prague")\
|
||||
|> filter(fn:(r) => r._field == "temperature" )‘
|
||||
result = client.query_api().query(org=org, query=query)
|
||||
results = []
|
||||
for table in result:
|
||||
for record in table.records:
|
||||
results.append((record.get_field(), record.get_value()))
|
||||
|
||||
print(results)
|
||||
[(temperature, 25.3)]
|
||||
```
|
||||
|
||||
For more information, see the [Python client README on GitHub](https://github.com/influxdata/influxdb-client-python).
|
Loading…
Reference in New Issue