Quick tour in Redis

Overview

Redis is what is called a key-value store, often referred to as a NoSQL database. The essence of a key-value store is the ability to store some data, called a value, inside a key. This data can later be retrieved only if we know the exact key used to store it.

Setup

Excute these commands in CMD to install (assuming you are using Mac/Unix)

1
2
3
4
5
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make
sudo make install

Then you can run make test to confirm your installment.

Data structure

  • Binary-safe strings
  • Lists
    • LPUSH, RPUSH, LPOP, RPOP
  • Sets
  • Sorted set (set in which each value has an associated score)
  • Hashes
    • HSET
    • HGETALL
    • HGET
    • HINCRBY
    • HDEL
  • Bit arrays
  • HyperLogLogs

Basic comments

We can use the command SET to store the value “fido” at key “server:name”:
SET server:name "fido"
Redis will store our data permanently, so we can later ask “What is the value stored at key server:name?” and Redis will reply with “fido”:
GET server:name => "fido"

Other common operations provided by key-value stores are DEL to delete a given key and associated value, SET-if-not-exists (called SETNX on Redis) that sets a key only if it does not already exist, and INCR to atomically increment a number stored at a given key

LLEN returns the current length of the list.
LPOP removes the first element from the list and returns it.
RPOP removes the last element from the list and returns it.

A set is similar to a list, except it does not have a specific order and each element may only appear once. Some of the important commands in working with sets are SADD, SREM, SISMEMBER, SMEMBERS and SUNION.

SADD adds the given value to the set.

1
SADD superpowers "flight"

SREM removes the given value from the set.
SISMEMBER tests if the given value is in the set. It returns 1 if the value is there and 0 if it is not.
SISMEMBER superpowers “flight” => 1
SMEMBERS returns a list of all the members of this set.
SMEMBERS superpowers => 1) “flight”, 2) “x-ray vision”
SUNION combines two or more sets and returns the list of all elements.

ZADD, ZRANGE are the equivalent in sorted set.

ZCOUNT key min max : Returns the number of elements in the sorted set at key with a score between min and max

ZREVRANGEBYSCORE key max min: Returns all the elements in the sorted set at key with a score between max and min (including elements with score equal to max or min)

Reference