Skip to content
On this page

Go

Insert

To begin with, we have to prepare a Series, which delegates one row data. There are three kind fields in Series you can use:

KindDescription
Tagindex column, helps to retrieve data more efficiently
Fieldvalue column, helps to analysis, aggregation, calculating, etc,.
Timestamptimestamp column, each table MUST have exactly one timestamp column

then, you can add one Series into Metric, then create an InsertRequest and call client.Insert to store the data into GreptimeDB.

Metric can change the Timestamp precision by metric.SetTimePrecision. The following is the supported options:

PrecisionDescription
time.Second
time.Milliseconddefault
time.Microsecond
time.Nanosecond
go
func Insert() {
    series := greptime.Series{}              // Create one row of data
    series.AddStringTag("host", "localhost") // add index column, for query efficiency
    series.AddFloatField("cpu", 0.90)        // add value column
    series.AddIntField("memory", 1024)       // add value column
    series.SetTimestamp(time.Now())          // requird

    metric := greptime.Metric{} // Create a Metric and add the Series
    metric.AddSeries(series)
    // metric.SetTimePrecision(time.Second)  // default is Millisecond
    // metric.SetTimestampAlias("timestamp") // default is 'ts'


    // Create an InsertRequest using fluent style
    // the specified table will be created automatically if it's not exist
    insertRequest := greptime.InsertRequest{}
    // if you want to specify another database, you can specify it via: `WithDatabase(database)`
    insertRequest.WithTable("monitor").WithMetric(metric) // .WithDatabase(database)

    // Fire the real Insert request and Get the affected number of rows
    n, err := client.Insert(context.Background(), insertRequest)
    if err != nil {
        fmt.Printf("fail to insert, err: %+v\n", err)
        return
    }
    fmt.Printf("AffectedRows: %d\n", n)
}