在HBase中,可以使用Scan对象和Filter实现根据时间范围查询数据。以下是一个示例代码:
import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.filter.SingleColumnValueFilter; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; public class TimeRangeQuery { public static void main(String[] args) throws IOException { Connection connection = ConnectionFactory.createConnection(); Table table = connection.getTable(TableName.valueOf("your_table_name")); Scan scan = new Scan(); long startTime = System.currentTimeMillis() - 3600000; // 1 hour ago long endTime = System.currentTimeMillis(); // current time FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL); filterList.addFilter(new SingleColumnValueFilter(Bytes.toBytes("cf"), Bytes.toBytes("timestamp"), CompareFilter.CompareOp.GREATER_OR_EQUAL, Bytes.toBytes(startTime))); filterList.addFilter(new SingleColumnValueFilter(Bytes.toBytes("cf"), Bytes.toBytes("timestamp"), CompareFilter.CompareOp.LESS_OR_EQUAL, Bytes.toBytes(endTime))); scan.setFilter(filterList); ResultScanner scanner = table.getScanner(scan); for (Result result : scanner) { // process the result } table.close(); connection.close(); } }
在上面的代码中,首先创建了一个Scan对象,然后设置了时间范围的过滤器FilterList。在这个过滤器中,使用SingleColumnValueFilter来指定时间戳列的值在指定范围内。最后,通过table.getScanner方法获取符合条件的数据,并进行处理。