在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方法獲取符合條件的數據,并進行處理。