How To Manage A Redis Database
How To Manage A Redis Database
International License.
ISBN 978-0-9997730-7-9
How To Manage a Redis Database
Mark Drake
2020-07
How To Manage a Redis Database
1. About DigitalOcean
2. Introduction
3. How To Connect to a Redis Database
4. How To Manage Redis Databases and Keys
5. How To Manage Replicas and Clients in Redis
6. How To Manage Strings in Redis
7. How To Manage Lists in Redis
8. How To Manage Hashes in Redis
9. How To Manage Sets in Redis
10. How To Manage Sorted Sets in Redis
11. How To Run Transactions in Redis
12. How To Expire Keys in Redis
13. How To Troubleshoot Issues in Redis
14. How To Change Redis’s Configuration from the Command Line
About DigitalOcean
Connecting to Redis
If you have redis-server installed locally, you can connect to the
Redis instance with the redis-cli command:
redis-cli
This will take you into redis-cli’s interactive mode which presents
you with a read-eval-print loop (REPL) where you can run Redis’s built-in
commands and receive replies.
In interactive mode, your command line prompt will change to reflect
your connection. In this example and others throughout this guide, the
prompt indicates a connection to a Redis instance hosted locally
(127.0.0.1) and accessed over Redis’s default port (6379):
The alternative to running Redis commands in interactive mode is to
run them as arguments to the redis-cli command, like so:
redis-cli redis_command
If you want to connect to a remote Redis datastore, you can specify its
host and port numbers with the -h and -p flags, respectively. Also, if
you’ve configured your Redis database to require a password, you can
include the -a flag followed by your password in order to authenticate:
redis-cli -h host -p port_number -a password
If you’ve set a Redis password, clients will be able to connect to Redis
even if they don’t include the -a flag in their redis-cli command.
However, they won’t be able to add, change, or query data until they
authenticate. To authenticate after connecting, use the auth command
followed by the password:
auth password
If the password passed to auth is valid, the command will return OK.
Otherwise, it will return an error.
If you’re working with a managed Redis database, your cloud provider
may give you a URI that begins with redis:// or rediss:// which
you can use to access your datastore. If the connection string begins with
redis://, you can include it as an argument to redis-cli to connect.
However, if you have a connection string that begins with rediss://,
that means your managed database requires connections over TLS/SSL.
redis-cli does not support TLS connections, so you’ll need to use a
different tool that supports the rediss protocol in order to connect with
the URI. For DigitalOcean Managed Databases, which require connections
to be made over TLS, we recommend using Redli to access the Redis
instance.
Use the following syntax to connect to a database with Redli. Note that
this example includes the --tls option, which specifies that the
connection should be made over TLS, and the -u flag, which declares that
the following argument will be a connection URI:
redli --tls -u rediss://connection_URI
If you’ve attempted to connect to an unavailable instance, redis-cli
will go into disconnected mode. The prompt will reflect this:
Redis will attempt to reestablish the connection every time you run a
command when it’s in a disconnected state.
Testing Connections
The ping command is useful for testing whether the connection to a
database is alive. Note that this is a Redis-specific command and is
different from the ping networking utility. However, the two share a
similar function in that they’re both used to check a connection between
two machines.
If the connection is up and no arguments are included, the ping
command will return PONG:
ping
Output
PONG
"hello Redis!"
If you run ping or any other command in disconnected mode, you will
see an output like this:
ping
Output
Conclusion
This guide details a number of commands used to establish, test, and close
connections to a Redis server. If there are other related commands,
arguments, or procedures you’d like to see in this guide, please ask or
make suggestions in the comments below.
For more information on Redis commands, see our tutorial series on
How to Manage a Redis Database.
How To Manage Redis Databases and
Keys
Managing Databases
Out of the box, a Redis instance supports 16 logical databases. These
databases are effectively siloed off from one another, and when you run a
command in one database it doesn’t affect any of the data stored in other
databases in your Redis instance.
Redis databases are numbered from 0 to 15 and, by default, you
connect to database 0 when you connect to your Redis instance. However,
you can change the database you’re using with the select command
after you connect:
select 15
If you’ve selected a database other than 0, it will be reflected in the
redis-cli prompt:
To swap all the data held in one database with the data held in another,
use the swapdb command. The following example will swap the data held
in database 6 with that in database 8, and any clients connected to either
database will be able to see changes immediately:
swapdb 6 8
swapdb will return OK if the swap is successful.
If you want to move a key to a different Redis instance, you can run
migrate. This command ensures the key exists on the target instance
before deleting it from the source instance. When you run migrate, the
command must include the following elements in this order:
To illustrate:
migrate 203.0.113.0 6379 key_1 7 8000
Additionally, migrate allows the following options which you can add
after the timeout argument:
COPY: Specifies that the key should not be deleted from the source
instance
REPLACE: Specifies that if the key already exists on the destination,
the migrate operation should delete and replace it
KEYS: Instead of providing a specific key to migrate, you can enter
an empty string ("") and then use the syntax from the keys
command to migrate any key that matches a pattern. For more
information on how keys works, see our tutorial on How To
Troubleshoot Issues in Redis.
Managing Keys
There are a number of Redis commands that are useful for managing keys
regardless of what type of data they hold. We’ll go over a few of these in
this section.
rename will rename the specified key. If it’s successful, it will return
OK:
rename old_key new_key
You can use randomkey to return a random key from the currently
selected database:
randomkey
Output
"any_key"
Use type to determine what type of data the given key holds. This
command’s output can be either string, list, hash, set, zset, or
stream:
type key_1
Output
"string"
If the specified key doesn’t exist, type will return none instead.
You can move an individual key to another database in your Redis
instance with the move command. move takes the name of a key and the
database where you want to move the key as arguments. For example, to
move the key key_1 to database 8, you would run the following:
move key_1 8
move will return OK if moving the key was successful.
Deleting Keys
To delete one or more keys of any data type, use the del command
followed by one or more keys that you want to delete:
del key_1 key_2
If this command deletes the key(s) successfully it will return
(integer) 1. Otherwise, it will return (integer) 0.
The unlink command performs a similar function as del, with the
difference being that del blocks the client as the server reclaims the
memory taken up by the key. If the key being deleted is associated with a
small object, the amount of time it takes for del to reclaim the memory is
very small and the blocking time may not even be noticeable.
However, it can become inconvenient if, for example, the key you’re
deleting is associated with many objects, such as a hash with thousands or
millions of fields. Deleting such a key can take a noticeably long time, and
you’ll be blocked from performing any other operations until it’s fully
removed from the server’s memory.
unlink, however, first determines the cost of deallocating the memory
taken up by the key. If it’s small then unlink functions the same way as
del by the key immediately while also blocking the client. However, if
there’s a high cost to deallocate memory for a key, unlink will delete the
key asynchronously by creating another thread and incrementally reclaim
memory in the background without blocking the client:
unlink key_1
Since it runs in the background, it’s generally recommended that you
use unlink to remove keys from your server to reduce errors on your
clients, though del will also suffice in many cases.
Warning: The following two commands are considered dangerous. The
flushdb and flushall commands will irreversibly delete all the keys
in a single database and all the keys in every database on the Redis server,
respectively. We recommend that you only run these commands if you are
absolutely certain that you want to delete all the keys in your database or
server.
It may be in your interest to rename these commands to something with
a lower likelihood of being run accidentally.
To delete all the keys in the selected database, use the flushdb
command:
flushdb
To delete all the keys in every database on a Redis server (including the
currently selected database), run flushall:
flushall
Both flushdb and flushall accept the async option, which allows
you to delete all the keys on a single database or every database in the
cluster asynchronously. This allows them to function similarly to the
unlink command, and they will create a new thread to incrementally
free up memory in the background.
/etc/redis/redis.conf
. . .
save 900 1
save 300 10
save 60 10000
. . .
dbfilename "nextfile.rdb"
. . .
With these settings, Redis will export a snapshot of the database to the
file defined by the dbfilename parameter every 900 seconds if at least
1 key is changed, every 300 seconds if at least 10 keys are changed, and
every 60 seconds if at least 10000 keys are changed.
You can use the shutdown command to back up your Redis data and
then close your connection. This command will block every client
connected to the database and then perform a save operation if at least
one save point is configured, meaning that it will export the database in its
current state to an .rdb file while preventing clients from making any
changes.
Additionally, the shutdown command will flush changes to Redis’s
append-only file before quitting if append-only mode is enabled. The
append-only file mode (AOF) involves creating a log of every write
operation on the server in a file ending in .aof after every snapshot. AOF
and RDB modes can be enabled on the same server, and using both
persistence methods is an effective way to back up your data.
In short, the shutdown command is essentially a blocking save
command that also flushes all recent changes to the append-only file and
closes the connection to the Redis instance:
Warning: The shutdown command is considered dangerous. By
blocking your Redis server’s clients, you can make your data unavailable
to users and applications that depend on it. We recommend that you only
run this command if you are testing out Redis’s behavior or you are
absolutely certain that you want to block all your Redis server’s clients.
In fact, it may be in your interest to rename this command to something
with a lower likelihood of being run accidentally.
shutdown
If you’ve not configured any save points but still want Redis to perform
a save operation, append the save option to the `shutdown command:
shutdown save
If you have configured at least one save point but you want to shut down
the Redis server without performing a save, you can add the nosave
argument to the command:
shutdown nosave
Note that the append-only file can grow to be very long over time, but
you can configure Redis to rewrite the file based on certain variables by
editing the redis.conf file. You can also instruct Redis to rewrite the
append-only file by running the bgrewriteaof command:
bgrewriteaof
bgrewriteaof will create the shortest set of commands needed to
bring the database back to its current state. As this command’s name
implies, it will run in the background. However, if another persistence
command is running in a background process already, that command must
finish before Redis will execute bgrewriteaof.
Conclusion
This guide details a number of commands used to manage databases and
keys. If there are other related commands, arguments, or procedures you’d
like to see in this guide, please ask or make suggestions in the comments
below.
For more information on Redis commands, see our tutorial series on
How to Manage a Redis Database.
How To Manage Replicas and Clients in
Redis
Managing Replicas
One of Redis’s most distinguishing features is its built-in replication.
When using replication, Redis creates exact copies of the primary
instance. These secondary instances reconnect to the primary any time
their connections break and will always aim to remain an exact copy of the
primary.
If you’re not sure whether the Redis instance you’re currently connected
to is a primary instance or a replica, you can check by running the role
command:
role
This command will return either master or slave, or potentially
sentinel if you’re using Redis Sentinel.
To designate a Redis instance as a replica of another instance on the fly,
run the replicaof command. This command takes the intended primary
server’s hostname or IP address and port as arguments:
replicaof hostname_or_IP port
If the server was already a replica of another primary, it will stop
replicating the old server and immediately start synchronizing with the
new one. It will also discard the old dataset.
To promote a replica back to being a primary, run the following
replicaof command:
replicaof no one
This will stop the instance from replicating the primary server, but will
not discard the dataset it has already replicated. This syntax is useful in
cases where the original primary fails. After running replicaof no
one on a replica of the failed primary, the former replica can be used as
the new primary and have its own replicas as a failsafe.
Note: Prior to version 5.0.0, Redis instead included a version of this
command named slaveof.
Managing Clients
A client is any machine or software that connects to a server in order to
access a service. Redis comes with several commands that help with
tracking and managing client connections.
The client list command returns a set of human-readable
information about current client connections:
client list
Output
Output
"elaine"
Output
(integer) "19492"
Redis client IDs are never repeated and are monotonically incremental.
This means that if one client has an ID greater than another, then it was
established at a later time.
Blocking Clients and Closing Client Connections
Replication systems are typically described as being either synchronous or
asynchronous. In synchronous replication, whenever a client adds or
changes data it must receive some kind of acknowledgement from a
certain number of replicas for the change to register as having been
committed. This helps to prevent nodes from having data conflicts but it
comes at a cost of latency, since the client must wait to perform another
operation until it has heard back from a certain number of replicas.
In asynchronous replication, on the other hand, the client sees a
confirmation that the operation is finished as soon as the data is written to
local storage. There can, however, be a lag between this and when the
replicas actually write the data. If one of the replicas fails before it can
write the change, that write will be lost forever. So while asynchronous
replication allows clients to continue performing operations without the
latency caused by waiting for replicas, it can lead to data conflicts between
nodes and may require extra work on the part of the database administrator
to resolve those conflicts.
Because of its focus on performance and low latency, Redis implements
asynchronous replication by default. However, you can simulate
synchronous replication with the wait command. wait blocks the
current client connection for a specified amount of time (in milliseconds)
until all the previous write commands are successfully transferred and
accepted by a specified number of replicas. This command uses the
following syntax:
wait number_of_replicas number_of_milliseconds
For example, if you want to block your client connection until all the
previous writes are registered by at least 3 replicas within a 30 millisecond
timeout, your wait syntax would look like this:
wait 3 30
The wait command returns an integer representing the number of
replicas that acknowledged the write commands, even if not every replica
does so:
Output
Conclusion
This guide details a number of commands used to manage Redis clients
and replicas. If there are other related commands, arguments, or
procedures you’d like to see outlined in this guide, please ask or make
suggestions in the comments below.
For more information on Redis commands, see our tutorial series on
How to Manage a Redis Database.
How To Manage Strings in Redis
Output
OK
Output
(integer) 16
Note that append can also be used to change the contents of strings.
See the section on manipulating strings for details on this.
Retrieving Strings
To retrieve a string, use the get command:
get key_Welcome1
Output
"Howdy"
Output
1) "Howdy"
2) "there"
3) "partners,"
4) "welcome to Texas"
For every key passed to mget that doesn’t hold a string value or doesn’t
exist at all, the command will return nil.
Manipulating Strings
If a string is made up of an integer, you can run the incr command to
increase it by one:
set key_1 3
incr key_1
Output
(integer) 4
Output
(integer) 20
The decr and decrby commands work the same way, but they
decrease the integer stored in a numeric string:
decr key_1
Output
(integer) 19
decrby key_1 16
Output
(integer) 3
Output
(integer) 15
You can also append integers to a string holding a numeric value. The
following example appends 45 to 3, the integer held in key_1, so it will
then hold 345. In this case, append will also return the new length of the
string, rather than its new value:
append key_1 45
Output
(integer) 3
Because this key still only holds a numeric value, you can perform the
incr and decr operations on it. You can also append alphabetic
characters to an integer string, but if you do this then running incr and
decr on the string will produce an error as the string value is no longer an
integer.
Conclusion
This guide details a number of commands used to create and manage
strings in Redis. If there are other related commands, arguments, or
procedures you’d like to see outlined in this guide, please ask or make
suggestions in the comments below.
For more information on Redis commands, see our tutorial series on
How to Manage a Redis Database.
How To Manage Lists in Redis
Creating Lists
A key can only hold one list, although any list can hold over four billion
elements. Redis reads lists from left to right, and you can add new list
elements to the head of a list (the “left” end) with the lpush command or
the tail (the “right” end) with rpush. You can also use lpush or rpush
to create a new list:
lpush key value
Both commands will output an integer showing how many elements are
in the list. To illustrate, run the following commands to create a list
containing the dictum “I think therefore I am”:
lpush key_philosophy1 "therefore"
lpush key_philosophy1 "think"
rpush key_philosophy1 "I"
lpush key_philosophy1 "I"
rpush key_philosophy1 "am"
The output from the last command will read:
Output
(integer) 5
Note that you can add multiple list elements with a single lpush or
rpush statement:
rpush key_philosophy1 "-" "Rene" "Decartes"
The lpushx and rpushx commands are also used to add elements to
lists, but will only work if the given list already exists. If either command
fails, it will return (integer) 0:
rpushx key_philosophy2 "Happiness" "is" "the"
"highest" "good" "–" "Aristotle"
Output
(integer) 0
It isn’t possible to convert Redis keys from one data type to another, so
to turn key_philosophy3 into a list you would need to delete the key
and start over with an lpush or rpush command.
Output
1) "I"
2) "think"
3) "therefore"
4) "I"
5) "am"
6) "sayeth"
7) "Rene"
8) "Decartes"
The offsets passed to lrange can also be negative numbers. When
used in this case, -1 represents the final element in the list, -2 represents
the second-to-last element in the list, and so on. The following example
returns the last three elements of the list held in key_philosophy1:
lrange key_philosophy1 -3 -1
Output
1) "I"
2) "am"
3) "sayeth"
To retrieve a single element from a list, you can use the lindex
command. However, this command requires you to supply the element’s
index as an argument. As with lrange, the index is zero-based, meaning
that the first element is at index 0, the second is at index 1, and so on:
lindex key_philosophy1 4
Output
"am"
To find out how many elements are in a given list, use the llen
command, which is short for “list length”:
llen key_philosophy1
Output
(integer) 8
If the value stored at the given key does not exist, llen will return an
error.
Output
(integer) 1
Output
(integer) 2
The lpop command removes and returns the first, or “leftmost”
element from a list:
lpop key_Bond
Output
"Never"
Output
"Dies"
Redis also includes the rpoplpush command, which removes the last
element from a list and pushes it to the beginning of another list:
rpoplpush key_Bond key_AfterToday
Output
"Tomorrow"
Conclusion
This guide details a number of commands that you can use to create and
manage lists in Redis. If there are other related commands, arguments, or
procedures you’d like to see outlined in this guide, please ask or make
suggestions in the comments below.
For more information on Redis commands, see our tutorial series on
How to Manage a Redis Database.
How To Manage Hashes in Redis
Creating Hashes
To create a hash, run the hset command. This command accepts the
name of the hash key, the field string, and corresponding value string as
arguments:
hset poet:Verlaine nationality French
Note: In this example and the following ones, poet:Verlaine is the
hash key. Dots, dashes, and colons are commonly used to make multi-word
keys and fields more readable. It’s helpful to make sure that your keys
follow a consistent and easily readable format.
hset returns (integer) 1 if the field specified is a new field and
the value was set correctly:
Output
(integer) 1
If, however, you fail to include a value, field, or name for the hash key,
hset will return an error.
Also, note that hset will overwrite the contents of the hash if it already
exists:
hset poet:Verlaine nationality Francais
If the field already exists and its value was updated successfully, hset
will return (integer) 0:
Output
(integer) 0
You can also use hsetnx to add fields to hashes, but it will only work
if the field does not yet exist. If the specified field does already exist, the
hsetnx won’t have any effect and will return (integer) 0:
hsetnx poet:Verlaine nationality French
Output
(integer) 0
Output
"Francais"
hmget uses the same syntax, but can return the values of multiple
fields
hmget poet:Verlaine born died
Output
1) "1844"
2) "1896"
If the hash you pass to hget or hmget does not exist, both commands
will return (nil):
hmget poet:Dickinson born died
Output
1) (nil)
2) (nil)
To obtain a list of all the fields held within a certain hash, run the
hkeys command:
hkeys poet:Verlaine
Output
1) "nationality"
2) "born"
3) "died"
4) "genre"
Output
1) "French"
2) "1844"
3) "1896"
4) "Decadent"
To return a list of every field held by a hash and their associated values,
run hgetall:
hgetall poet:Verlaine
Output
1) "nationality"
2) "French"
3) "born"
4) "1844"
5) "died"
6) "1896"
7) "genre"
8) "Decadent"
You can find the number of fields in a hash by running hlen, which
stands for “hash length”:
hlen poet:Verlaine
Output
(integer) 4
You can find the length of the value string associated with a field with
hstrlen, which stands for “hash string length”:
hstrlen poet:Verlaine nationality
Output
(integer) 8
Output
(integer) 2
If you pass a field that does not exist to hdel, it will ignore that field
but delete any other existing fields you specify.
Conclusion
This guide details a number of commands used to create and manage
hashes in Redis. If there are other related commands, arguments, or
procedures you’d like to see outlined in this guide, please ask or make
suggestions in the comments below.
For more information on Redis commands, see our tutorial series on
How to Manage a Redis Database.
How To Manage Sets in Redis
Creating Sets
The sadd command allows you to create a set and add one or more
members to it. The following example will create a set at a key named
key_horror with the members "Frankenstein" and "Godzilla":
sadd key_horror "Frankenstein" "Godzilla"
If successful, sadd will return an integer showing how many members
it added to the set:
Output
(integer) 2
If you try adding members of a set to a key that’s already holding a non-
set value, it will return an error. The first command in this block creates a
list named key_action with one element, "Shaft". The next
command tries to add a set member, "Shane", to the list, but this
produces an error because of the clashing data types:
rpush key_action "Shaft"
sadd key_action "Shane"
Output
Note that sets don’t allow more than one occurrence of the same
member:
sadd key_comedy "It's" "A" "Mad" "Mad" "Mad" "Mad"
"Mad" "World"
Output
(integer) 4
Output
1) "Curly"
2) "Moe"
3) "Larry"
4) "Shemp"
5) "Curly Joe"
6) "Joe"
Output
(integer) 0
To see how many members are in a given set (in other words, to find the
cardinality of a given set), run scard:
scard key_stooges
Output
(integer) 6
Output
"Larry"
To return multiple random, distinct elements from a set, you can follow
the srandmember command with the number of elements you want to
retrieve:
srandmember key_stooges 3
Output
1) "Larry"
2) "Moe"
3) "Curly Joe"
Output
1) "Shemp"
2) "Curly Joe"
3) "Curly Joe"
The random element function used in srandmember is not perfectly
random, although its performance improves in larger data sets. See the
command’s official documentation for more details.
Output
1) "Shemp"
2) "Larry"
srem allows you to remove one or more specific members from a set,
rather than random ones:
srem key_stooges "Joe" "Curly Joe"
Instead of returning the members removed from the set, srem returns
an integer showing how many members were removed:
Output
(integer) 2
Use smove to move a member from one set to another. This command
accepts as arguments the source set, the destination set, and the member to
move, in that order. Note that smove only allows you to move one
member at a time:
smove key_stooges key_jambands "Moe"
If the command moves the member successfully, it will return
(integer) 1:
Output
(integer) 1
Comparing Sets
Redis also provides a number of commands that find the differences and
similarities between sets. To demonstrate how these work, this section will
reference three sets named presidents, kings, and beatles. If
you’d like to try out the commands in this section yourself, create these
sets and populate them using the following sadd commands:
sadd presidents "George" "John" "Thomas" "James"
sadd kings "Edward" "Henry" "John" "James"
"George"
sadd beatles "John" "George" "Paul" "Ringo"
sinter compares different sets and returns the set intersection, or
values that appear in every set:
sinter presidents kings beatles
Output
1) "John"
2) "George"
Output
1) "John"
2) "George"
Output
1) "Thomas"
In other words, sdiff looks at each member in the first given set and
then compares those to members in each successive set. Any member in
the first set that also appears in the following sets is removed, and sdiff
returns the remaining members. Think of it as removing members of
subsequent sets from the first set.
sdiffstore performs a function similar to sdiff, but instead of
returning the set difference it creates a new set at a given destination,
containing the set difference:
sdiffstore new_set beatles kings presidents
smembers new_set
Output
1) "Paul"
2) "Ringo"
1) "Thomas"
2) "George"
3) "Paul"
4) "Henry"
5) "James"
6) "Edward"
7) "John"
8) "Ringo"
sunion treats the results like a new set in that it only allows one
occurrence of any given member.
sunionstore performs a similar function, but creates a new set
containing the set union at a given destination instead of just returning the
results:
sunionstore new_set presidents kings beatles
Output
(integer) 8
Conclusion
This guide details a number of commands used to create and manage sets
in Redis. If there are other related commands, arguments, or procedures
you’d like to see outlined in this guide, please ask or make suggestions in
the comments below.
For more information on Redis commands, see our tutorial series on
How to Manage a Redis Database.
How To Manage Sorted Sets in Redis
Output
(integer) 1
You can add more than one member to a sorted set with zadd. Note that
their scores don’t need to be sequential, there can be gaps between scores,
and multiple members held in the same sorted set can share the same
score:
zadd faveGuitarists 4 "Stephen Malkmus" 2 "Rosetta
Tharpe" 3 "Bola Sete" 3 "Doug Martsch" 8
"Elizabeth Cotten" 12 "Nancy Wilson" 4 "Memphis
Minnie" 12 "Michael Houser"
Output
(integer) 8
zadd can accept the following options, which you must enter after the
key name and before the first member score:
CH: Normally, zadd only returns the number of new elements added
to the sorted set. With this option included, though, zadd will return
the number changed elements. This includes newly added members
and members whose scores were changed.
INCR: This causes the command to increment the member’s score
value. If the member doesn’t yet exist, the command will add it to the
sorted set with the increment as its score, as if its original score was
0. With INCR included, the zadd will return the member’s new
score if it’s successful. Note that you can only include one
score/member pair at a time when using this option.
Instead of passing the INCR option to zadd, you can instead use the
zincrby command which behaves the exact same way. Instead of giving
the sorted set member the value indicated by the score value like zadd, it
increments that member’s score up by that value. For example, the
following command increments the score of the member "Stephen
Malkmus", which was originally 4, up by 5 to 9.
zincrby faveGuitarists 5 "Stephen Malkmus"
Output
"9"
As is the case with the zadd command’s INCR option, if the specified
member doesn’t exist then zincrby will create it with the increment
value as its score.
Output
1) "Joe Pass"
2) "Rosetta Tharpe"
3) "Bola Sete"
4) "Doug Martsch"
Note that if the sorted set you pass to zrange has two or more
elements that share the same score, it will sort those elements in
lexicographical, or alphabetical, order.
The start and stop indexes can also be negative numbers, with -1
representing the last member, -2 representing the second to last, and so
on:
zrange faveGuitarists -5 -2
Output
1) "Memphis Minnie"
2) "Elizabeth Cotten"
3) "Stephen Malkmus"
4) "Michael Houser"
zrange can accept the WITHSCORES argument which, when included,
will also return the members’ scores:
zrange faveGuitarists 5 6 WITHSCORES
Output
1) "Elizabeth Cotten"
2) "8"
3) "Stephen Malkmus"
4) "9"
Output
1) "Nancy Wilson"
2) "Michael Houser"
3) "Stephen Malkmus"
4) "Elizabeth Cotten"
5) "Memphis Minnie"
6) "Doug Martsch"
zrevrange can also accept the WITHSCORES option.
You can return a range of members based on their scores with the
zrangebyscore command. In the following example, the command
will return any member held in the faveGuitarists key with a score
of 2, 3, or 4:
zrangebyscore faveGuitarists 2 4
Output
1) "Rosetta Tharpe"
2) "Bola Sete"
3) "Doug Martsch"
4) "Memphis Minnie"
Output
1) "Rosetta Tharpe"
2) "Bola Sete"
3) "Doug Martsch"
Output
1) "Rosetta Tharpe"
2) "Bola Sete"
3) "Doug Martsch"
Output
1) "Stephen Malkmus"
2) "Elizabeth Cotten"
Output
1) "assembly"
2) "ball"
3) "magoun"
4) "porter"
Notice that this example returned only four of the eight members in the
set, even though the command sought a range from a to z. This is because
Redis values are case-sensitive, so the members that begin with uppercase
letters were excluded from its output. To return those, you could run the
following:
zrangebylex SomervilleSquares [A [z
Output
1) "Davis"
2) "Inman"
3) "Union"
4) "assembly"
5) "ball"
6) "magoun"
7) "porter"
Output
1) "porter"
2) "magoun"
3) "ball"
4) "assembly"
5) "Union"
6) "Inman"
7) "Davis"
Because it’s intended for use with sorted sets where every member has
the same score, zrangebylex does not accept the WITHSCORES option.
It does, however, accept the LIMIT option.
Output
(integer) 9
zcount can tell you how many elements are held within a given sorted
set that fall within a range of scores. The first number following the key is
the start of the range and the second one is the end of the range:
zcount faveGuitarists 3 8
Output
(integer) 4
"3"
If either the specified member or key don’t exist, zscore will return
(nil).
zrank is similar to zscore, but instead of returning the given
member’s score, it instead returns its rank. In Redis, a rank is a zero-based
index of the members of a sorted set, ordered by their score. For example,
"Joe Pass" has a score of 1, but because that is the lowest score of any
member in the key, it has a rank of 0:
zrank faveGuitarists "Joe Pass"
Output
(integer) 0
Output
(integer) 8
The only relation between a member’s score and their rank is where
their score stands in relation to those of other members. If there is a score
gap between two sequential members, that won’t be reflected in their rank.
Note that if two members have the same score, the one that comes first
alphabetically will have the lower rank.
Like zscore, zrank and zrevrank will return (nil) if the key or
member doesn’t exist.
zlexcount can tell you how many members are held in a sorted set
between a lexicographical range. The following example uses the
SomervilleSquares sorted set from the previous section:
zlexcount SomervilleSquares [M [t
Output
(integer) 5
Output
(integer) 2
There are three Redis commands that allow you to remove members of
a sorted set based on a range. For example, if each member in a sorted set
has the same score, you can remove members based on a lexicographical
range with zremrangebylex. This command uses the same syntax as
zrangebylex. The following example will remove every member that
begins with a capital letter from the SomervilleSquares key created
in the previous section:
zremrangebylex SomervilleSquares [A [Z
zremrangebylex will output an integer indicating how many
members it removed:
Output
(integer) 3
You can also remove members based on a range of scores with the
zremrangebyscore command, which uses the same syntax as the
zrangebyscore command. The following example will remove every
member held in faveGuitarists with a score of 4, 5, or 6:
zremrangebyscore faveGuitarists 4 6
Output
(integer) 1
You can remove members from a set based on a range of ranks with the
zremrangebyrank command, which uses the same syntax as
zrangebyrank. The following command will remove the three
members of the sorted set with the lowest rankings, which are defined by a
range of zero-based indexes:
zremrangebyrank faveGuitarists 0 2
Output
(integer) 3
Output
(integer) 1
Output
(integer) 9
Output
"9"
Output
"21"
Conclusion
This guide details a number of commands used to create and manage
sorted sets in Redis. If there are other related commands, arguments, or
procedures you’d like to see outlined in this guide, please ask or make
suggestions in the comments below.
For more information on Redis commands, see our tutorial series on
How to Manage a Redis Database.
How To Run Transactions in Redis
Running Transactions
The multi command tells Redis to begin a transaction block. Any
subsequent commands will be queued up until you run an exec command,
which will execute them.
The following commands form a single transaction block. The first
command initiates the transaction, the second sets a key holding a string
with the value of 1, the third increases the value by 1, the fourth increases
its value by 40, the fifth returns the current value of the string, and the last
one executes the transaction block:
multi
set key_MeaningOfLife 1
incr key_MeaningOfLife
incrby key_MeaningOfLife 40
get key_MeaningOfLife
exec
After running multi, redis-cli will respond to each of the
following commands with QUEUED. After you run the exec command, it
will show the output of each of those commands individually:
Output
1) OK
2) (integer) 2
3) (integer) 42
4) "42"
Canceling Transactions
To cancel a transaction, run the discard command. This prevents any
previously-queued commands from running:
multi
set key_A 146
incrby key_A 10
discard
Output
OK
Output
Output
In cases like this, you’ll need to restart the transaction block and make
sure you enter each command correctly.
Some impossible commands are possible to queue, such as running
incr on a key containing only a string. Because such command is
syntactically correct, Redis won’t return an error if you try to include it in
a transaction and won’t prevent you from running exec. In cases like this,
all other commands in the queue will be executed, but the impossible
command will return an error:
multi
set key_A 146
incrby key_A "ten"
exec
Output
1) OK
2) (error) ERR value is not an integer or out of
range
Output
(integer) 433
For more granular information, you can run pttl which will instead
return the amount of time until a key expires in milliseconds:
pttl key_melon
Output
(integer) 431506
Both ttl and pttl will return (integer) -1 if the key hasn’t been
set to expire and (integer) -2 if the key does not exist.
Persisting Keys
If a key has been set to expire, any command that overwrites the contents
of a key — like set or getset — will clear a key’s timeout value. To
manually clear a key’s timeout, use the persist command:
persist key_melon
The persist command will return (integer) 1 if it completed
successfully, indicating that the key will no longer expire.
Conclusion
This guide details a number of commands used to manipulate and check
key persistence in Redis. If there are other related commands, arguments,
or procedures you’d like to see outlined in this guide, please ask or make
suggestions in the comments below.
For more information on Redis commands, see our tutorial series on
How to Manage a Redis Database.
How To Troubleshoot Issues in Redis
Output
(integer) 42
Output
OK
1566157213.896437 [0 127.0.0.1:47740] "auth"
"foobared"
1566157215.870306 [0 127.0.0.1:47740] "set"
"key_1" "878"
Another command useful for debugging is info, which returns several
blocks of information and statistics about the server:
info
Output
# Server
redis_version:4.0.9
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:9435c3c2879311f3
redis_mode:standalone
os:Linux 4.15.0-52-generic x86_64
. . .
This command returns a lot of information. If you only want to see one
info block, you can specify it as an argument to info:
info CPU
Output
# CPU
used_cpu_sys:173.16
used_cpu_user:70.89
used_cpu_sys_children:0.01
used_cpu_user_children:0.04
Note that the information returned by the info command will depend
on which version of Redis you’re using.
Using the keys Command
The keys command is helpful in cases where you’ve forgotten the name
of a key, or perhaps you’ve created one but accidentally misspelled its
name. keys looks for keys that match a pattern:
keys pattern
The following glob-style variables are supported
Introduction
Redis is an open-source, in-memory key-value data store. Redis has
several commands that allow you to make changes to the Redis server’s
configuration settings on the fly. This tutorial will go over some of these
commands, and also explain how to make these configuration changes
permanent.
Output
1) "repl-ping-slave-period"
2) "10"
3) "repl-timeout"
4) "60"
5) "repl-backlog-size"
6) "1048576"
7) "repl-backlog-ttl"
8) "3600"
9) "repl-diskless-sync-delay"
10) "5"
11) "repl-disable-tcp-nodelay"
12) "no"
13) "repl-diskless-sync"
14) "no"