Java

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 Java ingester SDK provided by GreptimeDB is a lightweight library with the following features:

  • SPI-based extensible network transport layer, which provides the default implementation using the gRPC framework.
  • Non-blocking, purely asynchronous API that is easy to use.
  • Automatic collection of various performance metrics by default. You can then configure and write them to local files.
  • Ability to take in-memory snapshots of critical objects, configure them, and write them to local files. This is helpful for troubleshooting complex issues.

Installation

  1. Install the Java Development Kit(JDK)

Make sure that your system has JDK 8 or later installed. For more information on how to check your version of Java and install the JDK, see the Oracle Overview of JDK Installation documentation

  1. Add GreptiemDB Java SDK as a Dependency

If you are using Maven, add the following to your pom.xml dependencies list:

  1. <dependency>
  2. <groupId>io.greptime</groupId>
  3. <artifactId>ingester-all</artifactId>
  4. <version>0.7.3</version>
  5. </dependency>

The latest version can be viewed here.

After configuring your dependencies, make sure they are available to your project. This may require refreshing the project in your IDE or running the dependency manager.

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.

The following code demonstrates how to connect to GreptimeDB with the simplest configuration. For customizing the connection options, please refer to API Documentation. Please pay attention to the accompanying comments for each option, as they provide detailed explanations of their respective roles.

  1. // GreptimeDB has a default database named "public" in the default catalog "greptime",
  2. // we can use it as the test database
  3. String database = "public";
  4. // By default, GreptimeDB listens on port 4001 using the gRPC protocol.
  5. // We can provide multiple endpoints that point to the same GreptimeDB cluster.
  6. // The client will make calls to these endpoints based on a load balancing strategy.
  7. String[] endpoints = {"127.0.0.1:4001"};
  8. // Sets authentication information.
  9. AuthInfo authInfo = new AuthInfo("username", "password");
  10. GreptimeOptions opts = GreptimeOptions.newBuilder(endpoints, database)
  11. // If the database does not require authentication, we can use AuthInfo.noAuthorization() as the parameter.
  12. .authInfo(authInfo)
  13. // Enable secure connection if your server is secured by TLS
  14. //.tlsOptions(new TlsOptions())
  15. // A good start ^_^
  16. .build();
  17. GreptimeDB client = GreptimeDB.create(opts);

For customizing the connection options, please refer to API Documentation.

Data model

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.

Low-level API

The GreptimeDB low-level API provides a straightforward method to write data to GreptimeDB by adding rows to the table object with a predefined schema.

Create row objects

This following code snippet begins by constructing a table named cpu_metric, which includes columns host, cpu_user, cpu_sys, and ts. Subsequently, it inserts a single row into the table.

