hbase用代码完成查询某个用户所有的主叫电话(type=1)
时间: 2024-04-06 07:33:29 浏览: 9
假设HBase中存储的表为`call_logs`,其中包含列族`info`,存储了通话记录的信息,包括主叫号码、被叫号码、通话时间等,其中`type`为通话类型,1代表主叫。
以下是查询某个用户所有主叫电话的Java代码实现:
```java
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.Get;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class HBaseQuery {
// HBase连接配置
private static final Configuration conf = new Configuration();
static {
conf.set("hbase.zookeeper.quorum", "localhost");
conf.set("hbase.zookeeper.property.clientPort", "2181");
}
public static List<String> getCallerPhones(String userId) throws IOException {
List<String> callerPhones = new ArrayList<>();
try (Connection conn = ConnectionFactory.createConnection(conf);
Table table = conn.getTable(TableName.valueOf("call_logs"))) {
// 构造查询条件
Get get = new Get(Bytes.toBytes(userId));
get.addColumn(Bytes.toBytes("info"), Bytes.toBytes("caller_phone"));
get.addColumn(Bytes.toBytes("info"), Bytes.toBytes("type"));
// 查询HBase
Result result = table.get(get);
// 遍历查询结果
for (Cell cell : result.rawCells()) {
String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
if (qualifier.equals("caller_phone") && value != null) {
callerPhones.add(value);
}
}
}
return callerPhones;
}
}
```
以上代码中,`getCallerPhones` 方法接收一个`userId`参数,用于查询该用户所有的主叫电话。首先创建`Configuration`对象,设置HBase连接参数。然后创建`Connection`对象和`Table`对象,分别用于与HBase建立连接和操作表。接着构造`Get`对象,设置查询条件和需要查询的列族和列。最后调用`table.get()`方法查询HBase,得到查询结果`Result`,通过遍历`Result`中的`Cell`对象,获取主叫电话并加入到`callerPhones`列表中。