I have redis cache with structure as below
private HashOperations<String, Long, Object> hashOperations;
//put data in cache
hashOperations.put("Key", 1, SomeObject);
I need to fetch data from the cache with pagination( first page 50 results, second page next 50 results and so on). How can this be implemented with spring data redis. Any help is appreciated.
2
Answers
I found some work around for this online and used the same.
If you need to guarantee the order of elements I think you will need some kind of sorted set (
HSCAN
is a good way to read an entire hash, but it doesn’t guarantee ordering of what it returns and it does not guarantee that there will be no duplicate data in what it returns). The only Redis data type which fits the description of a sorted set is:ZSET
.ZSET
s have fields similar toHASH
es, but, instead of a string value, inside their fields they have adouble
“score” which is used to sort the fields.Thus, one thing you can do to get “hash paging” is to have a
ZSET
with all the same fields as yourHASH
. TheHASH
will contain the data in your fields and theZSET
will keep track of their ordering.ZSET
s have a method calledZRANGE
(documentation) which allows you to get a specific number of elements out of the set. For a “page” size of 50, it would look like this:So, to add some data to the zset/hash and then get a page you can do something like the following (pseudocode – might not compile):
Hopefully that all-String example is enough to illustrate how this can be done.