Read and write data

Updated at:

Use the DataHub Java SDK to read and write data.

Usage notes

  • You can read data from shards in the CLOSED or ACTIVE state.

  • You can write data only to shards in the ACTIVE state.

Important

We recommend using the High-Level SDK for reading and writing unless you have specific requirements. The High-Level SDK wraps the read/write APIs of the Low-Level SDK and is better suited for data I/O scenarios. For details, see Producer.

Read data

1. Obtain a cursor.

  • To read data from a topic, specify a shard and a cursor. There are four cursor types:

    • OLDEST: Points to the oldest available record in the shard.

    • LATEST: Points to the most recently written record.

    • SEQUENCE: Points to a record at a specified sequence number.

    • SYSTEM_TIME: Points to the first record with a timestamp equal to or greater than the specified timestamp.

  • Cursor selection guidelines:

    • To read data from the beginning, use OLDEST.

    • To check the most recent data, use LATEST.

    • To read the last N records, use SEQUENCE with SEQUENCE - N.

    • To sample and validate data after a specific point in time, use SYSTEM_TIME. Data reading starts from the position at SEQUENCE + 1.

    Note

    Ensure the data is within its retention period. Otherwise, a read operation will fail.

  1. Once a cursor is obtained, pass it to the getRecords method.

    Note

    DataHub provides a subscription feature for data consumption. The read operation is primarily for sampling and data validation.

Obtain a cursor

Parameters

Name

Type

Description

projectName

String

The project name.

topicName

String

The topic name.

shardId

String

The shard ID.

CursorType

CursorType

The cursor type. Valid values: OLDEST, LATEST, SYSTEM_TIME, and SEQUENCE.

Exception description

Class name

Error code

Exception description

DatahubClientException

-

The base class for all exceptions.

SeekOutOfRangeException

SeekOutOfRange

When calling getCursor, the specified sequence is out of the valid range (typically because the data has expired), or the specified timestamp is later than the current time.

Code examples

Get a cursor from the beginning (OLDEST).

public static void getCursor(String projectName, String topicName) {
    String shardId = "5";
    try {
        /* Example: Using OLDEST cursor type */
        String oldestCursor = datahubClient.getCursor(projectName, topicName, shardId, CursorType.OLDEST).getCursor();
        System.out.println("get cursor successful");
    } catch (DatahubClientException e) {
        System.out.println(e.getErrorMessage());
    }
}

Read the latest record(s).

To retrieve the latest N records, obtain the sequence number of the most recently written data, and then use it to get the corresponding cursor.

