An Introduction to REDIS SERVER, an advanced key value
By: Ali MasudianPour <firstname.lastname@example.org>
What REDIS is
Redis is an open source, BSD licensed, advanced key-value
store. It is often referred to as a data structure server since keys
can contain strings, hashes, lists, sets and sorted sets.
– It stands for REmote DIctionary Server
not a plain key-value store, a data structures server
supporting different kind of values
Free and open source
Easy to user
Easy to learn
Supported Data Types
Lists of binary-safe strings.
Sets of binary-safe strings, that are collection of unique unsorted
Sorted sets, similar to Sets but where every element is
associated to a floating number score. The elements are taken
sorted by score.
KEYS - VALUES
In REDIS, Keys are binary safe
– This means that you can use any binary sequence as key
From String like 'foo' to the content of a JPEG file
– REDIS keys accept empty
In REDIS, Values
– Can not be bigger than 512MB
To set a value to a key we use SET statement
– SET key value
– SET foo bar
– In above example we told redis to set bar value to foo key
To set string value we use double quotations
– SET keyname “The string content of value”
To get a value from redis we use GET statement
– GET keyname
– GET foo // it will return bar
– In above example we told redis to get foo key value.
Automatic increment by REDIS
– To use automatic increment of redis we use INCR
– Set counter 1
// Output wil be 2
We can also use INCRBY
– Set counter 1
– Incr counter
– // Output wil be 2
– Incrby counter 10
– //outpur will be 12
In opposite of INCR and INCRBY redis contains DESC and
– Just like DECR and DECRBY
– Set counter 10
// Output wil be 9
decrby counter 5
//output will be 4
EXPIRE and TTL
In REDIS we can set keys to expire in a given and specific
amount of time.
– To do that we use EXPIRE command
Set foo bar
Expire foo 50
– To find out how many time a key have we use TTL command
For instance after 10 second of declaring foo key if we use TTL command the
output will be something like below:
– Ttl foo
To create a list use LPUSH or RPUSH. If a list already exists,
LPUSH will add the given value to the beginning of the list and
RPUSH will add it to the end.
Redis lists contain the following commands
Sets are similar to lists but does not support duplication
– Add to sets
redis 127.0.0.1:6379> SADD names "Michael"
redis 127.0.0.1:6379> SADD names "JOHN"
redis 127.0.0.1:6379> SMEMBERS names
Now, if you try to add another set member with JOHN value it
will do nothing, because sets do not support duplication.
Other useful commands for set
– SADD, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER,
SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE,
Using a hash, you can assign values to fields in each key.
Common Commands in hashes are:
– HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS,
HDEL, HLEN, HKEYS, HVALS, HGETALL