|
1 | 1 | package examples; |
2 | 2 |
|
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
3 | 5 | import java.util.Iterator; |
4 | 6 | import java.util.List; |
5 | 7 |
|
@@ -44,6 +46,9 @@ public static void main(String args[]) { |
44 | 46 |
|
45 | 47 | // 迭代读取 |
46 | 48 | getByIterator(client, tableName); |
| 49 | + |
| 50 | + // 统计行数 |
| 51 | + countRows(client, tableName); |
47 | 52 | } catch (ServiceException e) { |
48 | 53 | System.err.println("操作失败,详情:" + e.getMessage()); |
49 | 54 | // 可以根据错误代码做出处理, OTS的ErrorCode定义在OTSErrorCode中。 |
@@ -207,4 +212,39 @@ private static void getByIterator(OTSClient client, String tableName) |
207 | 212 | System.out.println("Iterator get failed."); |
208 | 213 | } |
209 | 214 | } |
| 215 | + |
| 216 | + private static void countRows(OTSClient client, String tableName) |
| 217 | + throws OTSException, ClientException { |
| 218 | + // 构造迭代读取的起始位置 |
| 219 | + RowPrimaryKey inclusiveStartKey = new RowPrimaryKey(); |
| 220 | + inclusiveStartKey.addPrimaryKeyColumn(COLUMN_GID_NAME, |
| 221 | + PrimaryKeyValue.fromLong(1)); |
| 222 | + inclusiveStartKey.addPrimaryKeyColumn(COLUMN_UID_NAME, |
| 223 | + PrimaryKeyValue.INF_MIN); |
| 224 | + |
| 225 | + // 构造迭代读取的结束位置 |
| 226 | + RowPrimaryKey exclusiveEndKey = new RowPrimaryKey(); |
| 227 | + exclusiveEndKey.addPrimaryKeyColumn(COLUMN_GID_NAME, |
| 228 | + PrimaryKeyValue.fromLong(4)); |
| 229 | + exclusiveEndKey.addPrimaryKeyColumn(COLUMN_UID_NAME, |
| 230 | + PrimaryKeyValue.INF_MAX); |
| 231 | + |
| 232 | + // 构造迭代读取的参数对象,并设置起始和结束的位置,包括起始位置的行,不包括结束位置的行 |
| 233 | + RangeIteratorParameter rangeIteratorParameter = new RangeIteratorParameter(tableName); |
| 234 | + rangeIteratorParameter.setInclusiveStartPrimaryKey(inclusiveStartKey); |
| 235 | + rangeIteratorParameter.setExclusiveEndPrimaryKey(exclusiveEndKey); |
| 236 | + |
| 237 | + List<String> columnsToGet = new ArrayList<String>(); |
| 238 | + columnsToGet.add(COLUMN_GID_NAME); // 由于我们只统计行数,为了避免读出过多的数据,这里选择只返回主键列中的一列。 |
| 239 | + rangeIteratorParameter.setColumnsToGet(columnsToGet); |
| 240 | + |
| 241 | + int totalRowsCount = 0; |
| 242 | + Iterator<Row> iter = client.createRangeIterator(rangeIteratorParameter); |
| 243 | + while (iter.hasNext()) { |
| 244 | + totalRowsCount++; |
| 245 | + iter.next(); |
| 246 | + } |
| 247 | + |
| 248 | + System.out.println("Rows count in range is: " + totalRowsCount); |
| 249 | + } |
210 | 250 | } |
0 commit comments