4.3. Go#

4.3.1. Requirements#

Before you can get started, please ensure that:

  • You have the latest version of the QuasarDB client library installed on your computer

  • You have access to a running QuasarDB cluster.

The rest of this document assumes you have a cluster up and running under qdb://127.0.0.1:2836.

4.3.2. Installing libraries#

# Note: the Go api requires that you have the C api installed
# See the C api for more details
go get -d github.com/bureau14/qdb-api-go

4.3.3. Importing libraries#

Most languages require you to import the relevant QuasarDB modules before you can use them, so we start out with them.

import qdb "github.com/bureau14/qdb-api-go"

4.3.4. Connection management#

Establishing a connection with the QuasarDB cluster is easy. You need the URI of at least one of your nodes, and the client will automatically detect all nodes in the cluster.

A QuasarDB cluster operates in either a secure or an insecure mode. If you do not know whether your cluster is running in secure mode, please ask your system administrator.

4.3.4.1. Insecure connection#

clusterURI := "qdb://127.0.0.1:2836"
timeoutDuration := time.Duration(120) * time.Second
handle, err := qdb.SetupHandle(clusterURI, timeoutDuration)

4.3.4.2. Secure connection#

In case of a secure connection, we need to provide a few additional parameters:

  • A username;

  • A user private key;

  • A cluster public key.

More information on QuasarDB’s security mechanisms can be found in our security manual.

If you do not know the values of these parameters, please ask your system administrator.

clusterURI := "qdb://127.0.0.1:2836"
timeoutDuration := time.Duration(120) * time.Second
clusterPublicKeyPath := "/path/to/cluster_public.key"
usersPrivateKeyPath := "/path/to/user_private.key"
handle, err := qdb.SetupSecuredHandle(
    clusterURI,
    clusterPublicKeyPath,
    usersPrivateKeyPath,
    timeoutDuration,
    qdb.EncryptNone,
)

4.3.5. Creating a table#

Before we can store timeseries data, we need to create a table. A table is uniquely identified by a name (e.g. “stocks” or “sensors”) and can have 1 or more columns.

In this example we will create a table “stocks” with three columns, “open”, “close” and “volume”. The respective types of the columns are two double precision floating point values and a 64-bit signed integer.

table := handle.Timeseries("stocks")
columnsInfo := []qdb.TsColumnInfo{
    qdb.NewTsColumnInfo("open", qdb.TsColumnDouble),
    qdb.NewTsColumnInfo("close", qdb.TsColumnDouble),
    qdb.NewTsColumnInfo("volume", qdb.TsColumnInt64),
}
shardSizeDuration := 24 * time.Hour

err := table.Create(shardSizeDuration, columnsInfo...)

4.3.5.1. Attaching tags#

QuasarDB allows you to manage your tables by attaching tags to them. For more information about tags, see Managing tables with Tags.

In the example below, we will attach the tag nasdaq to the “stocks” table we created.

// Once you've created a table you can attach tags to it
err = table.AttachTag("nasdaq")

4.3.6. A word about API types#

Now that we have our tables in place, it’s time to start interacting with actual data. On a high-level, QuasarDB provides two different APIs for you to insert data:

  • A row-based API, where you insert data on a row-by-row basis. This API is referred to as our “batch inserter”. This API provides stronger guarantees in terms of consistency.

  • A column-based API, where you insert pure timeseries data per column. This data is typically aligned per timestamp, and therefor assumes unique timestamps.

If you’re unsure which API is best for you, start out with the row-based insertion API, the batch inserter.

You should now continue with either the row oriented or the column oriented tutorials.

4.3.7. Row oriented API#

4.3.7.1. Batch inserter#

The QuasarDB batch inserter provides you with a row-oriented interface to send data to the QuasarDB cluster. The data is buffered client-side and sent in batches, ensuring efficiency and consistency.

The batch writer has various modes of operation, each with different tradeoffs:

Insertion mode

Description

Use case(s)

Default

Transactional insertion mode that employs Copy-on-Write

General purpose

Fast

Transactional insert that does not employ Copy-on-Write. Newly written data may be visible to queries before the transaction is fully completed.

Streaming data, many small incremental writes

Asynchronous

Data is buffered in-memory in the QuasarDB daemon nodes before writing to disk. Data from multiple sources is buffered together, and periodically flushed to disk.

Streaming data where multiple processes simultaneously write into the same table(s)

Truncate (a.k.a. “upsert”)

Replaces any existing data with the provided data.

Replay of historical data

When in doubt, we recommend you use the default insertion mode.

The steps involved in using the batch writer API is as follows:

  1. Initialize a local batch inserter instance, providing it with the tables and columns you want to insert data for. Note that specifying multiple tables is supported: this will allow you to insert data into multiple tables in one atomic operation.

  2. Prepare/buffer the batch you want to insert. Buffering locally before sending ensures that the tranmission of the data is happening at maximum throughput, ensuring server-side efficiency.

  3. Push the batch to the cluster.

  4. If necessary, go back to step 2 to send additional batches.

We recommend you use batch sizes as large as possible: between 50k and 500k rows is optimal.

In the example below we will insert two different rows for two separate days into our “stocks” table.

batchColumnInfo := []qdb.TsBatchColumnInfo{
    qdb.NewTsBatchColumnInfo("stocks", "open", 2),
    qdb.NewTsBatchColumnInfo("stocks", "close", 2),
    qdb.NewTsBatchColumnInfo("stocks", "volume", 2),
}

batch, err := handle.TsBatch(batchColumnInfo...)
if err != nil {
    return err
}

batch.StartRow(time.Unix(1548979200, 0))
batch.RowSetDouble(0, 3.40)
batch.RowSetDouble(1, 3.50)
batch.RowSetInt64(2, 10000)

batch.StartRow(time.Unix(1549065600, 0))
batch.RowSetDouble(0, 3.50)
batch.RowSetDouble(1, 3.55)
batch.RowSetInt64(2, 7500)

err = batch.Push()

4.3.7.2. Bulk reader#

On the other side of the row-oriented API we have the “bulk reader”. The bulk reader provides streaming access to a single table, optionally limited by certain columns and/or certain time ranges.

If you want to have efficient row-oriented access to the raw data in a table, this is the API you want to use. If you want to execute aggregates, complex where clauses and/or multi-table joins, please see the query API.

The example below will show you how to read our stock data for just a single day.

table := handle.Timeseries("stocks")
bulk, err := table.Bulk()
if err != nil {
    return err
}

err = bulk.GetRanges(qdb.NewRange(time.Unix(1548979200, 0), time.Unix(1549065601, 0)))
if err != nil {
    return err
}

for {
    timestamp, err := bulk.NextRow()
    if err != nil {
        break
    }

    open, err := bulk.GetDouble()
    if err != nil {
        return err
    }
    close, err := bulk.GetDouble()
    if err != nil {
        return err
    }
    volume, err := bulk.GetInt64()
    if err != nil {
        return err
    }

    fmt.Printf("timestamp: %s, open: %v, close: %v, volume: %v\n", timestamp, open, close, volume)
}

The next section will show you how to store and retrieve the same dataset using the column-oriented API. If this is irrelevant to you, it’s safe to skip directly to the query API.

4.3.8. Column oriented API#

The other high level APIs QuasarDB offers are the column-oriented API. These APIs are more lightweight than the row-oriented APIs, and provides a good alternative if your dataset is shaped correctly.

4.3.8.1. Storing timeseries#

To store a single timeseries, all you have to do is provide a sequence of timestamp / value pairs, and which column you want to store them as.

table := handle.Timeseries("stocks")

openColumn := table.DoubleColumn("open")
closeColumn := table.DoubleColumn("close")
volumeColumn := table.Int64Column("volume")

t1 := time.Unix(1600000000, 0)
t2 := time.Unix(1610000000, 0)

openPoints := []qdb.TsDoublePoint{
    qdb.NewTsDoublePoint(t1, 3.40),
    qdb.NewTsDoublePoint(t2, 3.40),
}

closePoints := []qdb.TsDoublePoint{
    qdb.NewTsDoublePoint(t1, 3.50),
    qdb.NewTsDoublePoint(t2, 3.55),
}

volumePoints := []qdb.TsInt64Point{
    qdb.NewTsInt64Point(t1, 10000),
    qdb.NewTsInt64Point(t2, 7500),
}

err := openColumn.Insert(openPoints...)
if err != nil {
    return err
}

err = closeColumn.Insert(closePoints...)
if err != nil {
    return err
}

err = volumeColumn.Insert(volumePoints...)
if err != nil {
    return err
}

4.3.8.2. Retrieving timeseries#

To retrieve a single timeseries, you provide a column and one or more timerange(s). Our examples below show how to retrieve all three columns for a single day.

table := handle.Timeseries("stocks")

openColumn := table.DoubleColumn("open")
closeColumn := table.DoubleColumn("close")
volumeColumn := table.Int64Column("volume")

timeRange := qdb.NewRange(time.Unix(1600000000, 0), time.Unix(1610000001, 0))

openResults, err := openColumn.GetRanges(timeRange)
if err != nil {
    return err
}

closeResults, err := closeColumn.GetRanges(timeRange)
if err != nil {
    return err
}

volumeResults, err := volumeColumn.GetRanges(timeRange)
if err != nil {
    return err
}

for i := 0; i < 2; i++ {
    timestamp := openResults[i].Timestamp()
    open := openResults[i].Content()
    close := closeResults[i].Content()
    volume := volumeResults[i].Content()

    fmt.Printf("timestamp: %s, open: %v, close: %v, volume: %v\n", timestamp, open, close, volume)
}

4.3.9. Queries#

If you are looking for more flexible control over the kind of calculations performed on a dataset, or want to push certain computations to the cluster, QuasarDB offers an SQL-like query language for you to interact with your data. Please see our query language documentation.

In the example below, we will show you how to execute a simple query that calculates to total traded volume for the entire dataset.

query := handle.Query(fmt.Sprintf("SELECT SUM(volume) FROM stocks"))
table, err := query.Execute()
if err != nil {
    return err
}

for _, row := range table.Rows() {
    for _, col := range table.Columns(row) {
        fmt.Printf("%v ", col.Get().Value())
    }
    fmt.Println()
}

4.3.10. Dropping a table#

It’s easy to drop a table with QuasarDB, and is immediately visible to all clients.

table := handle.Timeseries("stocks")
err := table.Remove()

4.3.11. Reference#