hbase按照手机号-对方号码-时间戳方式时间倒序查询话费清单,给出代码
时间: 2023-08-29 15:04:47 浏览: 134
以下是一个按照手机号-对方号码-时间戳方式时间倒序查询 HBase 表中话费清单的示例代码:
```java
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
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.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.PrefixFilter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.util.Bytes;
public class HBaseDemo {
public static void main(String[] args) throws IOException {
Configuration config = new Configuration();
config.set("hbase.zookeeper.quorum", "localhost"); // HBase ZooKeeper 地址
Connection connection = ConnectionFactory.createConnection(config);
Table table = connection.getTable(TableName.valueOf("phone_bills")); // 话费清单表名
String phoneNum = "13800138000"; // 手机号码
byte[] startRow = Bytes.toBytes(phoneNum); // 起始行键
byte[] stopRow = Bytes.toBytes(phoneNum + "z"); // 终止行键
// 创建过滤器列表
FilterList filters = new FilterList(FilterList.Operator.MUST_PASS_ALL);
// 添加前缀过滤器
Filter prefixFilter = new PrefixFilter(startRow);
filters.addFilter(prefixFilter);
// 添加列值过滤器
byte[] family = Bytes.toBytes("cf"); // 列族
byte[] qualifier1 = Bytes.toBytes("callee"); // 对方号码列名
byte[] qualifier2 = Bytes.toBytes("timestamp"); // 时间戳列名
byte[] value = Bytes.toBytes("139"); // 以 139 开头的号码
SingleColumnValueFilter valueFilter = new SingleColumnValueFilter(
family, qualifier1, CompareFilter.CompareOp.EQUAL, value);
filters.addFilter(valueFilter);
// 创建扫描器
Scan scan = new Scan();
scan.setFilter(filters);
scan.setStartRow(startRow);
scan.setStopRow(stopRow);
scan.addFamily(family);
scan.addColumn(family, qualifier1);
scan.addColumn(family, qualifier2);
scan.setReversed(true); // 按时间倒序排列
// 执行扫描
ResultScanner scanner = table.getScanner(scan);
// 遍历结果
List<String> result = new ArrayList<String>();
for (Result r : scanner) {
String rowKey = Bytes.toString(r.getRow());
String callee = Bytes.toString(r.getValue(family, qualifier1));
String timestamp = Bytes.toString(r.getValue(family, qualifier2));
result.add(rowKey + "\t" + callee + "\t" + timestamp);
}
scanner.close();
// 反转结果列表
Collections.reverse(result);
// 输出结果
for (String s : result) {
System.out.println(s);
}
table.close();
connection.close();
}
}
```
需要注意的是,以上代码仅供参考,具体实现方式可能需要根据你的表结构和查询需求进行适当调整。
阅读全文