Go

GreptimeDB 使用不同的客户端库来写入和查询数据。 你根据需求可以选择合适的客户端库。

写入数据

GreptimeDB 提供了一个 ingester 库来帮助你写入数据。 它使用 gRPC 协议,支持自动生成表结构,无需在写入数据前创建表。 更多信息请参考 自动生成表结构。

GreptimeDB 提供的 Go Ingest SDK 是一个轻量级、并发安全的库,使用起来非常简单。

安装

使用下方的命令安装 Go Ingest SDK:

shell

1. go get github.com/GreptimeTeam/greptimedb-client-go@v0.1.2 google.golang.org/grpc google.golang.org/grpc/credentials/insecure

引入到代码中:

go

1. import (
2. greptime "github.com/GreptimeTeam/greptimedb-client-go"
3. "google.golang.org/grpc"
4. "google.golang.org/grpc/credentials/insecure"
5. )

连接数据库

连接 GreptimeDB 时,通常需要用户名和密码。 关于如何设置 GreptimeDB 的鉴权方式,请参考鉴权。 这里我们在使用 ingester 库连接 GreptimeDB 时设置用户名和密码。

go

1. options := []grpc.DialOption{
2. grpc.WithTransportCredentials(insecure.NewCredentials()),
3. }
4. // To connect a database that needs authentication, for example, those on Greptime Cloud,
5. // `Username` and `Password` are needed when connecting to a database that requires authentication.
6. // Leave the two fields empty if connecting a database without authentication.
7. cfg := greptime.NewCfg("127.0.0.1").
8. WithDatabase("public").      // change to your real database
9. WithPort(4001).              // default port
10. WithAuth("username", "password").            // `Username` and `Password`
11. WithDialOptions(options...). // specify your gRPC dail options
12. WithCallOptions()            // specify your gRPC call options

14. client, _ := greptime.NewClient(cfg)

行对象

表中的每条行数据包含三种类型的列:Tag、Timestamp 和 Field。更多信息请参考 数据模型。 列值的类型可以是 String、Float、Int、Timestamp 等。更多信息请参考 数据类型。

Go Ingest SDK 使用 Series 来表示一行数据,多个 Series 可以添加到 Metric 中,然后写入到 GreptimeDB 中。

创建行数据

下面的例子展示了如何创建包含 Tag、Timestamp 和 Field 列的行。Tag 列是 String 类型,Timestamp 列是 Timestamp 类型,Field 列是 Float 类型。

为了提高写入数据的效率,你可以一次创建多行数据写入 GreptimeDB。

go

1. seriesHost1 := greptime.Series{}
2. seriesHost1.AddStringTag("host", "host1")
3. seriesHost1.AddFloatField("cpu", 0.90)
4. seriesHost1.SetTimestamp(time.Now())

6. seriesHost2 := greptime.Series{}
7. seriesHost2.AddStringTag("host", "host2")
8. seriesHost2.AddFloatField("cpu", 0.70)
9. seriesHost2.SetTimestamp(time.Now())

11. metric := greptime.Metric{}
12. metric.AddSeries(seriesHost1, seriesHost2)

保存行数据

下方的例子展示了如何将行数据保存到 GreptimeDB 中。

go

1. seriesHost1 := greptime.Series{}
2. seriesHost1.AddStringTag("host", "host1")
3. seriesHost1.AddFloatField("cpu", 0.90)
4. seriesHost1.SetTimestamp(time.Now())

6. seriesHost2 := greptime.Series{}
7. seriesHost2.AddStringTag("host", "host2")
8. seriesHost2.AddFloatField("cpu", 0.70)
9. seriesHost2.SetTimestamp(time.Now())

11. metric := greptime.Metric{}
12. metric.AddSeries(seriesHost1, seriesHost2)

14. monitorReq := greptime.InsertRequest{}
15. monitorReq.WithTable("monitor").WithMetric(metric)

