I was using redis and jedis for quite some time and never needed the SCAN commands so far. Now however I need to use the SCAN commands, particularly hscan. I understand how it works on the redis level, but the jedis Java wrapper side is confusing to me. There are ScanResults
and ScanParameter
classes flowing around and I have no clear concept of how to use them properly. The documentation for this feature is non-existent or at least hard to find. Can anyone point out where to find decent examples of how to iterate over a hash using hscan with jedis?
Sorry to have no code, but what I tried so far just makes no sense whatsoever.
In the good tradition of answering own questions, here is what I found out:
String key = "THEKEY";
ScanParams scanParams = new ScanParams().count(100);
String cur = redis.clients.jedis.ScanParams.SCAN_POINTER_START;
boolean cycleIsFinished = false;
while(!cycleIsFinished) {
ScanResult<Entry<String, String>> scanResult =
jedis.hscan(key, cur, scanParams);
List<Entry<String, String>> result = scanResult.getResult();
//do whatever with the key-value pairs in result
cur = scanResult.getStringCursor();
if (cur.equals("0")) {
cycleIsFinished = true;
}
}
The important part is that cur is a String variable and it is "0"
if the scan is complete.
With the help of ScanParams I was able to define the approximate size of each chunk to get from the hash. Approximate, because the hash might change during the scan, so it may be that an element is returned twice in the loop.