How can data be deleted in HBase based on a timestamp?
In HBase, you can use the Delete class to delete data based on timestamp. Here is an example code:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
public class HBaseDeleteByTimestampExample {
private static final String TABLE_NAME = "your_table_name";
private static final String COLUMN_FAMILY = "your_column_family";
private static final String COLUMN_QUALIFIER = "your_column_qualifier";
private static final long TIMESTAMP = 1612896000000L; // 时间戳,单位为毫秒
public static void main(String[] args) throws IOException {
Configuration conf = HBaseConfiguration.create();
try (Connection connection = ConnectionFactory.createConnection(conf);
Table table = connection.getTable(Bytes.toBytes(TABLE_NAME))) {
Delete delete = new Delete(Bytes.toBytes("row_key")); // 根据行键删除数据
delete.addColumn(Bytes.toBytes(COLUMN_FAMILY), Bytes.toBytes(COLUMN_QUALIFIER), TIMESTAMP);
table.delete(delete);
System.out.println("Data deleted successfully.");
}
}
}
In the sample code above, a Delete object is first created. Then the addColumn method is used to specify the column family, column qualifier, and timestamp to be deleted. Finally, the table.delete method is called to execute the deletion operation.
It is important to note that the timestamp is a long integer value measured in milliseconds, and you can obtain the current timestamp using the System.currentTimeMillis() method.