17. insertsRequest := greptime.InsertsRequest{}
18. insertsRequest.Append(monitorReq)

20. res, err := client.Insert(context.Background(), insertsRequest)
21. if err != nil {
22. fmt.Printf("fail to insert, err: %+v\n", err)
23. // error handling
24. // ...
25. }
26. fmt.Printf("AffectedRows: %d\n", res.GetAffectedRows().Value)

更新行数据

请参考 更新数据了解更新机制。 下面的例子展示了先保存一行数据,然后更新这行数据。

go

1. // save a row data
2. series := greptime.Series{}
3. series.AddStringTag("host", "host1")
4. series.AddFloatField("cpu", 0.90)
5. series.SetTimestamp(1703832681000)
6. metric := greptime.Metric{}
7. metric.AddSeries(series)
8. monitorReq := greptime.InsertRequest{}
9. monitorReq.WithTable("monitor").WithMetric(metric)
10. insertsRequest := greptime.InsertsRequest{}
11. insertsRequest.Append(monitorReq)
12. res, _ := client.Insert(context.Background(), insertsRequest)

14. // update the row data
15. newSeries := greptime.Series{}
16. // The same tag `host1`
17. newSeries.AddStringTag("host", "host1")
18. // The same time index `1703832681000`
19. newSeries.SetTimestamp(1703832681000)
20. // The new field value `0.80`
21. newSeries.AddFloatField("cpu", 0.80)
22. // overwrite the existing data
23. metric := greptime.Metric{}
24. metric.AddSeries(newSeries)
25. monitorReq := greptime.InsertRequest{}
26. monitorReq.WithTable("monitor").WithMetric(metric)
27. insertsRequest := greptime.InsertsRequest{}
28. insertsRequest.Append(monitorReq)
29. res, _ := client.Insert(context.Background(), insertsRequest)

更多示例

有关更多可运行的代码片段和常用方法的解释,请参阅示例。

Ingester 库参考

查询数据

GreptimeDB 使用 SQL 作为主要查询语言,兼容 MySQL 和 PostgreSQL。 因此,我们推荐使用成熟的 SQL 驱动来查询数据。

推荐的查询库

我们推荐使用 Gorm 库来查询数据。

安装

使用下方的命令安装 Gorm:

shell

1. go get -u gorm.io/gorm

以 MySQL 为例安装 driver:

shell

1. go get -u gorm.io/driver/mysql

引入到代码中:

go

1. import (
2. "gorm.io/gorm"
3. "gorm.io/driver/mysql"
4. )

连接到数据库

下方的例子展示了如何连接到 GreptimeDB:

go

1. type Mysql struct {
2. Host     string
3. Port     string
4. User     string
5. Password string
6. Database string

8. DB *gorm.DB
9. }

11. m := &Mysql{
12. Host:     "127.0.0.1",
13. Port:     "4002", // default port for MySQL
14. User:     "username",
15. Password: "password",
16. Database: "public",
17. }

19. dsn := fmt.Sprintf("tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
20. m.Host, m.Port, m.Database)
21. dsn = fmt.Sprintf("%s:%s@%s", m.User, m.Password, dsn)
22. db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
23. if err != nil {
24. //error handling
25. }
26. m.DB = db

Raw SQL

我们推荐使用 Raw SQL 来体验 GreptimeDB 的全部功能。 下面的例子展示了如何使用 Raw SQL 查询数据:

go

1. type Monitor struct {
2. Host        string    `gorm:"column:host;primaryKey"`
3. Ts          time.Time `gorm:"column:ts;primaryKey"`
4. Cpu         float64   `gorm:"column:cpu"`
5. }

7. func (Monitor) TableName() string {
8. return "monitor"
9. }

11. var monitor Monitor
12. db.Raw("SELECT host, cpu, ts FROM users WHERE ts > ?", 1701360000000).Scan(&result)

查询库参考

有关如何使用查询库的更多信息,请参考相应库的文档: