Redis is a database. To be more specific redis is a very simple database implementing a dictionary where keys are associated with values. For example I can set the key "surname_1992" to the string "Smith".
Redis takes the whole dataset in memory, but the dataset is persistent since from time to time Redis writes a dump of the dataset on disk. The dump is loaded every time the server is restarted.
This means that it can happen that after a system crash the last modifications of the dataset are lost, but it's the price to pay for a lot of speed. Redis is the right database for all the applications where it is acceptable after a crash that some modifications gets lost, but where speed is very important.
However you can configure Redis to save the DB after a given number of modifications and/or after a given amount of time since the last change in the dataset. Saving happens in background so the DB will continue to serve queries while it is saving the DB dump on disk.
Replication is under development in order to make Redis an highly available DB.
Mainly in two ways:
No, the idea is to provide atomic primitives in order to make the programmer able to use redis with locking free algorithms. For example imagine you have 10 computers and 1 redis server. You want to count words in a very large text. This large text is split among the 10 computers, every computer will process its part and use Redis's INCR command to atomically increment a counter for every occurrence of the word found.
INCR/DECR are not the only atomic primitives, there are others like PUSH/POP on lists, POP RANDOM KEY operations, UPDATE and so on. For example you can use Redis like a Tuple Space (http://en.wikipedia.org/wiki/Tuple_space) in order to implement distributed algorithms.
Another synchronization primitive is the support for multiple DBs. By default DB 0 is selected for every new connection, but using the SELECT command it is possible to select a different database. The MOVE operation can move an item from one DB to another atomically. This can be used as a base for locking free algorithms together with the 'RANDOMKEY' or 'POPRANDOMKEY' commands.
Redis supports the following three data types as values:
Values can be Strings, Lists or Sets. Keys can be a subset of strings not containing newlines ("\n") and spaces (" ").
Note that sometimes strings may hold numeric vaules that must be parsed by Redis. An example is the INCR command that atomically increments the number stored at the specified key. In this case Redis is able to handle integers that can be stored inside a 'long long' type, that is a 64-bit signed integer.
Strings are implemented as dynamically allocated strings of characters. Lists are implemented as doubly linked lists with cached length. Sets are implemented using hash tables that use chaining to resolve collisions.
(note, you can skip this section if you are only interested in "formal" doc.)
Later in this document you can find detailed information about Redis commands, the protocol specification, and so on. This kind of documentation is useful but... if you are new to Redis it is also BORING! The Redis protocol is designed so that is both pretty efficient to be parsed by computers, but simple enough to be used by humans just poking around with the 'telnet' command, so this section will show to the reader how to play a bit with Redis to get an initial feeling about it, and how it works.
To start just compile redis with 'make' and start it with './redis-server'. The server will start and log stuff on the standard output, if you want it to log more edit redis.conf, set the loglevel to debug, and restart it.
You can specify a configuration file as unique parameter:
./redis-server /etc/redis.conf
This is NOT required. The server will start even without a configuration file using a default built-in configuration.
Now let's try to set a key to a given value:
$ telnet localhost 6379 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. SET foo 3 bar +OK
The first line we sent to the server is "set foo 3". This means "set the key foo with the following three bytes I'll send you". The following line is the "bar" string, that is, the three bytes. So the effect is to set the key "foo" to the value "bar". Very simple!
(note that you can send commands in lowercase and it will work anyway, commands are not case sensitive)
Note that after the first and the second line we sent to the server there is a newline at the end. The server expects commands terminated by "\r\n" and sequence of bytes terminated by "\r\n". This is a minimal overhead from the point of view of both the server and client but allows us to play with Redis with the telnet command easily.
The last line of the chat between server and client is "+OK". This means our key was added without problems. Actually SET can never fail but the "+OK" sent lets us know that the server received everything and the command was actually executed.
Let's try to get the key content now:
GET foo 3 bar
Ok that's very similar to 'set', just the other way around. We sent "get foo", the server replied with a first line that is just a number of bytes the value stored at key contained, followed by the actual bytes. Again "\r\n" are appended both to the bytes count and the actual data.
What about requesting a non existing key?
GET blabla nil
When the key does not exist instead of the length just the "nil" string is sent. Another way to check if a given key exists or not is indeed the EXISTS command:
EXISTS nokey 0 EXISTS foo 1
As you can see the server replied '0' the first time since 'nokey' does not exist, and '1' for 'foo', a key that actually exists.
Ok... now you know the basics, read the "REDIS COMMANDS REFERENCE" section to learn all the commands supported by Redis and the "PROTOCOL SPECIFICATION" section for more details about the protocol used if you plan to implement one for a language missing a decent client implementation.
Return value: none
Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 GB).
Return value: status code reply
Get the value of the specified key. If the key does not exist the special value 'nil' is returned. If the value stored at key is not a string an error is returned because GET can only handle string values.
Return value: bluk reply
SETNX works exactly like SET with the only difference that if the key already exists no operation is performed. SETNX actually means "SET if Not eXists".
*Return value: integer reply, specifically:
1 if the key was set 0 if the key was not set*
Increment the number stored at key by one. If the key does not exist or contains a value of a wrong type, set the key to the value of "1" (like if the previous value was zero).
INCRBY works just like INCR but instead to increment by 1 the increment is value.
Return value: integer reply
Test if the specified key exists. The command returns "0" if the key exists, otherwise "1" is returned. Note that even keys set with an empty string as value will return "1".
*Return value: integer reply, specifically:
1 if the key exists 0 if the key does not exist*
Remove the specified key. If the key does not exist no operation is performed. The command always returns success.
*Return value: integer reply, specifically:
1 if the key was removed 0 if the key does not exist*
Return value: single line reply
Returns all the keys matching the glob-style pattern as space separated strings. For example if you have in the database the keys "foo" and "foobar" the command "KEYS foo*
" will return "foo foobar".
Note that while the time complexity for this operation is O(n) the constant times are pretty low. For example Redis running on an entry level laptop can scan a 1 million keys database in 40 milliseconds. Still it's better to consider this one of the slow commands that may ruin the DB performance if not used with care.
Return value: bulk reply
Returns a random key from the currently seleted DB.
Return value: single line reply
Return value: status code reply
*Return value: integer reply, specifically:
1 if the key was renamed 0 if the target key already exist -1 if the source key does not exist -3 if source and destination keys are the same*
Add the given string to the head of the list contained at key. If the key does not exist an empty list is created just before the append operation. If the key exists but is not a List an error is returned.
Return value: status code reply
Add the given string to the tail of the list contained at key. If the key does not exist an empty list is created just before the append operation. If the key exists but is not a List an error is returned.
Return value: status code reply
Return the length of the list stored at the specified key. If the key does not exist zero is returned (the same behaviour as for empty lists). If the value stored at key is not a list the special value -1 is returned. Note: client library should raise an exception when -1 is returned instead to pass the value back to the caller like a normal list length value.
*Return value: integer reply, specifically:
the length of the list as an integer>=
0 if the operation succeeded -2 if the specified key does not hold a list value*
Return the specified elements of the list stored at the specified key. Start and end are zero-based indexes. 0 is the first element of the list (the list head), 1 the next element and so on.
For example LRANGE foobar 0 2 will return the first three elements of the list.
start and end can also be negative numbers indicating offsets from the end of the list. For example -1 is the last element of the list, -2 the penultimate element and so on.
Indexes out of range will not produce an error: if start is over the end of the list, or start >
end, an empty list is returned. If end is over the end of the list Redis will threat it just like the last element of the list.
Return value: multi bulk reply
Trim an existing list so that it will contain only the specified range of elements specified. Start and end are zero-based indexes. 0 is the first element of the list (the list head), 1 the next element and so on.
For example LTRIM foobar 0 2 will modify the list stored at foobar key so that only the first three elements of the list will remain.
start and end can also be negative numbers indicating offsets from the end of the list. For example -1 is the last element of the list, -2 the penultimate element and so on.
Indexes out of range will not produce an error: if start is over the end of the list, or start > end, an empty list is left as value. If end over the end of the list Redis will threat it just like the last element of the list.
Hint: the obvious use of LTRIM is together with LPUSH/RPUSH. For example:
LPUSH mylist <someelement> LTRIM mylist 0 99The above two commands will push elements in the list taking care that the list will not grow without limits. This is very useful when using Redis to store logs for example. It is important to note that when used in this way LTRIM is an O(1) operation because in the average case just one element is removed from the tail of the list.
Return value: status code reply
Return the specified element of the list stored at the specified key. 0 is the first element, 1 the second and so on. Negative indexes are supported, for example -1 is the last element, -2 the penultimate and so on.
If the value stored at key is not of list type an error is returned. If the index is out of range an empty string is returned.
Note that even if the average time complexity is O(n) asking for the first or the last element of the list is O(1).
Return value: bulk reply
Set the list element at index (see LINDEX for information about the index argument) with the new value. Out of range indexes will generate an error. Note that setting the first or last elements of the list is O(1).
Return value: status code reply
Atomically return and remove the first element of the list. For example if the list contains the elements "a","b","c" LPOP will return "a" and the list will become "b","c".
If the key does not exist or the list is already empty the special value 'nil' is returned.
Return value: bulk reply
Add the specified member to the set value stored at key. If member is already a member of the set no operation is performed. If key does not exist a new set with the specified member as sole member is crated. If the key exists but does not hold a set value an error is returned.
*Return value: integer reply, specifically:
1 if the new element was added 0 if the new element was already a member of the set -2 if the key contains a non set value*
Remove the specified member from the set value stored at key. If member was not a member of the set no operation is performed. If key does not exist or does not hold a set value an error is returned.
*Return value: integer reply, specifically:
1 if the new element was removed 0 if the new element was not a member of the set -2 if the key does not hold a set value*
Return the set cardinality (number of elements). If the key does not exist 0 is returned, like for empty sets. If the key does not hold a set value -1 is returned. Client libraries should raise an error when -1 is returned instead to pass the value to the caller.
*Return value: integer reply, specifically:
the cardinality (number of elements) of the set as an integer>=
0 if the operation succeeded -2 if the specified key does not hold a set value*
Return 1 if member is a member of the set stored at key, otherwise 0 is returned. On error a negative value is returned. Client libraries should raise an error when a negative value is returned instead to pass the value to the caller.
*Return value: integer reply, specifically:
1 if the element is a member of the set 0 if the element is not a member of the set OR if the key does not exist -2 if the key does not hold a set value*
Return the members of a set resulting from the intersection of all the sets hold at the specified keys. Like in LRANGE the result is sent to the client as a multi-bulk reply (see the protocol specification for more information). If just a single key is specified, then this command produces the same result as SELEMENTS. Actually SELEMENTS is just syntax sugar for SINTERSECT.
If at least one of the specified keys does not exist or does not hold a set value an error is returned.
Return value: multi bulk reply
Return all the members (elements) of the set value stored at key. This is just syntax glue for SINTERSECT.
Return value: status code reply
*Return value: integer reply, specifically:
1 if the key was moved 0 if the key was not moved because already present on the target DB or was not found in the current DB. -3 if the destination DB is the same as the source DB -4 if the database index if out of range*
Return value: status code reply
Return value: status code reply
Return value: integer reply (UNIX timestamp)
Return value: status code reply on error, on success the server quits and the connection is closed
The Redis protocol is a compromise between being easy to parse by a computer and being easy to parse by an human. Before reading this section you are strongly encouraged to read the "REDIS TUTORIAL" section of this README in order to get a first feeling of the protocol playing with it by TELNET.
A client connects to a Redis server creating a TCP connection to the port 6973. Every redis command or data transmitted by the client and the server is terminated by "\r\n" (CRLF).
The simplest commands are the inline commands. This is an example of a server/client chat (the server chat starts with S:, the client chat with C:)
C: PING S: +PONG
An inline command is a CRLF-terminated string sent to the client. The server usually replies to inline commands with a single line that can be a number or a return code.
When the server replies with a status code (that is a one line reply just indicating if the operation succeeded or not), if the first character of the reply is a "+" then the command succeeded, if it is a "-" then the following part of the string is an error.
The following is another example of an INLINE command returning an integer:
C: EXISTS somekey S: 0
Since 'somekey' does not exist the server returned '0'.
Note that the EXISTS command takes one argument. Arguments are separated simply by spaces.
A bulk command is exactly like an inline command, but the last argument of the command must be a stream of bytes in order to send data to the server. the "SET" command is a bulk command, see the following example:
C: SET mykey 6 C: foobar S: +OK
The last argument of the commnad is '6'. This specify the number of DATA bytes that will follow (note that even this bytes are terminated by two additional bytes of CRLF).
All the bulk commands are in this exact form: instead of the last argument the number of bytes that will follow is specified, followed by the bytes, and CRLF. In order to be more clear for the programmer this is the string sent by the client in the above sample:
"SET mykey 6\r\nfoobar\r\n"
The server may reply to an inline or bulk command with a bulk reply. See the following example:
C: GET mykey S: 6 S: foobar
A bulk reply is very similar to the last argument of a bulk command. The server sends as the first line the number of bytes of the actual reply followed by CRLF, then the bytes are sent followed by additional two bytes for the final CRLF. The exact sequence sent by the server is:
"6\r\nfoobar\r\n"
If the requested value does not exist the bulk reply will use the special value 'nil' instead to send the line containing the number of bytes to read. This is an example:
C: GET nonexistingkey S: nil
The client library API should not return an empty string, but a nil object. For example a Ruby library should return 'nil' while a C library should return NULL.
Bulk replies can signal errors, for example trying to use GET against a list value is not permitted. Bulk replies use a negative bytes count in order to signal an error. An error string of ABS(bytes_count) bytes will follow. See the following example:
S: GET alistkey S: -38 S: -ERR Requested element is not a string
-38 means: sorry your operation resulted in an error, but a 38 bytes string that explains this error will follow. Client APIs should abort on this kind of errors, for example a PHP client should call the die() function.
The following commands reply with a bulk reply: GET, KEYS, LINDEX, LPOP, RPOP
In the specific case of the LRANGE command the server needs to return multiple values (every element of the list is a value, and LRANGE needs to return more than a single element). This is accomplished using multiple bulk writes, prefixed by an initial line indicating how many bulk writes will follow. Example:
C: LRANGE mylist 0 3 S: 4 S: 3 S: foo S: 3 S: bar S: 5 S: Hello S: 5 S: World
The first line the server sent is "4\r\n" in order to specify that four bulk write will follow. Then every bulk write is transmitted.
If the specified key does not exist instead of the number of elements in the list, the special value 'nil' is sent. Example:
C: LRANGE nokey 0 1 S: nil
A client library API SHOULD return a nil object and not an empty list when this happens. This makes possible to distinguish between empty list and non existing ones.
Like bulk reply errors Multi-bulk reply errors are reported using a negative count. Example:
C: LRANGE stringkey 0 1 S: -38 S: -ERR Requested element is not a string
The following commands reply with a multi-bulk reply: LRANGE, LINTER
Check the Bulk replies errors section for more information.
As already seen a status code reply is in the form of a single line string terminated by "\r\n". For example:
{{ +OK }}
and
{{ -ERR no suck key }}
are two examples of status code replies. The first character of a status code reply is always "+" or "-".
The following commands reply with a status code reply: PING, SET, SELECT, SAVE, BGSAVE, SHUTDOWN, RENAME, LPUSH, RPUSH, LSET, LTRIM
This type of reply is just a CRLF terminated string representing an integer. For example "0\r\n", or "1000\r\n" are integer replies.
With commands like INCR or LASTSAVE using the integer reply to actually return a value there is no special meaning for the returned integer. It is just an incremental number for INCR, a UNIX time for LASTSAVE and so on.
Some commands like EXISTS will return 1 for true and 0 for false.
Other commands like SADD, SREM and SETNX will return 1 if the operation was actually done, 0 otherwise, and a negative value if the operation is invalid (for example SADD against a non-set value), accordingly to this table: {{ -1 no such key -2 operation against the a key holding a value of the wrong type -3 source and destiantion objects/dbs are the same -4 argument out of range }} In all this cases it is mandatory that the client raises an error instead to pass the negative value to the caller. Please check the commands documentation for the exact behaviour.
The following commands will reply with an integer reply: SETNX, DEL, EXISTS, INCR, INCRBY, DECR, DECRBY, DBSIZE, LASTSAVE, RENAMENX, MOVE, LLEN, SADD, SREM, SISMEMBER, SCARD
The commands that will never return a negative integer (commands that can't fail) are: INCR, DECR, INCRBY, DECRBY, LASTSAVE, EXISTS, SETNX, DEL, DBSIZE.
This replies are just single line strings terminated by CRLF. Only two commands reply in this way currently, RANDOMKEY and TYPE.
A client can use the same connection in order to issue multiple commands. Pipelining is supported so multiple commands can be sent with a single write operation by the client, it is not needed to read the server reply in order to issue the next command. All the replies can be read at the end.
Usually Redis server and client will have a very fast link so this is not very important to support this feature in a client implementation, still if an application needs to issue a very large number of commands in short time to use pipelining can be much faster.
Redis is released under the GPL license, version 2. See the COPYING file for more information.
Redis is written and maintained by Salvatore Sanfilippo, Aka 'antirez'.
Enjoy, antirez