LoginSignup
0
0

More than 3 years have passed since last update.

InfluxDB 2.0 を使う(3) Goのクライアントライブラリを使う

Last updated at Posted at 2019-12-02

はじめに

InfluxDB 2.0で、前々回前回 ではCLIで値の入出力を行いました。本記事ではGo言語クライアントライブラリ influxdb-client-go で同様の処理を行う手順を見ていきます。

環境

  • OS: Debian 9.11
  • InfluxDB: v2.0.0-alpha.20
  • influxdb-client-go v0.1.4

アクセストークンの作成

ライブラリからInfluxDBにアクセスするにはアクセストークンが必要です。アクセストークンはあらかじめサーバで作成します。アクセストークンの作成にはCLIを用います。

$ ./influx auth create --org my_organization  --write-buckets my_buckets --read-buckets my_buckets

これは指定したorganization(ユーザのグループ)に対し、値の登録と取得を許可するアクセストークンを作成するコマンドです。指定bucketへのread/writeを許可します。他のオプションはこちらを参照して下さい。

結果は次のようになります。Tokenとある(bbbbbbbbbbbbbbbbに相当する部分)がアクセストークンです。

ID                  Token               Status  UserID              Permissions
aaaaaaaaaaaaaaaa    bbbbbbbbbbbbbbbb    active  cccccccccccccccc    [read:orgs/dddddddddddddddd/buckets write:orgs/dddddddddddddddd/buckets]

値の登録と取得の例

サンプル値を登録し、同じ値を取得するコードを以下に示します。

main.go
package main

import (
    "context"
    "fmt"
    "net/http"
    "time"

    influxdb "github.com/influxdata/influxdb-client-go"
)

func main() {
    // クライアントの初期化
    token := "bbbbbbbbbbbbbbbb"
    client := &http.Client{}
    influx, err := influxdb.New("http://localhost:9999", token, influxdb.WithHTTPClient(client))
    if err != nil {
        panic(err)
    }

    // 値の登録
    metrics := []influxdb.Metric{
        influxdb.NewRowMetric(
            map[string]interface{}{"temperature": 12.3, "humidity": 45.6},
            "my_measurement",
            map[string]string{"city": "tokyo"},
            time.Now(),
        ),
    }
    if _, err := influx.Write(context.Background(), "my_bucket", "my_organization", metrics...); err != nil {
        panic(err)
    }

    // 値の取得
    flux := "from(bucket: \"my_bucket\") |> range(start:-24h)"
    result, err := influx.QueryCSV(context.Background(), flux, "my_organization")
    if err != nil {
        panic(err)
    }
    for i := 0; result.Next(); i++ {
        m := map[string]interface{}{}
        err := result.Unmarshal(m)
        if err != nil {
            panic(err)
        }
        fmt.Println(i, m["_measurement"], m["_time"], m["city"], m["_field"], m["_value"])
    }

    // クライアントの終了
    influx.Close()
}

値の登録にはWriteを用います。ここではタイムスタンプとして現在時刻を指定し、またタグにcityを追加しています。

値の取得にはQueryCSVを用います。ここでは直近24時間のデータを取得するクエリをFluxで記し関数に渡しています。結果に対し、result.Nextでfor文を回しつつ、Unmarshalでmapに変換するというのがイディオムのようです。

実行結果は以下の通りです。

$ go run main.go
0 my_measurement 2019-12-02 12:44:09.456475011 +0000 UTC tokyo temperature 12.3
1 my_measurement 2019-12-02 12:44:09.456475011 +0000 UTC tokyo humidity 45.6

おわりに

InfluxDB 2.0のGo言語クライアントライブラリで値の登録と取得を行うサンプルを見ていきました。InfluxDB 2.0はまだアルファ版のため、今後ライブラリに大きな変更が入りうる点はご了承下さい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0