Hbase Java API 代码开发(CURD,Filter 过滤器)
- 1、Hbase API 类和数据模型
- 2、基本增删改查实现
- 2.1、声明静态属性
- 2.2、创建表(指定列簇版本数)
- 2.3、上传单条数据
- 2.4、批量上传数据
- 2.5、根据 startKey 和 endKey 查询数据
- 2.6、根据 rowkey 查询数据
- 2.7、查询指定 rowkey 下列簇列的数据
- 2.8、查询表中的某一列
- 2.9、更新表中的某一列
- 2.10、查询某列数据的多个版本
- 2.11、列簇过滤器
- 2.12、列过滤器
- 2.13、值过滤器
- 2.14、单列值过滤器(单列值排除过滤器)
- 2.15、rowkey 前缀过滤器
- 2.16、qualifier 列前缀过滤器
- 2.17、分页查询
- 2.18、多过滤器综合查询
- 2.19、根据 rowkey 删除数据
- 2.20、删除数据表
- 2.21、main 方法
1、Hbase API 类和数据模型
几个主要 Hbase API 类和数据模型之间的对应关系:
java 类 | HBase 数据模型 |
---|---|
Admin | 数据库(DataBase) |
HBaseConfiguration | 数据库(DataBase) |
Table | 表(Table) |
HTableDescriptor | 列簇(Column Family) |
HColumnDescriptor | 列簇(Column Family) |
Put | 列修饰符(Column Qualifier) |
Get | 列修饰符(Column Qualifier) |
Delete | 列修饰符(Column Qualifier) |
Result | 列修饰符(Column Qualifier) |
Scan | 列修饰符(Column Qualifier) |
ResultScanner | 列修饰符(Column Qualifier) |
1.1、Admin
(1)关系:org.apache.hadoop.hbase.client.Admin
(2)作用:提供了一个接口来管理 HBase 数据库的表信息。它提供的方法包括:创建表,删除表,列出表项,使表有效或无效,以及添加或删除表列簇成员等。
返回值 | 函数 | 描述 |
---|---|---|
void | addColumn(String tableName, HColumnDescriptor column) | 向一个已经存在的表添加列簇 |
void | checkHBaseAvailable(HBaseConfiguration conf) | 静态函数,查看 HBase 是否处于运行状态 |
void | createTable(HTableDescriptor desc) | 创建一个表,同步操作 |
void | deleteTable(byte[] tableName) | 删除一个已经存在的表 |
void | enableTable(byte[] tableName) | 使表处于有效状态 |
void | disableTable(byte[] tableName) | 使表处于无效状态 |
HTableDescriptor[] | listTables() | 列出所有用户控件表项 |
void | modifyTable(byte[] tableName, HTableDescriptor htd) | 修改表的模式,是异步的操作,可能需要花费一定的时间 |
boolean | tableExists(String tableName) | 检查表是否存在 |
(3)用法示例:
// 根据配置从工厂获取链接
Connection conn = ConnectionFactory.createConnection(conf);
// 获取集群的客户端操作实例对象
admin = conn.getAdmin();
1.2、HBaseConfiguration
(1)关系:org.apache.hadoop.hbase.HBaseConfiguration
(2)作用:对 HBase 进行配置。
返回值 | 函数 | 描述 |
---|---|---|
void | addResource(Path file) | 通过给定的路径所指的文件来添加资源 |
void | clear() | 清空所有已设置的属性 |
string | get(String name) | 获取属性名对应的值 |
String | getBoolean(String name, boolean defaultValue) | 获取为 boolean 类型的属性值,如果其属性值类型不为 boolean,则返回默认属性值 |
void | set(String name, String value) | 通过属性名来设置值 |
void | setBoolean(String name, boolean value) | 设置 boolean 类型的属性值 |
(3)用法示例:
HBaseConfiguration config = new HBaseConfiguration();
config.set("hbase.zookeeper.property.clientPort","2181");
该方法设置了 hbase.zookeeper.property.clientPort
的端口号为 2181
。一般情况下,HBaseConfiguration 会使用构造函数进行初始化,然后在使用其他方法。
1.3、HTableDescriptor
(1)关系:org.apache.hadoop.hbase.HTableDescriptor
(2)作用:包含了表的名字极其对应表的列簇。
返回值 | 函数 | 描述 |
---|---|---|
void | addFamily(HColumnDescriptor) | 添加一个列簇 |
HColumnDescriptor | removeFamily(byte[] column) | 移除一个列簇 |
byte[] | getName() | 获取表的名字 |
byte[] | getValue(byte[] key) | 获取属性的值 |
void | setValue(String key, String value) | 设置属性的值 |
(3)用法示例:
HTableDescriptor htd = new HTableDescriptor(table);
htd.addFamily(new HcolumnDescriptor("family"));
在上述例子中,通过一个 HColumnDescriptor 实例,为 HTableDescriptor 添加了一个列簇:family
1.4、HColumnDescriptor
(1)关系:org.apache.hadoop.hbase.HColumnDescriptor
(2)作用:维护着关于列簇的信息,例如版本号,压缩设置等。它通常在创建表或者为表添加列簇的时候使用。列簇被创建后不能直接修改,只能通过删除然后重新创建的方式。列簇被删除的时候,列簇里面的数据也会同时被删除。
返回值 | 函数 | 描述 |
---|---|---|
byte[] | getName() | 获取列簇的名字 |
byte[] | getValue(byte[] key) | 获取对应的属性的值 |
void | setValue(String key, String value) | 设置对应属性的值 |
(3)用法示例:
HTableDescriptor htd = new HTableDescriptor(tablename);
HColumnDescriptor col = new HColumnDescriptor("content");
htd.addFamily(col);
此例添加了一个 content 的列簇。
1.5、Table
(1)关系:org.apache.hadoop.hbase.client.Table
(2)作用:可以用来和 HBase 表直接通信。此方法对于更新操作来说是非线程安全的。
返回值 | 函数 | 描述 |
---|---|---|
void | checkAdnPut(byte[] row, byte[] family, byte[] qualifier, byte[] value, Put put) | 自动的检查 row/family/qualifier 是否与给定的值匹配 |
void | close() | 释放所有的资源或挂起内部缓冲区中的更新 |
Boolean | exists(Get get) | 检查 Get 实例所指定的值是否存在于 HTable 的列中 |
Result | get(Get get) | 获取指定行的某些单元格所对应的值 |
byte[][] | getEndKeys() | 获取当前一打开的表每个区域的结束键值 |
ResultScanner | getScanner(byte[] family) | 获取当前给定列簇的 scanner 实例 |
HTableDescriptor | getTableDescriptor() | 获取当前表的 HTableDescriptor 实例 |
byte[] | getTableName() | 获取表名 |
static boolean | isTableEnabled(HBaseConfiguration conf, String tableName) | 检查表是否有效 |
void | put(Put put) | 向表中添加值 |
(3)用法示例:
TableName tb_ame = TableName.valueOf(tableName);
// 获取表操作对象
Table table = conn.getTable(tb_ame);
ResultScanner scanner = table.getScanner(family);
1.6、 Put
(1)关系:org.apache.hadoop.hbase.client.Put
(2)作用:用来对单个行执行添加操作。
返回值 | 函数 | 描述 |
---|---|---|
Put | add(byte[] family, byte[] qualifier, byte[] value) | 将指定的列和对应的值添加到 Put 实例中 |
Put | add(byte[] family, byte[] qualifier, long ts, byte[] value) | 将指定的列和对应的值及时间戳添加到 Put 实例中 |
byte[] | getRow() | 获取 Put 实例的行 |
RowLock | getRowLock() | 获取 Put 实例的行锁 |
long | getTimeStamp() | 获取 Put 实例的时间戳 |
boolean | isEmpty() | 检查 familyMap 是否为空 |
Put | setTimeStamp(long timeStamp) | 设置 Put 实例的时间戳 |
(3)用法示例:
HTable table = new HTable(conf,Bytes.toBytes(tablename));
Put p = new Put(brow);//为指定行创建一个 Put 操作
p.add(family,qualifier,value);
table.put(p);
1.7、 Get
(1)关系:org.apache.hadoop.hbase.client.Get
(2)作用:用来获取单个行的相关信息。
返回值 | 函数 | 描述 |
---|---|---|
Get | addColumn(byte[] family, byte[] qualifier) | 获取指定列簇和列修饰符对应的列 |
Get | addFamily(byte[] family) | 通过指定的列簇获取其对应列的所有列 |
Get | setTimeRange(long minStamp,long maxStamp) | 获取指定取件的列的版本号 |
Get | setFilter(Filter filter) | 当执行 Get 操作时设置服务器端的过滤器 |
(3)用法示例:
HTable table = new HTable(conf, Bytes.toBytes(tablename));
Get g = new Get(Bytes.toBytes(row));
1.8、 Result
(1)关系:org.apache.hadoop.hbase.client.Result
(2)作用:存储 Get 或者 Scan 操作后获取表的单行值。使用此类提供的方法可以直接获取值或者各种 Map 结构(key-value 对)。
返回值 | 函数 | 描述 |
---|---|---|
boolean | containsColumn(byte[] family, byte[] qualifier) | 检查指定的列是否存在 |
NavigableMap<byte[], byte[]> | getFamilyMap(byte[] family) | 获取对应列簇所包含的修饰符与值的键值对 |
byte[] | getValue(byte[] family, byte[] qualifier) | 获取对应列的最新值 |
9、 Scan
10、ResultScanner
11、Delete
2、基本增删改查实现
创建项目 hbase-demo,导入依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zc.hbase</groupId>
<artifactId>hbase-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<encoding>UTF-8</encoding>
<hadoop.version>2.7.5</hadoop.version>
<hbase.version>1.6.0</hbase.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>${hbase.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client</artifactId>
<version>${hadoop.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
新建类 com.zc.hbase.HbaseDemoTest
。
2.1、声明静态属性
// 声明静态配置
static Configuration conf;
// 声明静态链接
static Connection conn;
// 声明集群的客户端操作实例对象
static Admin admin;
// zookeeper集群链接地址
private static final String ZK_CONNECT_STR = "hadoop01:2181,hadoop02:2181,hadoop03:2181,hadoop04:2181,hadoop05:2181";
static {
// Hbase 加载配置
conf = HBaseConfiguration.create();
// 设置属性
conf.set("hbase.zookeeper.quorum", ZK_CONNECT_STR);
try {
// 根据配置从工厂获取链接
conn = ConnectionFactory.createConnection(conf);
// 获取集群的客户端操作实例对象
admin = conn.getAdmin();
} catch (IOException e) {
e.printStackTrace();
}
}
2.2、创建表(指定列簇版本数)
/**
* 创建表,指定列簇版本数
* @param tableName 表名
* @param familys 列簇列表
* @throws Exception
*/
public static void createTable(String tableName, String[] familys)
throws Exception {
// 实例化表对象
TableName tb_name = TableName.valueOf(tableName);
if (!admin.tableExists(tb_name)){ // 如果表不存在
// 构件表名
HTableDescriptor htd = new HTableDescriptor(tb_name);
// 构建列簇列表
for (int i = 0; i < familys.length; i++) {
HColumnDescriptor hcd = new HColumnDescriptor(familys[i]);
hcd.setValue("VERSIONS","3");
htd.addFamily(hcd);
}
// 创建表
admin.createTable(htd);
System.out.println("表 " + tableName + " 创建成功");
} else System.out.println("表 " + tableName + " 已经存在");
}
2.3、上传单条数据
/**
* 上传单条数据
* @param tableName 表名
* @param rowkey 行键
* @param family 列簇
* @param qualifier 列
* @param value 数据
* @throws Exception
*/
public static void putOneData(String tableName, String rowkey, String family, String qualifier, String value)
throws Exception {
TableName tb_ame = TableName.valueOf(tableName);
if (admin.tableExists(tb_ame)){ // 表存在
// 获取表操作对象
Table table = conn.getTable(tb_ame);
HTableDescriptor htd = table.getTableDescriptor();
HColumnDescriptor hcd = htd.getFamily(family.getBytes());
if (hcd != null){
// 初始化表上传 put 对象
Put put = new Put(rowkey.getBytes());
// 准备 put 语句
put.addColumn(family.getBytes(), qualifier.getBytes(), value.getBytes());
// 向表提交 put 语句上传数据
table.put(put);
System.out.println("数据上传成功");
} else System.out.println("列簇 "+ family +" 不存在,上传数据失败");
table.close();
} else System.out.println("表不存在,数据上传失败");
}
2.4、批量上传数据
/**
* 批量上传数据
* @param batchData 二维数组存储多条数据
* @throws Exception
*/
public static void putBatchData(String tableName, String[][] batchData)
throws Exception {
TableName tb_ame = TableName.valueOf(tableName);
if (admin.tableExists(tb_ame)){ // 表存在
// 获取表操作对象
Table table = conn.getTable(tb_ame);
HTableDescriptor htd = table.getTableDescriptor();
List<Put> puts = new ArrayList<>();
int suucCount = 0;
int errCount = 0;
String[][] errBatchData = new String[batchData.length][4];
for (int i = 0; i < batchData.length; i++) {
HColumnDescriptor hcd = htd.getFamily(batchData[i][1].getBytes());
if (hcd != null){
// 初始化表上传 put 对象
Put put = new Put(batchData[i][0].getBytes());
// 准备 put 语句
put.addColumn(batchData[i][1].getBytes(), batchData[i][2].getBytes(), batchData[i][3].getBytes());
puts.add(put);
suucCount++;
} else {
errCount++;
for (int j = 0; j < batchData[i].length; j++) {
errBatchData[errCount - 1][j] = batchData[i][j];
}
}
}
// 向表提交 put 语句上传数据
table.put(puts);
System.out.println("准备的数据共有 " + batchData.length + " 条\n" + "有 " + suucCount + " 数据上传成功");
System.out.println("上传失败的数据共有 " + errCount + " 条,分别为:");
for (int i = 0; i < errCount; i++) {
System.out.print("{");
for (int j = 0; j < errBatchData[i].length; j++) {
if (j == errBatchData[i].length - 1){
System.out.print(errBatchData[i][j]);
} else {
System.out.print(errBatchData[i][j] + ",");
}
}
System.out.println("}");
}
table.close();
} else System.out.println("表不存在,数据上传失败");
}
2.5、根据 startKey 和 endKey 查询数据
/**
* 根据 startKey 和 endKey 查询数据,区间 [startKey, endKey)
*
* @param tableName 表名
* @param startKey 开始查询的 rowkey,包括
* @param endKey 结束查询的 rowkey,不包括
* @throws Exception
*/
public static void queryByStartKeyAndEndKey(String tableName, String startKey, String endKey)
throws Exception {
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
Scan scan = new Scan();
scan.setStartRow(startKey.getBytes());
scan.setStopRow(endKey.getBytes());
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
System.out.println(new String(result.getRow()));
Cell[] cells = result.rawCells();
for (Cell cell : cells) {
String rowkey = Bytes.toString(CellUtil.cloneRow(cell));
String family = Bytes.toString(CellUtil.cloneFamily(cell));
String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value);
}
}
}
2.6、根据 rowkey 查询数据
/**
* 根据 rowkey 查询数据
*
* @param tableName 表名
* @param rowkey 查询的 rowkey
* @throws Exception
*/
public static void queryByRowkey(String tableName, String rowkey) throws Exception {
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
Get get = new Get(rowkey.getBytes());
Result result = table.get(get);
if (result.isEmpty()) {
System.out.println("rowkey:" + rowkey + "不存在");
} else {
Cell[] cells = result.rawCells();
for (Cell cell : cells) {
String family = Bytes.toString(CellUtil.cloneFamily(cell));
String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value);
}
}
}
2.7、查询指定 rowkey 下列簇列的数据
/**
* 查询指定 rowkey 下列簇列的数据,一个 rowkey 对应一个 result
*
* @param tableName 表名
* @param rowkey rowkey
* @param family 列簇
* @param qualifier 列
* @throws Exception 异常
*/
public static void getQualifierValue(String tableName, String rowkey, String family, String qualifier)
throws Exception {
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
Get get = new Get(rowkey.getBytes());
Result result = table.get(get);
if (result.isEmpty()) {
System.out.println("rowkey:" + rowkey + "不存在");
} else {
HTableDescriptor htd = table.getTableDescriptor();
HColumnDescriptor hcd = htd.getFamily(family.getBytes());
if (hcd == null) {
System.out.println("family:" + family + "不存在");
} else {
String value = Bytes.toString(result.getValue(family.getBytes(),
qualifier.getBytes()));
if (value == null) {
System.out.println("qualifier:" + qualifier + " 在 rowkey:" + rowkey +
", family:" + family + " 下没有数据");
} else System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value);
}
}
}
2.8、查询表中的某一列
/**
* 查询表中的某一列
* @param tableName 表名
* @param rowkey rowKey
* @param family 列簇
* @param qualifier 列
* @throws Exception
*/
public static void getResultByColumn(String tableName, String rowkey,String family, String qualifier)
throws Exception {
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
Get get = new Get(Bytes.toBytes(rowkey));
// 获取指定列簇和列修饰符对应的列
get.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
Result result = table.get(get);
Cell[] cells = result.rawCells();
for (Cell cell: cells) {
String value = Bytes.toString(CellUtil.cloneValue(cell));
long timestramp = cell.getTimestamp();
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value +
", timestramp:" + timestramp);
}
}
2.9、更新表中的某一列
/**
* 更新表中的某一列
* @param tableName 表名
* @param rowkey rowkey
* @param family 列簇
* @param qualifier 列
* @param value 值
* @throws Exception
*/
public static void updateTable(String tableName, String rowkey,String family, String qualifier, String value)
throws Exception {
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
Put put = new Put(Bytes.toBytes(rowkey));
put.add(CellUtil.createCell(Bytes.toBytes(family),Bytes.toBytes(qualifier), Bytes.toBytes(value)));
table.put(put);
System.out.println("update table Success!");
}
2.10、查询某列数据的多个版本
/**
* 查询某列数据的多个版本
* @param tableName 表名
* @param rowkey rowkey
* @param family 列簇
* @param qualifier 列
* @throws Exception
*/
public static void getResultByVersion(String tableName, String rowkey, String family, String qualifier)
throws Exception {
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
Get get = new Get(Bytes.toBytes(rowkey));
get.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
get.setMaxVersions(5);
Result result = table.get(get);
Cell[] cells = result.rawCells();
for (Cell cell: cells) {
String value = Bytes.toString(CellUtil.cloneValue(cell));
long timestramp = cell.getTimestamp();
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value +
", timestramp:" + timestramp);
}
}
2.11、列簇过滤器
/**
* 列簇过滤器,查询表中列簇中包含了字符串 familyFilterStr 的所有数据
*
* @param tableName
* @param familyFilterStr
* @throws Exception
*/
public static void familyFilter(String tableName, String familyFilterStr)
throws Exception {
FamilyFilter familyFilter = new FamilyFilter(CompareFilter.CompareOp.EQUAL,
new SubstringComparator(familyFilterStr));
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
Scan scan = new Scan();
scan.setFilter(familyFilter);
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
System.out.println(new String(result.getRow()));
Cell[] cells = result.rawCells();
for (Cell cell : cells) {
String rowkey = Bytes.toString(CellUtil.cloneRow(cell));
String family = Bytes.toString(CellUtil.cloneFamily(cell));
String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value);
}
}
}
2.12、列过滤器
/**
* 列过滤器,查询表中所有列簇下列中包含了字符串 qulifierFilterStr 的所有数据
*
* @param tableName
* @param qulifierFilterStr
* @throws Exception
*/
public static void qulifierFilter(String tableName, String qulifierFilterStr)
throws Exception {
QualifierFilter qualifierFilter = new QualifierFilter(CompareFilter.CompareOp.EQUAL,
new SubstringComparator(qulifierFilterStr));
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
Scan scan = new Scan();
scan.setFilter(qualifierFilter);
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
System.out.println(new String(result.getRow()));
Cell[] cells = result.rawCells();
for (Cell cell : cells) {
String rowkey = Bytes.toString(CellUtil.cloneRow(cell));
String family = Bytes.toString(CellUtil.cloneFamily(cell));
String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value);
}
}
}
2.13、值过滤器
/**
* 值过滤器,查询表中所有列簇下列的值中包含了字符串 valueFilterStr 的所有数据
* @param tableName
* @param valueFilterStr
* @throws Exception
*/
public static void valueFilter(String tableName, String valueFilterStr)
throws Exception {
ValueFilter valueFilter = new ValueFilter(CompareFilter.CompareOp.EQUAL,
new SubstringComparator(valueFilterStr));
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
Scan scan = new Scan();
scan.setFilter(valueFilter);
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
System.out.println(new String(result.getRow()));
Cell[] cells = result.rawCells();
for (Cell cell : cells) {
String rowkey = Bytes.toString(CellUtil.cloneRow(cell));
String family = Bytes.toString(CellUtil.cloneFamily(cell));
String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value);
}
}
}
2.14、单列值过滤器(单列值排除过滤器)
/**
* 单列值过滤器
* 单列值排除过滤器
* @param tableName
* @param family
* @param qualifier
* @param valueFilterStr
* @throws Exception
*/
public static void singleColumnValueFilter(String tableName, String family, String qualifier, String valueFilterStr)
throws Exception{
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
HTableDescriptor htd = table.getTableDescriptor();
HColumnDescriptor hcd = htd.getFamily(family.getBytes());
if (hcd == null) {
System.out.println("family:" + family + "不存在");
} else {
//单列值过滤器
SingleColumnValueFilter scvef = new SingleColumnValueFilter(family.getBytes(),
qualifier.getBytes(),
CompareFilter.CompareOp.EQUAL,
valueFilterStr.getBytes());
//单列值排除过滤器
// SingleColumnValueExcludeFilter scvef = new SingleColumnValueExcludeFilter(family.getBytes(),
// qualifier.getBytes(),
// CompareFilter.CompareOp.EQUAL,
// valueFilterStr.getBytes());
Scan scan = new Scan();
scan.setFilter(scvef);
ResultScanner scanner = table.getScanner(scan);
System.out.println(scanner.toString());
for (Result result : scanner) {
System.out.println(new String(result.getRow()));
Cell[] cells = result.rawCells();
for (Cell cell : cells) {
String rowkey = Bytes.toString(CellUtil.cloneRow(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value);
}
}
}
}
2.15、rowkey 前缀过滤器
/**
* rowkey 前缀过滤器
* @param tableName
* @param prefixRowkeyFilterStr
* @throws Exception
*/
public static void prefixRowkeyFilter(String tableName, String prefixRowkeyFilterStr)
throws Exception {
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
PrefixFilter prefixFilter = new PrefixFilter(prefixRowkeyFilterStr.getBytes());
Scan scan = new Scan();
scan.setFilter(prefixFilter);
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
System.out.println(new String(result.getRow()));
Cell[] cells = result.rawCells();
for (Cell cell : cells) {
String rowkey = Bytes.toString(CellUtil.cloneRow(cell));
String family = Bytes.toString(CellUtil.cloneFamily(cell));
String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value);
}
}
}
2.16、qualifier 列前缀过滤器
/**
* qualifier 列前缀过滤器
* @param tableName
* @param columnPrefixFilterStr
* @throws Exception
*/
public static void columnPrefixFilter(String tableName, String columnPrefixFilterStr)
throws Exception {
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
ColumnPrefixFilter columnPrefixFilter = new ColumnPrefixFilter(columnPrefixFilterStr.getBytes());
Scan scan = new Scan();
scan.setFilter(columnPrefixFilter);
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
System.out.println(new String(result.getRow()));
Cell[] cells = result.rawCells();
for (Cell cell : cells) {
String rowkey = Bytes.toString(CellUtil.cloneRow(cell));
String family = Bytes.toString(CellUtil.cloneFamily(cell));
String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value);
}
}
}
2.17、分页查询
/**
* 分页查询
* @param tableName
* @throws IOException
*/
public static void pageFilter(String tableName,String family,String qualifier,int pageNum,int pageSize)
throws IOException {
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
Scan scan = new Scan();
if (pageNum == 1){
PageFilter pageFilter = new PageFilter(pageSize);
scan.setStartRow(Bytes.toBytes(""));
scan.setFilter(pageFilter);
scan.setMaxResultSize(pageSize);
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
//获取rowkey
String rowkey = Bytes.toString(result.getRow());
//指定列族以及列打印列当中的数据出来
String value = Bytes.toString(result.getValue(family.getBytes(), qualifier.getBytes()));
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value);
}
} else {
String rowkey = "";
for (int i = pageNum - 1; i <= pageNum; i++) {
if (i == pageNum) {
PageFilter filter = new PageFilter(pageSize);
scan.setStartRow(Bytes.toBytes(rowkey));
scan.setFilter(filter);
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
//获取rowkey
rowkey = Bytes.toString(result.getRow());
//指定列族以及列打印列当中的数据出来
String value = Bytes.toString(result.getValue(family.getBytes(), qualifier.getBytes()));
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value);
}
} else {
PageFilter filter = new PageFilter((pageNum - 1) * pageSize + 1);
scan.setStartRow(Bytes.toBytes(rowkey));
scan.setFilter(filter);
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
//获取rowkey
rowkey = Bytes.toString(result.getRow());
}
}
}
}
}
2.18、多过滤器综合查询
/**
* 多过滤器综合查询
* @param tableName
* @param rowkeyPrefixFilterStr
* @param valueFilterStr
* @throws Exception
*/
public static void filterList(String tableName, String rowkeyPrefixFilterStr, String valueFilterStr)
throws Exception {
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
FilterList filterList = new FilterList();
PrefixFilter prefixFilter = new PrefixFilter(rowkeyPrefixFilterStr.getBytes());
ValueFilter valueFilter = new ValueFilter(CompareFilter.CompareOp.EQUAL,
new SubstringComparator(valueFilterStr));
filterList.addFilter(prefixFilter);
filterList.addFilter(valueFilter);
Scan scan = new Scan();
scan.setFilter(filterList);
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
Cell[] cells = result.rawCells();
for (Cell cell : cells) {
String rowkey = Bytes.toString(CellUtil.cloneRow(cell));
String family = Bytes.toString(CellUtil.cloneFamily(cell));
String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
System.out.println("rowkey:" + rowkey + ", family:" + family +
", qualifier:" + qualifier + ", value:" + value);
}
}
}
2.19、根据 rowkey 删除数据
/**
* 根据 rowkey 删除数据
*/
public static void deleteByRowkey(String tableName,String rowkey)
throws Exception {
TableName ta_name = TableName.valueOf(tableName);
Table table = conn.getTable(ta_name);
Delete delete = new Delete(rowkey.getBytes());
// delete.addColumn(family.getBytes(), qualifier.getBytes());
table.delete(delete);
System.out.println("rowkey:" + rowkey + " 数据删除成功");
}
2.20、删除数据表
/**
* 删除数据表
*/
public static void dropTable(String tableName)
throws Exception {
TableName ta_name = TableName.valueOf(tableName);
admin.disableTable(ta_name); //先禁用表
admin.deleteTable(ta_name); //再删除表 hbase-shell 中-> 先disable,再drop
System.out.println("表 " + tableName + " 删除成功");
}
2.21、main 方法
public static void main(String[] args) throws Exception {
String tableName = "ApiTest";
String[] familys = {"cf1", "cf2"};
// createTable(tableName, familys);
// putOneData(tableName,"first01", "cf1", "username","张三");
String[][] batchData = {
{"first01", "cf1", "username", "李四"},
{"first01", "cf1", "age", "22"},
{"first01", "cf1", "gender", "male"},
{"first01", "cf2", "hobby", "music"},
{"first01", "cf3", "err", "errdata"},
{"first02", "cf1", "username", "liyujie"},
{"first02", "cf1", "age", "20"},
{"first02", "cf1", "gender", "female"},
{"first02", "cf2", "hobby", "dance"},
{"first02", "cf3", "err", "errdata"},
{"first03", "cf1", "username", "wangwu"},
{"first03", "cf1", "age", "21"},
{"first03", "cf1", "gender", "male"},
{"first03", "cf2", "hobby", "dance"},
{"first03", "cf3", "err", "errdata"}
};
// putBatchData(tableName, batchData);
// queryByStartKeyAndEndKey(tableName,"first02","first04");
// queryByRowkey(tableName,"first01");
// getQualifierValue(tableName,"first01","cf1","username");
// getQualifierValue(tableName,"first01","cf2","age");
// getQualifierValue(tableName,"first04","cf1","gender");
// getQualifierValue(tableName,"first01","cf3","hobby");
// getResultByColumn(tableName,"first01","cf1","username");
// getResultByVersion(tableName,"first01","cf1","username");
// updateTable(tableName,"first01","cf1","username", "王者五");
// familyFilter(tableName,"f2");
// qulifierFilter(tableName,"obb");
// valueFilter(tableName, "yu");
// singleColumnValueFilter(tableName,"cf1","age","21");
// prefixRowkeyFilter(tableName,"first");
// columnPrefixFilter(tableName,"gen");
// pageFilter(tableName,"cf1","age",3,2);
// filterList(tableName,"fir","0");
// deleteByRowkey(tableName,"first03");
// dropTable(tableName);
// 关闭流
admin.close();
conn.close();
}
}