public static void getCursor(String projectName, String topicName) {
    String shardId = "5";
    try {
        /* Example: Using LATEST cursor type */
        String latestCursor = datahubClient.getCursor(projectName, topicName, shardId, CursorType.LATEST).getCursor();

        /* Example: Using SEQUENCE cursor type */
        // Get the sequence number of the latest record
        long seq = datahubClient.getCursor(projectName, topicName, shardId, CursorType.LATEST).getSequence();

        // Get the cursor pointing to the position of the last 10 records
        String seqCursor = datahubClient.getCursor(projectName, topicName, shardId, CursorType.SEQUENCE, seq - 9).getCursor();
    } catch (DatahubClientException e) {
        System.out.println(e.getErrorMessage());
    }

Get a cursor by timestamp (SYSTEM_TIME).

Convert the Date to a timestamp before obtaining the cursor.

public static void getcursor(String projectName,String topicName) {
    String shardId = "5";
    try {
        //Convert the date string to a timestamp
        String time = "2019-07-01 10:00:00";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long timestamp = 0L;
        try {
            Date date = simpleDateFormat.parse(time);
            timestamp = date.getTime();// Get the timestamp in milliseconds
            // System.out.println(timestamp);
        } 
     // Get the cursor pointing to the data position after the specified time
        String timeCursor = datahubClient.getCursor(projectName, topicName, shardId, CursorType.SYSTEM_TIME, timestamp).getCursor();
        System.out.println("get cursor successful");
    } catch (DatahubClientException e) {
        System.out.println(e.getErrorMessage());  
    } catch (ParseException e) {
            System.out.println(e.getErrorOffset());
        }
}

Read data using the getRecords operation

Parameters

Name

Type

Description

projectName

String

The project name.

topicName

String

The topic name.

shardId

String

The shard ID.

schema

RecordSchema

The table schema. This parameter is required for Tuple-type topics and not applicable to Blob-type topics.

cursor

String

The cursor.

Exception description

Class name

Error code

Exception description

DatahubClientException

-

The base class for all exceptions.

Code examples

  • Read data from a tuple topic.

    public static void example(String projectName, String topicName) {
        // Maximum number of records to read per request
        int recordLimit = 1000;
        String shardId = "7";
    
        // Get the cursor pointing to the oldest available record
        // Note: Normally, getCursor is called only once during initialization,
        // then getRecords should use the nextCursor for subsequent reads
        String cursor = "";
        try {
            cursor = datahubClient.getCursor(projectName, topicName, shardId, CursorType.OLDEST).getCursor();
        } catch (DatahubClientException e) {
            System.out.println(e.getErrorMessage());
        }
    
        while (true) {
            try {
                GetRecordsResult result = datahubClient.getRecords(projectName, topicName, shardId, recordSchema, cursor, recordLimit);
                if (result.getRecordCount() <= 0) {
                    // No data available, sleep before retrying
                    Thread.sleep(10000);
                    continue;
                }
    
                for (RecordEntry entry : result.getRecords()) {
                    TupleRecordData data = (TupleRecordData) entry.getRecordData();
                    System.out.println("field1: " + data.getField("field1") + "\t"
                            + "field2: " + data.getField("field2"));
                }
    
                // Get the next cursor for the next read
                cursor = result.getNextCursor();
            } catch (InvalidCursorException ex) {
                // The cursor is invalid or has expired. It is recommended to reacquire the cursor before resuming consumption
                cursor = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.OLDEST).getCursor();
            } catch (DatahubClientException e) {
                System.out.println(e.getErrorMessage());
            }
        }
    }
    
  • Read data from a blob topic.

    public static void example(String projectName, String topicName) {
        // Maximum number of records to read per request
        int recordLimit = 1000;
        String shardId = "7";
    
        // Get the cursor pointing to the oldest available record
        // Note: Normally, getCursor is called only once during initialization,
        // then getRecords should use the nextCursor for subsequent reads
        String cursor = "";
        try {
            cursor = datahubClient.getCursor(projectName, blobTopicName, shardId, CursorType.OLDEST).getCursor();
        } catch (DatahubClientException e) {
            System.out.println(e.getErrorMessage());     
        }
    
        while (true) {
            try {
                GetRecordsResult result = datahubClient.getRecords(projectName, blobTopicName, shardId, recordSchema, cursor, recordLimit);
                if (result.getRecordCount() <= 0) {
                    // No data available. Sleep before the next read attempt.
                    Thread.sleep(10000);
                    continue;
                }
    
                /* Consume the data */
                for (RecordEntry record : result.getRecords()) {
                    BlobRecordData data = (BlobRecordData) record.getRecordData();
                    System.out.println(new String(data.getData()));
                }
    
                // Get the next cursor for the following read
                cursor = result.getNextCursor();
            } catch (InvalidCursorException ex) {
                // The cursor is invalid or expired. It is recommended to reacquire the cursor before resuming consumption
                cursor = datahubClient.getCursor(Constant.projectName, Constant.blobTopicName, shardId, CursorType.OLDEST).getCursor();
            } catch (DatahubClientException e) {
                System.out.println(e.getErrorMessage()); 
            } 
        }
    }
    

Write data

Starting from version 2.12, the server supports the putRecordsByShard operation. In earlier versions, only the putRecords operation is available. With putRecordsByShard, you must specify the target shard; otherwise, data is written to the first shard in the ACTIVE state by default. Both operations accept a List of RecordEntry objects as the records parameter, and all records must be of the same type—either Tuple or Blob. DataHub supports two types of data writing:

  • Shard-specific writing (server version 2.12 or later), using the putRecordsByShard operation.

  • Mixed-shard writing, using the putRecords operation.

With putRecords operation, check the PutRecordsResult to determine whether the write succeeded. In contrast, putRecordsByShard operation indicates success or failure directly through exceptions. If the server version supports it, use putRecordsByShard.

