Go

GreptimeDB uses different client libraries for writing and querying data. You can choose the client library that best suits your needs.

Write data

GreptimeDB provides an ingester library to help you write data. It utilizes the gRPC protocol, which supports schemaless writing and eliminates the need to create tables before writing data. For more information, refer to Automatic Schema Generation.

The Go ingester SDK provided by GreptimeDB is a lightweight, concurrent-safe library that is easy to use with the metric struct.

Installation

Use the following command to install the GreptimeDB client library for Go:

shell

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

Import the library in your code:

go

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

Connect to database

Username and password are always required to connect to GreptimeDB. For how to set authentication to GreptimeDB, see Authentication. Here we set the username and password when using the library to connect to 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
  13. client, _ := greptime.NewClient(cfg)

Row object

Each row item in a table consists of three types of columns: Tag, Timestamp, and Field. For more information, see Data Model. The types of column values could be String, Float, Int, Timestamp, etc. For more information, see Data Types.

The Go ingester SDK uses Series to represent a row data item. Multiple Series can be added to a Metric object and then written to GreptimeDB.

Create rows

The following example shows how to create a row contains Tag, Timestamp, and Field columns. The Tag column is a String type, the Timestamp column is a Timestamp type, and the Field column is a Float type.

To improve the efficiency of writing data, you can create multiple rows at once to write to GreptimeDB.

go

  1. seriesHost1 := greptime.Series{}
  2. seriesHost1.AddStringTag("host", "host1")
  3. seriesHost1.AddFloatField("cpu", 0.90)
  4. seriesHost1.SetTimestamp(time.Now())
  5. seriesHost2 := greptime.Series{}
  6. seriesHost2.AddStringTag("host", "host2")
  7. seriesHost2.AddFloatField("cpu", 0.70)
  8. seriesHost2.SetTimestamp(time.Now())
  9. metric := greptime.Metric{}
  10. metric.AddSeries(seriesHost1, seriesHost2)

Save rows

The following example shows how to save rows to tables in GreptimeDB.

go

  1. seriesHost1 := greptime.Series{}
  2. seriesHost1.AddStringTag("host", "host1")
  3. seriesHost1.AddFloatField("cpu", 0.90)
  4. seriesHost1.SetTimestamp(time.Now())
  5. seriesHost2 := greptime.Series{}
  6. seriesHost2.AddStringTag("host", "host2")
  7. seriesHost2.AddFloatField("cpu", 0.70)
  8. seriesHost2.SetTimestamp(time.Now())
  9. metric := greptime.Metric{}
  10. metric.AddSeries(seriesHost1, seriesHost2)
  11. monitorReq := greptime.InsertRequest{}
  12. monitorReq.WithTable("monitor").WithMetric(metric)
  13. insertsRequest := greptime.InsertsRequest{}
  14. insertsRequest.Append(monitorReq)
  15. res, err := client.Insert(context.Background(), insertsRequest)
  16. if err != nil {
  17. fmt.Printf("fail to insert, err: %+v\n", err)
  18. // error handling
  19. // ...
  20. }
  21. fmt.Printf("AffectedRows: %d\n", res.GetAffectedRows().Value)

Update rows

Please refer to update data for the updating mechanism. The following example shows saving a row and then updating the row.

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

More examples

For fully runnable code snippets and explanations for common methods, see the Examples.

Ingester library reference

Query data

GreptimeDB uses SQL as the main query language and is compatible with MySQL and PostgreSQL. Therefore, we recommend using mature SQL drivers to query data.

We recommend using the Gorm library, which is popular and developer-friendly.

Installation

Use the following command to install the Gorm library:

shell

  1. go get -u gorm.io/gorm

and install the MySQL driver as the example:

shell

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

Then import the libraries in your code:

go

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

Connect to database

The following example shows how to connect to GreptimeDB:

go

  1. type Mysql struct {
  2. Host string
  3. Port string
  4. User string
  5. Password string
  6. Database string
  7. DB *gorm.DB
  8. }
  9. m := &Mysql{
  10. Host: "127.0.0.1",
  11. Port: "4002", // default port for MySQL
  12. User: "username",
  13. Password: "password",
  14. Database: "public",
  15. }
  16. dsn := fmt.Sprintf("tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
  17. m.Host, m.Port, m.Database)
  18. dsn = fmt.Sprintf("%s:%s@%s", m.User, m.Password, dsn)
  19. db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
  20. if err != nil {
  21. //error handling
  22. }
  23. m.DB = db

Raw SQL

We recommend you using raw SQL to experience the full features of GreptimeDB. The following example shows how to use raw SQL to query data:

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. }
  6. func (Monitor) TableName() string {
  7. return "monitor"
  8. }
  9. var monitor Monitor
  10. db.Raw("SELECT host, cpu, ts FROM users WHERE ts > ?", 1701360000000).Scan(&result)

Query library reference

For more information about how to use the query library, please see the documentation of the corresponding library: