4.2. Java#

4.2.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://

4.2.2. Installation#


4.2.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 net.quasardb.qdb.*;
import net.quasardb.qdb.ts.*;
import net.quasardb.qdb.jni.*;
import net.quasardb.qdb.exception.*;

4.2.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. Insecure connection#

Session c;

try {
    c = Session.connect(Session.SecurityOptions.ofFiles("user_private.key",
} catch (IOException ex) {
    System.err.println("Failed to read security options from disk");
} catch (ConnectionRefusedException ex) {
    System.err.println("Failed to connect to cluster, make sure server is running!");
} 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.

Session c;

try {
    c = Session.connect(Session.SecurityOptions.ofFiles("user_private.key",
} catch (IOException ex) {
    System.err.println("Failed to read security options from disk");
} catch (ConnectionRefusedException ex) {
    System.err.println("Failed to connect to cluster, make sure server is running!");

4.2.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.

Column[] definitions = {
    new Column.Double ("open"),
    new Column.Double ("close"),
    new Column.Int64 ("volume")

// This will return a reference to the newly created Table
Table t = Table.create(c, "stocks", definitions); 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.

// You can also attach a tag by only providing the table string. See the
// javadocs for other ways to call this function.

Table.attachTag(c, t, "nasdaq");

4.2.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.2.7. Row oriented API# 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


Use case(s)


Transactional insertion mode that employs Copy-on-Write

General purpose


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


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.

// We initialize a Writer here, by using the builder interface.
Writer w = Writer.builder(c).build();

// Now let's acquire a reference to the table
Table t = new Table(c, "stocks");

// Insert the first row: to start a new row, we must provide it with a mandatory
// timestamp that all values for this row will share. QuasarDB will use this timestamp
// as its primary index.
         new Timespec(Instant.ofEpochSecond(1548979200)),
         new Value[] {

// Inserting the next row is a matter of just calling append.
         new Timespec(Instant.ofEpochSecond(1549065600)),
         new Value[] {

// Now that we're done, we push the buffer as one single operation. Note that,
// because in this specific example we are using the autoFlushWriter, this would
// happen automatically under the hood every append() invocations.
w.flush(); 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.

// We first initialize the TimeRange we are looking for. Providing a timerange
// to a bulk reader is mandatory.
TimeRange[] ranges = new TimeRange[] { new TimeRange(new Timespec(Instant.ofEpochSecond(1548979200)),
                                                     new Timespec(Instant.ofEpochSecond(1549065600))) };

// In this example, we initialize a bulk reader by simply providing a session,
// table name and timerange we're interested in. For alternative ways to initialize
// a bulk reader, please refer to the javadoc of the Table class.
Reader r = Table.reader(c, "stocks", ranges);

// The reader implements an Iterator interface which allows us to traverse the rows:
while (r.hasNext()) {

    WritableRow row = r.next();

    // Each row has a timestamp which you can access as a Timespec:
    System.out.println("row timestamp: " + row.getTimestamp().toString());

    // Note that the offsets of the values array align with the offsets we used
    // when creating the table, i.e. 0 means "open", 1 means "close" and 2 means
    // "volume":
    Value[] values = row.getValues();

    Value openValue = values[0];
    Value closealue = values[1];
    Value volumeValue = values[2];

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.2.8. 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.

// We can either construct a query from a raw string like this
Query q1 = Query.of("SELECT SUM(volume) FROM stocks");

// Or we can use the QueryBuilder for more flexible query building, especially
// useful for providing e.g. ranges.
String colName = "volume";
String tableName = "stocks";

Query q2 = new QueryBuilder()
    .add("SELECT SUM(")
    .add(") FROM")

// Execute the query
Result r = q1.execute(c);

// In this case, columns[0] matches to result rows[0] and are
// our timestamps.
String[] columns = r.columns;
Row[] rows = r.rows;

// Last but not least, the Query results API also implements native Java
// streams.
Stream<Row> s = r.stream();

System.out.println("total row count: " + s.count());

4.2.9. Dropping a table#

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

// We can simply remove a table by its name.

Table.remove(c, "stocks");

4.2.10. Reference#

  • Javadoc <../../javadoc/>