Skip to content

Commit 34c1f6b

Browse files
committed
Add sample for get rows count in range.
1 parent 185b9a3 commit 34c1f6b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/test/java/examples/OTSMultiDataSample.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package examples;
22

3+
import java.util.ArrayList;
4+
import java.util.Collections;
35
import java.util.Iterator;
46
import java.util.List;
57

@@ -44,6 +46,9 @@ public static void main(String args[]) {
4446

4547
// 迭代读取
4648
getByIterator(client, tableName);
49+
50+
// 统计行数
51+
countRows(client, tableName);
4752
} catch (ServiceException e) {
4853
System.err.println("操作失败,详情:" + e.getMessage());
4954
// 可以根据错误代码做出处理, OTS的ErrorCode定义在OTSErrorCode中。
@@ -207,4 +212,39 @@ private static void getByIterator(OTSClient client, String tableName)
207212
System.out.println("Iterator get failed.");
208213
}
209214
}
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+
}
210250
}

0 commit comments

Comments
 (0)