bylijinnan
bylijinnan

Reputation: 766

how to get both keys and values when using redis's 'keys' command

I want to get both keys and values . Now I'm doing it like this:

Set<String> keys = redisTemplate.keys("Tom*");
if (keys != null) {

   //get them one by one
   for (String key : keys) {
      String value = redisTemplate.opsForValue().get(key);
   }
}

first, I have to get all the keys which starts with "abc". second, I get values one by one.

Can I get both keys and values at one time?

UPDATE:

Thank soveran.
I have some properties associated to each user:

1)Tom.loginTimes=3  
2)Tom.tradeMoneyCount=100 

Before I define two separated keys: Tom.loginTimes and Tom.tradeMoneyCount. Now I think I should use hmset:

10.75.201.3:63790> hmset Tom loginTimes 3 tradeMoneyCount 100
OK
10.75.201.3:63790> hgetall Tom
1) "loginTimes"
2) "3"
3) "tradeMoneyCount"
4) "100"

Thanks.

Upvotes: 1

Views: 10555

Answers (2)

Tiger Jain
Tiger Jain

Reputation: 11

You can use below kind of code to get all the keys at the same time, and it returns a set of keys. I am using the Spring Redis API:

public StringBuffer getAllKeys() {

       System.out.println("get all keys");

       StringBuffer sb = new StringBuffer();

       Set<byte[]> keys = redisTemplate.getConnectionFactory().getConnection().keys("*".getBytes());

       Iterator<byte[]> it = keys.iterator();

       while(it.hasNext()){

           byte[] data = (byte[])it.next();
           sb.append(new String(data, 0, data.length));
              }

       return sb;
    }

Upvotes: 1

Leonid Beschastny
Leonid Beschastny

Reputation: 51490

hashes is the right way to do it.

As for the keys command, it was added to redis for debug purposes and never meant to be used in production. Here is a warning from redis docs for keys command:

Warning: consider KEYS as a command that should only be used in production environments with extreme care. It may ruin performance when it is executed against large databases. This command is intended for debugging and special operations, such as changing your keyspace layout. Don't use KEYS in your regular application code. If you're looking for a way to find keys in a subset of your keyspace, consider using SCAN or sets.

Upvotes: 1

Related Questions