Using the Scan
API, you can scan key-value pairs from TiKV in a range (from a startKey
to an endKey
).
To configure the Scan
API to return a limited number of key-value pairs, you can use the limit
argument as in the following example code:
Scan all data
import java.util.List;
import org.tikv.common.TiConfiguration;
import org.tikv.common.TiSession;
import org.tikv.common.key.Key;
import org.tikv.raw.RawKVClient;
import org.tikv.shade.com.google.protobuf.ByteString;
TiConfiguration conf = TiConfiguration.createRawDefault("127.0.0.1:2379");
TiSession session = TiSession.create(conf);
RawKVClient client = session.createRawClient();
// prepare data
String keyPrefix = "p";
for(int i = 1; i <= 9; i ++) {
for(int j = 1; j <= 9; j ++) {
client.put(ByteString.copyFromUtf8(keyPrefix + i + j), ByteString.copyFromUtf8("v" + i + j));
}
}
// scan all data
ByteString endKey = Key.toRawKey(ByteString.copyFromUtf8(keyPrefix + "99")).next().toByteString();
int limit = 4;
while(true) {
Key maxKey = Key.MIN;
for (Kvrpcpb.KvPair pair : list) {
System.out.println(pair);
Key currentKey = Key.toRawKey(pair.getKey());
if(currentKey.compareTo(maxKey) > 0) {
maxKey = currentKey;
}
}
if(list.size() < limit) {
break;
}
To get the example code above, click here.