Java

Insert

Data Ingestion Process

Use the following code to insert an object to GreptimeDB:

java

  1. TableSchema tableSchema = TableSchema.newBuilder(TableName.with("db_name", "monitor"))
  2. .semanticTypes(SemanticType.Tag, SemanticType.Timestamp, SemanticType.Field, SemanticType.Field)
  3. .dataTypes(ColumnDataType.String, ColumnDataType.Int64, ColumnDataType.Float64, ColumnDataType.Float64)
  4. .columnNames("host", "ts", "cpu", "memory")
  5. .build();
  6. WriteRows rows = WriteRows.newBuilder(tableSchema).build();
  7. rows.insert("127.0.0.1", System.currentTimeMillis(), 0.1, null)
  8. .insert("127.0.0.2", System.currentTimeMillis(), 0.3, 0.5)
  9. .finish();
  10. CompletableFuture<Result<WriteOk, Err>> writeFuture = greptimeDB.write(rows);
  11. writeFuture.whenComplete((result, throwable) -> {
  12. if (throwable != null) {
  13. throwable.printStackTrace();
  14. } else {
  15. System.out.println(result);
  16. }
  17. });

To begin, we must create a TableSchema and then use it to construct a WriteRows object. Since the TableSchema can be reused, caching it can prevent unnecessary construction.

Once the WriteRows object is created, data can be added to it. However, this data is only stored in memory and has not yet been sent to the server. To insert multiple rows efficiently, we use batch insertion. Once all desired data has been added to the WriteRows, remember to call its finish method before sending it to the server.

After calling the write method on our completed WriteRows, a future will be returned which allows us to obtain write results through its callback function.

Write API

java

  1. /**
  2. * Write a single table multi rows data to database.
  3. *
  4. * @param rows rows with one table
  5. * @param ctx invoke context
  6. * @return write result
  7. */
  8. CompletableFuture<Result<WriteOk, Err>> write(WriteRows rows, Context ctx);
NameDescription
rowsSeveral rows of data to write to the database (all data must belong to the same table).
ctxThe KV in ctx will be written to the gRPC headers metadata then sent to GreptimeDB server.
Result<WriteOk, Err>Inspired by Result in Rust, where WriteOk and Err only one is meaningful and the other is empty.If the call succeeds, you can extract the appropriate information from WriteOk, otherwise you need to extract useful information from Err.