Influxdb is a popular temporal database and the 1.x and 2.x versions are incompatible, as is the code
The packages used in this document are
import influxdb2 "github.com/influxdata/influxdb-client-go/v2"
Copy the code
Be sure to close the database connection after the operation is complete
registered
After deployment, directly access the ports opened by The InfluxDB using a browser, and you can see the Start button. Click the button to register the initial account directly on the page
You can also use code to register
client := influxdb2.NewClient(url, "")
_, err := client.Setup(context.Background(), user, pwd, org, bucket, timeout)
defer client.Close()
Copy the code
parameter | Sample values | annotation |
---|---|---|
url | http://127.0.0.1:8086 | Note the address of influxDB, including http:// |
user | The name of the account to be registered | |
pwd | The password of the account must contain at least 8 characters | |
org | Organization, ideally for the InfluxDB, stores logs for all the InfluxDB services. Org is then used to distinguish micro services/micro services maintained by each department | |
bucket | Name the bucket where the account is stored | |
timeout | 0 | Timeout period. The data written to the account will be automatically deleted after the timeout period. If 0 is written, the data will be retained permanently |
Click “Data” on the left menu and then click “Tokens” on the top of the page. Finally, click the token of the account we just created.After clicking, a popup window will appear, and above the popup window is the identity token and token of the accountWe can use this identity token to manipulate influxDB in our code
write
Writing requires obtaining the write object, and obtaining the write object requires creating a connection
client := influxdb2.NewClient(url, token)
// Get a non-blocking write object
writeAPI := client.WriteAPI(org, bucket)
// Get blocking write object
writeBlockingAPI := client.WriteAPIBlocking(org, bucket)
Copy the code
parameter | Sample values | annotation |
---|---|---|
url | http://127.0.0.1:8086 | Note the address of influxDB, including http:// |
token | Is the identity token obtained after registration above | |
org | Organization, ideally for the InfluxDB, stores logs for all the InfluxDB services. Org is then used to distinguish micro services/micro services maintained by each department | |
bucket | Specifies the bucket to which data is written to the account |
Note that writing objects only need to get one as needed **, the rest of this article uses non-blocking writing objects as an example **
Writing is divided into two writing methods, the actual function is no difference, you can choose their own style to use
client := influxdb2.NewClient(url, token)
writeAPI := client.WriteAPI(org, bucket)
// Write in line protocol format
// The standard format is as follows. / Note that the content in [] is optional. / Time If you do not write, the insertion time/time is automatically set
// <measurement>[,<tag_key>=<tag_value>[,<tag_key>=<tag_value>]] <field_key>=<field_value>[,<field_key>=<field_value>] [<timestamp>]
// Here is an example
// myMeasurement,tag1=value1,tag2=value2 fieldKey="fieldValue" 1556813561098000000
writeAPI.WriteRecord(fmt.Sprintf("stat,unit=temperature min=%f,max=%f".23.5.45.0))
writeAPI.WriteRecord(fmt.Sprintf("stat,unit=temperature min=%f,max=%f".22.5.40.0))
writeAPI.Flush()
defer client.Close()
Copy the code
So this is line protocol style, this is a write syntax defined by Influx, so if you’re interested you can read the official documentation system and the general syntax looks like line 3, and note that if value is a string then double quoted influxdb to improve write performance, There will be a mechanism similar to mysql’s Redolog, where the data we write is not written to the database immediately, but is written to the cache first and then written to the database when appropriate. Writeapi.flush () causes the InfluxDB to immediately write cached data to the database.
There is also a point struct writing style
client := influxdb2.NewClient(url, token)
writeAPI := client.WriteAPI(org, bucket)
p := influxdb2.NewPoint("stat".map[string]string{"unit": "temperature"},
map[string]interface{} {"min": 30.0."max": 35.0},
time.Now())
writeAPI.WritePoint(p)
writeAPI.Flush()
defer client.Close()
Copy the code
Finally, there is the chain call style of point, which is my personal favorite
client := influxdb2.NewClient(url, token)
writeAPI := client.WriteAPI(org, bucket)
p := influxdb2.NewPointWithMeasurement("stat").
AddTag("unit"."temperature").
AddField("State"."Normal").
AddField("max".35.0)
writeAPI.WritePoint(p)
writeAPI.Flush()
defer client.Close()
Copy the code
The query
Since each Field data is considered as a point in the InfluxDB, the data returned by code is returned in the unit of Field. To be honest, I sometimes find it inconvenient
client := influxdb2.NewClient(url, token)
defer client.Close()
query := fmt.Sprintf("from(bucket:\"%v\")|> range(start: -3h) |> filter(fn: (r) => r._measurement == \"stat\")"."bucket")
result, err := client.QueryAPI(org).QueryRaw(context.Background(), query, influxdb2.DefaultDialect())
iferr ! =nil {
log.Fatal(err.Error())
return
}
result, err := queryAPI.Query(context.Background(), query)
iferr ! =nil {
panic(err)
}
for result.Next() {
if result.TableChanged() {
fmt.Printf("table: %s\n", result.TableMetadata().String())
}
fmt.Printf("value: %v\n", result.Record().Value())
}
ifresult.Err() ! =nil {
fmt.Printf("query parsing error: %\n", result.Err().Error())
}
Copy the code
So I can type out the data that I just wrote
In general, I prefer to use your browser to view the data directly on the page. Click Explore on the left menu bar, as shown in the image, select your own bucket or table, and click Submit to draw the imageIf you are writing string data, obviously strings cannot be quantified in the graph. To view the string data you are writing, switch to source data mode and switch to query writing and delete the line that generated the graphClick the “Script Editor” button to switch to the query editing interfaceDelete the aggregateWindow sentence as shown in the picture, and then click Submit to see the string data you wrote