Pagination Using Redis

Continuing my last post on Redis, I was trying to achieve simple pagination using Redis. A use case can be showing reviews/comments on a web page.

When using a sorted set –

public static  void testRedisPagination(){
    ShardedJedis redis = JEDIS_POOL.getResource();
    redis.del("temp");
    String redisKey = "temp";
    for (int i = 0; i < 38; i++) {
        String val = "val - " + i;
        redis.zadd(redisKey, i, val);
    }
    long total = redis.zcard(redisKey);
    System.out.println("Total value inserted - " + total);
    int perPage = 7;
    System.out.println("Total number of pages - " + total/perPage);
    for (int pageNumber = 1; pageNumber <= total / perPage + 1; pageNumber++) {
        long start  = total - ((pageNumber-1)*perPage + 1);
        long end = start - perPage;
        System.out.println(" ===== Printing page " + (pageNumber));
        Set<String> values = redis.zrevrangeByScore(redisKey, start, end + 1);
        for (String value : values) {
            System.out.println(value + "\t");   
        }
        System.out.println("\n\n");
    }

When using a list

public static void testRedisPagination(){
 ShardedJedis redis = JEDIS_POOL.getResource();
 String redisKey = "temp";
 for (int i = 0; i < 38; i++) {
    String val = "val - " + i;
    redis.lpush(redisKey, val);
 } 
 long total = redis.llen(redisKey);
 System.out.println("Total value inserted - " + total);
 int perPage = 5;
 System.out.println("Total number of pages - " + total/perPage);
 for (int pageNumber = 1; pageNumber <= total / perPage; pageNumber++)  {
   int start = (pageNumber-1)*perPage + 1;
   int end = start + perPage -1;
   System.out.println(" ===== Printing page " + (pageNumber));
   List<String> values = redis.lrange(redisKey, start-1, end-1);
   for (String value : values) {
     System.out.println(value + "\t"); 
   }
 System.out.println("\n\n");
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s