Redis RANDOMKEY Command Example
If you’re reading this article you probably are looking for a reminder of the Redis RANDOMKEY syntax. Well you’re in luck because we’ll give you the syntax and it’s super simple! If that’s all you needed then we’re happy to help but we’ll also continue on after that and give you more details about the RANDOMKEY command, what it does, and when to use it. With that let’s show you the command.
If you’re a hardcore coder and just want to see the code, jump to the end of the article for the Just the Code section where you can take a look at real uses of the command without any explanation to slow you down.
The RANDOMKEY Syntax
The syntax is just this simple because it requires no parameters:
The RANDOMKEY Return Value
The RANDOMKEY commands returns a random key from your database.
Now let’s use RANDOMKEY in an example.
First let’s set some variables:
Now let’s use the RANDOMKEY command to select a random key from our database:
What if the database is empty?
If the database is empty the RANDOMKEY command will return a value of
nil. Let’s see an example of that being using the FLUSHALL command to clear out the database and then using the RANDOMKEY command:
When to Use RANDOMKEY?
One use case for RANDOMKEY might be for testing purposes. Maybe you’ll have a loop that uses RANDOMKEY to pull a key and then perform some check on it’s value. It could also be useful if you just want to display a random sampling of data.
Nitty Gritty Details
The RANDOMKEY command has been available since version 1.0.0.
Using RANDOMKEY with Drivers
If you’re interacting with Redis through a set of drivers and want to use the RANDOMKEY command, you’ll of course have to do it in a different way. There are drivers on the Redis website for all the major programming languages out there. Here we’ll show what an example of what the command might look like if you were using a Node.js driver for Redis called
node_redis. The drivers are listed on the official Redis website. The call to RANDOMKEY would look something like this:
We of course can’t cover every driver so we suggest you go to your drivers documentation and find the specific syntax for you.
We hope you found the information you needed to use the Redis RANDOMKEY command. We explained the syntax, what it does, and that what it returns in the scenario that your database is completely empty. To recap, it returns a random key from your database. If the database is empty then it returns
Just the Code
127.0.0.1:6379> MSET var_a aaa var_b bbb var_c ccc
127.0.0.1:6379> SET var_a aaa
127.0.0.1:6379> SET var_b bbb
127.0.0.1:6379> SET var_c ccc
Using node_redis driver:
Pilot the ObjectRocket platform free for 30 Days
It's easy to get started. Imagine the time you'll save by not worrying about database management. Let's do this!PILOT FREE FOR 30 DAYS