Parameters

Name

Type

Description

projectName

String

The project name.

topicName

String

The topic name.

shardId

String

The shard ID.

Exception description

Class name

Error code

Exception description

DatahubClientException

-

The base class for all exceptions.

Code examples

  • Write tuple-type data

    // Write tuple-type data
    public static void tupleExample(String project, String topic, int retryTimes) {
        // Get the record schema
        RecordSchema recordSchema = datahubClient.getTopic(project, topic).getRecordSchema();
    
        // Generate 10 records
        List<RecordEntry> recordEntries = new ArrayList<>();
        for (int i = 0; i < 10; ++i) {
            RecordEntry recordEntry = new RecordEntry();
            // Set custom attributes for each record, such as IP or hostname. Optional — not required for writing data.
            recordEntry.addAttribute("key1", "value1");
    
            TupleRecordData data = new TupleRecordData(recordSchema);
            data.setField("field1", "HelloWorld");
            data.setField("field2", 1234567);
            recordEntry.setRecordData(data);
            recordEntries.add(recordEntry);
        }
    
        try {
            PutRecordsResult result = datahubClient.putRecords(project, topic, recordEntries);
            int failedCount = result.getFailedRecordCount();
            if (failedCount > 0) {
                retry(datahubClient, result.getFailedRecords(), retryTimes, project, topic);
            }
        } catch (DatahubClientException e) {
            System.out.println("requestId: " + e.getRequestId() + "\tmessage: " + e.getErrorMessage());
        }
    }
    
    // Retry mechanism
    public static void retry(DatahubClient client, List<RecordEntry> records, int retryTimes, String project, String topic) {
        boolean success = false;
        while (retryTimes != 0) {
            retryTimes = retryTimes - 1;
            PutRecordsResult result = client.putRecords(project, topic, records);
            if (result.getFailedRecordCount() > 0) {
                retry(client, result.getFailedRecords(), retryTimes, project, topic);
            }
            success = true;
            break;
        }
        if (!success) {
            System.out.println("retryFailure");
        }
    }

    Write blob-type data

    // Write blob-type data
    public static void blobExample() {
        // Generate 10 records
        List<RecordEntry> recordEntries = new ArrayList<>();
        String shardId = "4";
    
        for (int i = 0; i < 10; ++i) {
            RecordEntry recordEntry = new RecordEntry();
            // Set custom attributes for each record
            recordEntry.addAttribute("key1", "value1");
    
            BlobRecordData data = new BlobRecordData("123456".getBytes(Charsets.UTF_8));
            recordEntry.setRecordData(data);
            recordEntry.setShardId(shardId);
            recordEntries.add(recordEntry);
    
            // Override shard ID — note: the final shard ID set is "0"
            recordEntry.setShardId("0");
        }
    
        while (true) {
            try {
                // Supported from server version 2.12. For earlier versions, use putRecords instead.
                // datahubClient.putRecordsByShard(Constant.projectName, Constant.topicName, shardId, recordEntries);
                datahubClient.putRecords(Constant.projectName, Constant.topicName, recordEntries);
                System.out.println("write data successful");
                break;
            } catch (DatahubClientException e) {
                System.out.println(e.getErrorMessage());
            }
        }
    }
    
  • Multiple write methods

    Before DataHub version 2.12, only the putRecords operation was available. The RecordEntry class includes three attributes—shardId, partitionKey, and hashKey—that control which shard receives the data.

    Note

    Starting from version 2.12, use the putRecordsByShard operation to avoid performance degradation caused by server-side partitioning.

    • Write by ShardId (recommended):

      RecordEntry entry = new RecordEntry();
      entry.setShardId("0");
    • Write by hashKey

      Specify a 128-bit MD5 hash value. The system determines the target shard based on the hash and shard configuration.

      RecordEntry entry = new RecordEntry();
      entry.setHashKey("7FFFFFFFFFFFFFFD7FFFFFFFFFFFFFFD");
    • Write by partitionKey

      Specify a string value as the partitionKey. The system determines the target shard based on the MD5 value of the string and shard configuration.

      RecordEntry entry = new RecordEntry();
      entry.setPartitionKey("TestPartitionKey");