0

I am trying to do an HSCAN using Lettuce's synchronous commands. The problem is that I can't figure out the correct way of initializing the MapScanCursor. I've had no success with the constructor, and MapScanCursor.INITIAL gives type ScanCursor (no luck casting that to MapScanCursor either).

Here is an example:

RedisClient redisClient = RedisClient.create("redis://" + url + ":" + port);
RedisHashCommands<String, String> redisCommands = redisClient.connect().sync();
List<String> fields = new LinkedList<>();

MapScanCursor<String, String> scanCursor = ?

do {
    scanCursor = redisCommands.hscan(key, scanCursor);
    fields.addAll(scanCursor.getMap().keySet());
} while (!scanCursor.isFinished());

How should I initialize "scanCursor"?

1 Answers1

1

You have two options:

To answer your question, initialize scanCursor with just hscan(key).

MapScanCursor<String, String> scanCursor = null;

do {
    if (scanCursor == null) {
        scanCursor = redisCommands.hscan(key);
    } else {
        scanCursor = redisCommands.hscan(key, scanCursor);
    }
    fields.addAll(scanCursor.getMap().keySet());
} while (!scanCursor.isFinished());

Alternatively, you can use ScanIterator (see Lettuce 4.4) which is an Iterator and covers the complexity of Redis SCAN usage:

ScanIterator<KeyValue<String, String>> iterator = ScanIterator.hscan(redisCommands, key);

while (iterator.hasNext()) {

    KeyValue<String, String> next = iterator.next();
    // …
} 

Update

Updated the do…while-based approach according to tcfritchman's comment.

mp911de
  • 17,546
  • 2
  • 55
  • 95
  • Thanks for the helpful answer with an excellent alternative. This fixed my problem. One small issue though is that when using the first option, you must do the check for `!scanCursor.isFinished()` before calling `hscan` a second time. Otherwise you will get an error if the scan finishes on the first call. Eg. `scanCursor = redisCommands.hscan(key); while (!scanCursor.isFinished()) {scanCursor = redisCommands.hscan(key, scanCursor); fields.addAll(scanCursor.getMap().keySet()); }` – tcfritchman Jun 19 '17 at 17:39