Redis Command Basics - Part 3

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

In this third installment of this multi-part article we’ll show you more essential Redis command basics. These Redis commands tend to build on each other so please keep following along and running them yourself in your local environment is a great for cementing the concepts.

More Essential Redis Commands

Note: We are going to run a FLUSHALL command between each demo so we start with a blank slate.

GETSET

The GETSET command is a little nuanced. What it does is it SETS a key to a value and then returns the previous value. Let’s see it in action:

1
2
3
4
5
127.0.0.1:6379> SET str1 initialvalue
OK
127.0.0.1:6379> GETSET str1 newvalue
"initialvalue"
127.0.0.1:6379>

SETEX

The SETEX command is a combination of the SET and EXPIRE commands, so it will set s key to a string value that will expire after a specified amount of seconds. Let’s see an example:

1
2
3
4
5
6
7
127.0.0.1:6379> SETEX key1 60 "hi"
OK
127.0.0.1:6379> GET key1
"hi"
// Waited 60 seconds
127.0.0.1:6379> GET key1
(nil)

This is the equivalent to:

1
2
3
4
127.0.0.1:6379> SET key1 "hi"
OK
127.0.0.1:6379> EXPIRE key1 60
(integer) 1

PSETEX

PSETEX is exactly like SETEX except it takes the expire time in milliseconds. So to expire a value after one minute you’d execute this:

1
2
127.0.0.1:6379> PSETEX key1 60000 "hi"
OK

To get the time until expiration you use the PTTL command.

1
2
127.0.0.1:6379> PTTL key1
(integer) 17905

PERSIST

If you’ve set a key value to expire and you no longer want to expire you can do so by using the PERSIST command like so:

1
2
3
4
5
6
7
8
127.0.0.1:6379> SETEX key1 100 "hi"
OK
127.0.0.1:6379> TTL key1
(integer) 95
127.0.0.1:6379> PERSIST key1
(integer) 1
127.0.0.1:6379> TTL key1
(integer) -1

We used the TTL command to show that at first it had an expiration and after the PERSIST it no longer did (-1).

SETNX

If you only want to set a key value if the key does not exist use SETNX.

1
2
3
4
5
6
127.0.0.1:6379> SET key1 "hi"
OK
127.0.0.1:6379> SETNX key1 "bye"
(integer) 0
127.0.0.1:6379> SETNX key2 "bye"
(integer) 1

Notice that only the second SETNX set a value. The first one did not because key1 already existed.

Conclusion

We’ve covered a few more essential Redis commands including SETNX, PERSIST, PSETEX, SETEX, and GETSET. We hope you have a fuller understanding of the basic Redis commands.

If you need help setting up Redis or managing Redis please don’t hesitate to reach out to us at Object Rocket and ask us questions about your specific application. We’re always glad to help.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.