Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RedisTemplate - hash get multiple entries by key set

Tags:

spring

redis

I use spring's RedisTemplate.

I have a hash in redis.

I want to query redis, using the template, in order to get all entries whose key in a certain set of keys.

I noticed the method:

Map<Object, Object> entries = redisTemplate.opsForHash().multiGet(HASH_NAME, keySet);

But, unfortunately this method returns only the values, without the matching keys.

I could also do it like this:

Map<Object, Object> entries = redisTemplate.opsForHash().entries(HASH_NAME);
for(Object key : keySet){
    System.out.println(entries.get(key));
}

But this means I will get all entries from redis, to my local machine, and iterate them.

Don't I have a better way of doing this?

like image 741
user1028741 Avatar asked Oct 21 '15 11:10

user1028741


2 Answers

If you're using RedisTemplate you could use opsForHash().entries(H key) to get all the hash, (keys and values).

For example...

Map messageGroupMetadata = redisTemplate.opsForHash().entries(H key);

Besides it's necesary to set RedisTemplate serializers to complete this operation.

redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
like image 120
eljuegodeender Avatar answered Oct 02 '22 07:10

eljuegodeender


From the documentation of HMGET:

Array reply: list of values associated with the given fields, in the same order as they are requested.

And from the documentation for Spring Redis Hash multiGet, you can see it returns a list (not a map), which should be in the same order as the keys you sent.

Example code:

List<Object> values = redisTemplate.opsForHash().multiGet(HASH_NAME, keySet);
int i = 0;
for (String k: keySet) {
    // k is the key
    // and here is the value corresponding to the key k
    Object value = values.get(i++);
}
like image 42
arun Avatar answered Oct 02 '22 08:10

arun