The table consists of three types of columns:

  • Tag: The host column, with values of type String.
  • Field: The cpu_user and cpu_sys columns, with values of type Float.
  • Timestamp: The ts column, with values of type Timestamp.
  1. // Construct the table schema for CPU metrics
  2. TableSchema cpuMetricSchema = TableSchema.newBuilder("cpu_metric")
  3. .addTag("host", DataType.String) // Identifier for the host
  4. .addTimestamp("ts", DataType.TimestampMillisecond) // Timestamp in milliseconds
  5. .addField("cpu_user", DataType.Float64) // CPU usage by user processes
  6. .addField("cpu_sys", DataType.Float64) // CPU usage by system processes
  7. .build();
  8. // Create the table from the defined schema
  9. Table cpuMetric = Table.from(cpuMetricSchema);
  10. // Example data for a single row
  11. String host = "127.0.0.1"; // Host identifier
  12. long ts = System.currentTimeMillis(); // Current timestamp
  13. double cpuUser = 0.1; // CPU usage by user processes (in percentage)
  14. double cpuSys = 0.12; // CPU usage by system processes (in percentage)
  15. // Insert the row into the table
  16. // NOTE: The arguments must be in the same order as the columns in the defined schema: host, ts, cpu_user, cpu_sys
  17. cpuMetric.addRow(host, ts, cpuUser, cpuSys);

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

  1. // Creates schemas
  2. TableSchema cpuMetricSchema = TableSchema.newBuilder("cpu_metric")
  3. .addTag("host", DataType.String)
  4. .addTimestamp("ts", DataType.TimestampMillisecond)
  5. .addField("cpu_user", DataType.Float64)
  6. .addField("cpu_sys", DataType.Float64)
  7. .build();
  8. TableSchema memMetricSchema = TableSchema.newBuilder("mem_metric")
  9. .addTag("host", DataType.String)
  10. .addTimestamp("ts", DataType.TimestampMillisecond)
  11. .addField("mem_usage", DataType.Float64)
  12. .build();
  13. Table cpuMetric = Table.from(cpuMetricSchema);
  14. Table memMetric = Table.from(memMetricSchema);
  15. // Adds row data items
  16. for (int i = 0; i < 10; i++) {
  17. String host = "127.0.0." + i;
  18. long ts = System.currentTimeMillis();
  19. double cpuUser = i + 0.1;
  20. double cpuSys = i + 0.12;
  21. cpuMetric.addRow(host, ts, cpuUser, cpuSys);
  22. }
  23. for (int i = 0; i < 10; i++) {
  24. String host = "127.0.0." + i;
  25. long ts = System.currentTimeMillis();
  26. double memUsage = i + 0.2;
  27. memMetric.addRow(host, ts, memUsage);
  28. }

Insert data

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

  1. // Saves data
  2. // For performance reasons, the SDK is designed to be purely asynchronous.
  3. // The return value is a future object. If you want to immediately obtain
  4. // the result, you can call `future.get()`.
  5. CompletableFuture<Result<WriteOk, Err>> future = greptimeDB.write(cpuMetric, memMetric);
  6. Result<WriteOk, Err> result = future.get();
  7. if (result.isOk()) {
  8. LOG.info("Write result: {}", result.getOk());
  9. } else {
  10. LOG.error("Failed to write: {}", result.getErr());
  11. }

Streaming insert

Streaming insert is useful when you want to insert a large amount of data such as importing historical data.

  1. StreamWriter<Table, WriteOk> writer = greptimeDB.streamWriter();
  2. // write data into stream
  3. writer.write(cpuMetric);
  4. writer.write(memMetric);
  5. // You can perform operations on the stream, such as deleting the first 5 rows.
  6. writer.write(cpuMetric.subRange(0, 5), WriteOp.Delete);

Close the stream writing after all data has been written. In general, you do not need to close the stream writing when continuously writing data.

  1. // complete the stream
  2. CompletableFuture<WriteOk> future = writer.completed();
  3. WriteOk result = future.get();
  4. LOG.info("Write result: {}", result);

Update data

Please refer to update data for the updating mechanism. In the following code, we first save a row and then use the same tag and time index to identify the row for updating.

  1. Table cpuMetric = Table.from(myMetricCpuSchema);
  2. // insert a row data
  3. long ts = 1703832681000L;
  4. cpuMetric.addRow("host1", ts, 0.23, 0.12);
  5. Result<WriteOk, Err> putResult = greptimeDB.write(cpuMetric).get();
  6. // update the row data
  7. Table newCpuMetric = Table.from(myMetricCpuSchema);
  8. // The same tag `host1`
  9. // The same time index `1703832681000`
  10. // The new value: cpu_user = `0.80`, cpu_sys = `0.11`
  11. long ts = 1703832681000L;
  12. myMetricCpuSchema.addRow("host1", ts, 0.80, 0.11);
  13. // overwrite the existing data
  14. CompletableFuture<Result<WriteOk, Err>> future = greptimeDB.write(myMetricCpuSchema);
  15. Result<WriteOk, Err> result = future.get();

High-level API

The high-level API uses an ORM style object to write data to GreptimeDB. It allows you to create, insert, and update data in a more object-oriented way, providing developers with a friendlier experience. However, it is not as efficient as the low-level API. This is because the ORM style object may consume more resources and time when converting the objects.

Create row objects

GreptimeDB Java Ingester SDK allows us to use basic POJO objects for writing. This approach requires the use of Greptime’s own annotations, but they are easy to use.

  1. @Metric(name = "cpu_metric")
  2. public class Cpu {
  3. @Column(name = "host", tag = true, dataType = DataType.String)
  4. private String host;
  5. @Column(name = "ts", timestamp = true, dataType = DataType.TimestampMillisecond)
  6. private long ts;
  7. @Column(name = "cpu_user", dataType = DataType.Float64)
  8. private double cpuUser;
  9. @Column(name = "cpu_sys", dataType = DataType.Float64)
  10. private double cpuSys;
  11. // getters and setters
  12. // ...
  13. }
  14. @Metric(name = "mem_metric")
  15. public class Memory {
  16. @Column(name = "host", tag = true, dataType = DataType.String)
  17. private String host;
  18. @Column(name = "ts", timestamp = true, dataType = DataType.TimestampMillisecond)
  19. private long ts;
  20. @Column(name = "mem_usage", dataType = DataType.Float64)
  21. private double memUsage;
  22. // getters and setters
  23. // ...
  24. }
  25. // Add rows
  26. List<Cpu> cpus = new ArrayList<>();
  27. for (int i = 0; i < 10; i++) {
  28. Cpu c = new Cpu();
  29. c.setHost("127.0.0." + i);
  30. c.setTs(System.currentTimeMillis());
  31. c.setCpuUser(i + 0.1);
  32. c.setCpuSys(i + 0.12);
  33. cpus.add(c);
  34. }
  35. List<Memory> memories = new ArrayList<>();
  36. for (int i = 0; i < 10; i++) {
  37. Memory m = new Memory();
  38. m.setHost("127.0.0." + i);
  39. m.setTs(System.currentTimeMillis());
  40. m.setMemUsage(i + 0.2);
  41. memories.add(m);
  42. }

Insert data

Write data with POJO objects:

  1. // Saves data
  2. CompletableFuture<Result<WriteOk, Err>> puts = greptimeDB.writeObjects(cpus, memories);
  3. Result<WriteOk, Err> result = puts.get();
  4. if (result.isOk()) {
  5. LOG.info("Write result: {}", result.getOk());
  6. } else {
  7. LOG.error("Failed to write: {}", result.getErr());
  8. }

Streaming insert

Streaming insert is useful when you want to insert a large amount of data such as importing historical data.

  1. StreamWriter<List<?>, WriteOk> writer = greptimeDB.objectsStreamWriter();
  2. // write data into stream
  3. writer.write(cpus);
  4. writer.write(memories);
  5. // You can perform operations on the stream, such as deleting the first 5 rows.
  6. writer.write(cpus.subList(0, 5), WriteOp.Delete);

Close the stream writing after all data has been written. In general, you do not need to close the stream writing when continuously writing data.

  1. // complete the stream
  2. CompletableFuture<WriteOk> future = writer.completed();
  3. WriteOk result = future.get();
  4. LOG.info("Write result: {}", result);

Update data

Please refer to update data for the updating mechanism. In the following code, we first save a row and then use the same tag and time index to identify the row for updating.

  1. Cpu cpu = new Cpu();
  2. cpu.setHost("host1");
  3. cpu.setTs(1703832681000L);
  4. cpu.setCpuUser(0.23);
  5. cpu.setCpuSys(0.12);
  6. // insert a row data
  7. Result<WriteOk, Err> putResult = greptimeDB.writeObjects(cpu).get();
  8. // update the row data
  9. Cpu newCpu = new Cpu();
  10. // The same tag `host1`
  11. newCpu.setHost("host1");
  12. // The same time index `1703832681000`
  13. newCpu.setTs(1703832681000L);
  14. // The new value: cpu_user = `0.80`, cpu_sys = `0.11`
  15. cpu.setCpuUser(0.80);
  16. cpu.setCpuSys(0.11);
  17. // overwrite the existing data
  18. Result<WriteOk, Err> updateResult = greptimeDB.writeObjects(newCpu).get();

More examples

For fully runnable code snippets and the complete code of the demo, please refer to the Examples.

Debug logs

The ingester SDK provides metrics and logs for debugging. Please refer to Metrics & Display and Magic Tools to learn how to enable or disable the logs.

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.

Java database connectivity (JDBC) is the JavaSoft specification of a standard application programming interface (API) that allows Java programs to access database management systems.

Many databases, such as MySQL or PostgreSQL, have implemented their own drivers based on the JDBC API. Since GreptimeDB supports multiple protocols, we use MySQL as an example to demonstrate how to use JDBC. If you want to use other protocols, just replace the MySQL driver with the corresponding driver.

Installation

If you are using Maven, add the following to your pom.xml dependencies list:

  1. <!-- MySQL usage dependency -->
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <version>8.0.33</version>
  6. </dependency>

Connect to database

The following example shows how to connect to GreptimeDB:

Here we will use MySQL as an example to demonstrate how to connect to GreptimeDB.

  1. public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
  2. Properties prop = new Properties();
  3. prop.load(QueryJDBC.class.getResourceAsStream("/db-connection.properties"));
  4. String dbName = (String) prop.get("db.database-driver");
  5. String dbConnUrl = (String) prop.get("db.url");
  6. String dbUserName = (String) prop.get("db.username");
  7. String dbPassword = (String) prop.get("db.password");
  8. Class.forName(dbName);
  9. Connection dbConn = DriverManager.getConnection(dbConnUrl, dbUserName, dbPassword);
  10. return Objects.requireNonNull(dbConn, "Failed to make connection!");
  11. }

You need a properties file to store the DB connection information. Place it in the Resources directory and name it db-connection.properties. The file content is as follows:

  1. # DataSource
  2. db.database-driver=com.mysql.cj.jdbc.Driver
  3. db.url=jdbc:mysql://localhost:4002/public
  4. db.username=
  5. db.password=

Or you can just get the file from here.

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.

  1. try (Connection conn = getConnection()) {
  2. Statement statement = conn.createStatement();
  3. // DESC table;
  4. ResultSet rs = statement.executeQuery("DESC cpu_metric");
  5. LOG.info("Column | Type | Key | Null | Default | Semantic Type ");
  6. while (rs.next()) {
  7. LOG.info("{} | {} | {} | {} | {} | {}",
  8. rs.getString(1),
  9. rs.getString(2),
  10. rs.getString(3),
  11. rs.getString(4),
  12. rs.getString(5),
  13. rs.getString(6));
  14. }
  15. // SELECT COUNT(*) FROM cpu_metric;
  16. rs = statement.executeQuery("SELECT COUNT(*) FROM cpu_metric");
  17. while (rs.next()) {
  18. LOG.info("Count: {}", rs.getInt(1));
  19. }
  20. // SELECT * FROM cpu_metric ORDER BY ts DESC LIMIT 5;
  21. rs = statement.executeQuery("SELECT * FROM cpu_metric ORDER BY ts DESC LIMIT 5");
  22. LOG.info("host | ts | cpu_user | cpu_sys");
  23. while (rs.next()) {
  24. LOG.info("{} | {} | {} | {}",
  25. rs.getString("host"),
  26. rs.getTimestamp("ts"),
  27. rs.getDouble("cpu_user"),
  28. rs.getDouble("cpu_sys"));
  29. }
  30. }

For the complete code of the demo, please refer to here.

Query library reference

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