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?
4 Answers 4
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());
Comments
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++);
}
Comments
I also had same issue. Even if the method description says multiget should return the data in the same sequence as input, it does not. It returns it in the way a Map would return. I wanted to open a bug for this but I don't see any option to do so on spring.io.
Comments
Not sure about spring, but Redis has a native solution for this need. You can use SORT command:
SORT index_set BY nosort get # get *->hash_field1 get *->hash_field2 ...
The first get # will return the set element, which in your case is the hash key name.