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:

xml

  1. <dependency>
  2. <groupId>io.greptime</groupId>
  3. <artifactId>ingester-all</artifactId>
  4. <version>${latest_version}</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.

java

  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. // A good start ^_^
  14. .build();
  15. GreptimeDB client = GreptimeDB.create(opts);

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

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 Java ingester SDK uses Table to denote multiple rows in a table. We can add row data items into the Table object, which are then written into GreptimeDB.

On the other hand, there is an alternative approach that 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.

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.

java

  1. // Creates schemas
  2. TableSchema cpuMetricSchema = TableSchema.newBuilder("cpu_metric") //
  3. .addColumn("host", SemanticType.Tag, DataType.String) //
  4. .addColumn("ts", SemanticType.Timestamp, DataType.TimestampMillisecond) //
  5. .addColumn("cpu_user", SemanticType.Field, DataType.Float64) //
  6. .addColumn("cpu_sys", SemanticType.Field, DataType.Float64) //
  7. .build();
  8. Table cpuMetric = Table.from(cpuMetricSchema);
  9. String host = "127.0.0.1";
  10. long ts = System.currentTimeMillis();
  11. double cpuUser = 0.1;
  12. double cpuSys = 0.12;
  13. cpuMetric.addRow(host, ts, cpuUser, cpuSys);

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

java

  1. // Creates schemas
  2. TableSchema cpuMetricSchema = TableSchema.newBuilder("cpu_metric") //
  3. .addColumn("host", SemanticType.Tag, DataType.String) //
  4. .addColumn("ts", SemanticType.Timestamp, DataType.TimestampMillisecond) //
  5. .addColumn("cpu_user", SemanticType.Field, DataType.Float64) //
  6. .addColumn("cpu_sys", SemanticType.Field, DataType.Float64) //
  7. .build();
  8. TableSchema memMetricSchema = TableSchema.newBuilder("mem_metric") //
  9. .addColumn("host", SemanticType.Tag, DataType.String) //
  10. .addColumn("ts", SemanticType.Timestamp, DataType.TimestampMillisecond) //
  11. .addColumn("mem_usage", SemanticType.Field, 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. }

Or we can build data with POJO objects:

java

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

Save rows

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

java

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

We also can write with POJO objects:

java

  1. // Saves data
  2. CompletableFuture<Result<WriteOk, Err>> puts = greptimeDB.writePOJOs(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. }

Update rows

Please refer to update data for the updating mechanism. The following example shows saving a row and then updating the row.

java

  1. Table cpuMetric = Table.from(myMetricCpuSchema);
  2. // save 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.81`
  11. long ts = 1703832681000L;
  12. myMetricCpuSchema.addRow("host1", ts, 0.80, 0.81);
  13. // overwrite the existing data
  14. Result<WriteOk, Err> updateResult = greptimeDB.write(myMetricCpuSchema).get();

Or we can update with POJO objects:

java

  1. Cpu cpu = new Cpu();
  2. cpu.setHost("host1");
  3. cpu.setTs(1703832681000L);
  4. cpu.setCpuUser(0.23);
  5. cpu.setCpuSys(0.12);
  6. // save a row data
  7. Result<WriteOk, Err> putResult = greptimeDB.writePOJOs(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.81`
  15. cpu.setCpuUser(0.80);
  16. cpu.setCpuSys(0.81);
  17. // overwrite the existing data
  18. Result<WriteOk, Err> updateResult = greptimeDB.writePOJOs(newCpu).get();

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

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.

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.

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 mutiple 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:

xml

  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.

java

  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:

txt

  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:

java

  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: