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:
go get github.com/GreptimeTeam/[email protected] google.golang.org/grpc google.golang.org/grpc/credentials/insecure
go get github.com/GreptimeTeam/[email protected] google.golang.org/grpc google.golang.org/grpc/credentials/insecure
Import the library in your code:
import (
greptime "github.com/GreptimeTeam/greptimedb-client-go"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
import (
greptime "github.com/GreptimeTeam/greptimedb-client-go"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
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.
options := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
}
// To connect a database that needs authentication, for example, those on Greptime Cloud,
// `Username` and `Password` are needed when connecting to a database that requires authentication.
// Leave the two fields empty if connecting a database without authentication.
cfg := greptime.NewCfg("127.0.0.1").
WithDatabase("public"). // change to your real database
WithPort(4001). // default port
WithAuth("username", "password"). // `Username` and `Password`
WithDialOptions(options...). // specify your gRPC dail options
WithCallOptions() // specify your gRPC call options
client, _ := greptime.NewClient(cfg)
options := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
}
// To connect a database that needs authentication, for example, those on Greptime Cloud,
// `Username` and `Password` are needed when connecting to a database that requires authentication.
// Leave the two fields empty if connecting a database without authentication.
cfg := greptime.NewCfg("127.0.0.1").
WithDatabase("public"). // change to your real database
WithPort(4001). // default port
WithAuth("username", "password"). // `Username` and `Password`
WithDialOptions(options...). // specify your gRPC dail options
WithCallOptions() // specify your gRPC call options
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.
seriesHost1 := greptime.Series{}
seriesHost1.AddStringTag("host", "host1")
seriesHost1.AddFloatField("cpu", 0.90)
seriesHost1.SetTimestamp(time.Now())
seriesHost2 := greptime.Series{}
seriesHost2.AddStringTag("host", "host2")
seriesHost2.AddFloatField("cpu", 0.70)
seriesHost2.SetTimestamp(time.Now())
metric := greptime.Metric{}
metric.AddSeries(seriesHost1, seriesHost2)
seriesHost1 := greptime.Series{}
seriesHost1.AddStringTag("host", "host1")
seriesHost1.AddFloatField("cpu", 0.90)
seriesHost1.SetTimestamp(time.Now())
seriesHost2 := greptime.Series{}
seriesHost2.AddStringTag("host", "host2")
seriesHost2.AddFloatField("cpu", 0.70)
seriesHost2.SetTimestamp(time.Now())
metric := greptime.Metric{}
metric.AddSeries(seriesHost1, seriesHost2)
Save rows ​
The following example shows how to save rows to tables in GreptimeDB.
seriesHost1 := greptime.Series{}
seriesHost1.AddStringTag("host", "host1")
seriesHost1.AddFloatField("cpu", 0.90)
seriesHost1.SetTimestamp(time.Now())
seriesHost2 := greptime.Series{}
seriesHost2.AddStringTag("host", "host2")
seriesHost2.AddFloatField("cpu", 0.70)
seriesHost2.SetTimestamp(time.Now())
metric := greptime.Metric{}
metric.AddSeries(seriesHost1, seriesHost2)
monitorReq := greptime.InsertRequest{}
monitorReq.WithTable("monitor").WithMetric(metric)
insertsRequest := greptime.InsertsRequest{}
insertsRequest.Append(monitorReq)
res, err := client.Insert(context.Background(), insertsRequest)
if err != nil {
fmt.Printf("fail to insert, err: %+v\n", err)
// error handling
// ...
}
fmt.Printf("AffectedRows: %d\n", res.GetAffectedRows().Value)
seriesHost1 := greptime.Series{}
seriesHost1.AddStringTag("host", "host1")
seriesHost1.AddFloatField("cpu", 0.90)
seriesHost1.SetTimestamp(time.Now())
seriesHost2 := greptime.Series{}
seriesHost2.AddStringTag("host", "host2")
seriesHost2.AddFloatField("cpu", 0.70)
seriesHost2.SetTimestamp(time.Now())
metric := greptime.Metric{}
metric.AddSeries(seriesHost1, seriesHost2)
monitorReq := greptime.InsertRequest{}
monitorReq.WithTable("monitor").WithMetric(metric)
insertsRequest := greptime.InsertsRequest{}
insertsRequest.Append(monitorReq)
res, err := client.Insert(context.Background(), insertsRequest)
if err != nil {
fmt.Printf("fail to insert, err: %+v\n", err)
// error handling
// ...
}
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.
// save a row data
series := greptime.Series{}
series.AddStringTag("host", "host1")
series.AddFloatField("cpu", 0.90)
series.SetTimestamp(1703832681000)
metric := greptime.Metric{}
metric.AddSeries(series)
monitorReq := greptime.InsertRequest{}
monitorReq.WithTable("monitor").WithMetric(metric)
insertsRequest := greptime.InsertsRequest{}
insertsRequest.Append(monitorReq)
res, _ := client.Insert(context.Background(), insertsRequest)
// update the row data
newSeries := greptime.Series{}
// The same tag `host1`
newSeries.AddStringTag("host", "host1")
// The same time index `1703832681000`
newSeries.SetTimestamp(1703832681000)
// The new field value `0.80`
newSeries.AddFloatField("cpu", 0.80)
// overwrite the existing data
metric := greptime.Metric{}
metric.AddSeries(newSeries)
monitorReq := greptime.InsertRequest{}
monitorReq.WithTable("monitor").WithMetric(metric)
insertsRequest := greptime.InsertsRequest{}
insertsRequest.Append(monitorReq)
res, _ := client.Insert(context.Background(), insertsRequest)
// save a row data
series := greptime.Series{}
series.AddStringTag("host", "host1")
series.AddFloatField("cpu", 0.90)
series.SetTimestamp(1703832681000)
metric := greptime.Metric{}
metric.AddSeries(series)
monitorReq := greptime.InsertRequest{}
monitorReq.WithTable("monitor").WithMetric(metric)
insertsRequest := greptime.InsertsRequest{}
insertsRequest.Append(monitorReq)
res, _ := client.Insert(context.Background(), insertsRequest)
// update the row data
newSeries := greptime.Series{}
// The same tag `host1`
newSeries.AddStringTag("host", "host1")
// The same time index `1703832681000`
newSeries.SetTimestamp(1703832681000)
// The new field value `0.80`
newSeries.AddFloatField("cpu", 0.80)
// overwrite the existing data
metric := greptime.Metric{}
metric.AddSeries(newSeries)
monitorReq := greptime.InsertRequest{}
monitorReq.WithTable("monitor").WithMetric(metric)
insertsRequest := greptime.InsertsRequest{}
insertsRequest.Append(monitorReq)
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.
Recommended library ​
We recommend using the Gorm library, which is popular and developer-friendly.
Installation ​
Use the following command to install the Gorm library:
go get -u gorm.io/gorm
go get -u gorm.io/gorm
and install the MySQL driver as the example:
go get -u gorm.io/driver/mysql
go get -u gorm.io/driver/mysql
Then import the libraries in your code:
import (
"gorm.io/gorm"
"gorm.io/driver/mysql"
)
import (
"gorm.io/gorm"
"gorm.io/driver/mysql"
)
Connect to database ​
The following example shows how to connect to GreptimeDB:
type Mysql struct {
Host string
Port string
User string
Password string
Database string
DB *gorm.DB
}
m := &Mysql{
Host: "127.0.0.1",
Port: "4002", // default port for MySQL
User: "username",
Password: "password",
Database: "public",
}
dsn := fmt.Sprintf("tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
m.Host, m.Port, m.Database)
dsn = fmt.Sprintf("%s:%s@%s", m.User, m.Password, dsn)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
//error handling
}
m.DB = db
type Mysql struct {
Host string
Port string
User string
Password string
Database string
DB *gorm.DB
}
m := &Mysql{
Host: "127.0.0.1",
Port: "4002", // default port for MySQL
User: "username",
Password: "password",
Database: "public",
}
dsn := fmt.Sprintf("tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
m.Host, m.Port, m.Database)
dsn = fmt.Sprintf("%s:%s@%s", m.User, m.Password, dsn)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
//error handling
}
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:
type Monitor struct {
Host string `gorm:"column:host;primaryKey"`
Ts time.Time `gorm:"column:ts;primaryKey"`
Cpu float64 `gorm:"column:cpu"`
}
func (Monitor) TableName() string {
return "monitor"
}
var monitor Monitor
db.Raw("SELECT host, cpu, ts FROM users WHERE ts > ?", 1701360000000).Scan(&result)
type Monitor struct {
Host string `gorm:"column:host;primaryKey"`
Ts time.Time `gorm:"column:ts;primaryKey"`
Cpu float64 `gorm:"column:cpu"`
}
func (Monitor) TableName() string {
return "monitor"
}
var monitor Monitor
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: