HZN
HZN

Reputation: 77

Get random Redis key greater than x

I understand that the command 'RANDOMKEY' returns a random key from the currently selected Redis database.

However, assuming all key values are numeric, how do I get a random key that has a value greater than zero?

Upvotes: 0

Views: 1634

Answers (1)

Itamar Haber
Itamar Haber

Reputation: 50122

You can't use RANDOMKEY for that, but you could use a Redis Set for that.

For every non-zero key that you set in the database, add that key's name to a set. For example, let's say your key is:

SET foo 1

Follow that command with something like:

SADD nonzeros foo

Assuming you SADD every non-zero key name to the set named nonzeros, you can get a random key name by doing:

SRANDMEMBER nonzeros

And then do GET for that key.

Upvotes: 1

Related Questions