Redis datatypes
From wikinotes
Documentation
commands (note filter by datatype) https://redis.io/commands
Keys
- keys are binary safe (safe to use string, or contents of a jpg)
- keys are unique, should be long enough to be descriptive, but not so long to inflate lookup cost
- keys are automatically added by set/rpush/... operations if key does not yet exist
- keys are automatically deleted when they do not hold a value
- you cannot get/set a key at the same time, making it possible to use redis as a queue
- you can assign a TTL on keys
Nil
Strings
https://redis.io/commands#string
- strings are binary safe (may contain binary blobs)
- strings can have a size up to 512MB
SET key value # a string SET key 100 # still a string SETBIT foo 2 f # set key 'foo's 2nd character to 'f' SETNX foo 1 # set key 'foo' if not exists MSET key-1 1 key-2 2 # set multiple keys at once INCR key # increments string as if were number
Collections
Lists
https://redis.io/commands#list
- retrieving items is O(n)
- lists are 0-indexed
- lists support negative indexes (starting from tail of list)
- popping items from an empty list returns
(nil)
.- lists can support very large numbers of items, queues for example often refer to a single key, continuously pushing items to the end of the list.
RPUSH key 1 # append '1' to list (returns index) (creates if not exist) LPUSH key 1 # prepend '1' to list (returns index) (creates if not exist) LPOP key # remove/return first item in list RPOP key # remove/return last item in list BLPOP key 5 # remove/return first item in list (wait up to 5s before returning if empty -- more efficient polling) BRPOP key 5 # remove/return last item in lest (wait up to 5s before returning if empty -- more efficient polling) LRANGE 0 -1 # list all elements in list LTRIM 0 2 # return first 2x items in list, and remove all other items from itSets
- retrieving items is O(1) -> O(n)
- all members are strings
SADD key 1 2 3 # add elements to set SMEMBERS key # print all members of set SISMEMBER key 2 # test if '2' is member of set SPOP # return random elementSorted Sets
A set that is sorted by a score string.
# {score} {value} ZADD key 0 Ottawa ZADD key 201 Montreal ZADD key 451 Toronto ZRANGE key 0 -1 # show all items in set ZRANGEBYSCORE key -inf 300 # all items with score up to 300 ZREMRANGEBYSCORE key 200 300 # remove all items with scores between 200 and 300Hashes
https://redis.io/commands#hash
HKEYS key # list all keys in hash HGET key mapkey-2 HGETALL key HMGET key mapkey-1 mapkey-2 # get hash-map value HSET key mapkey-1 val-1 # create/update single hash-map value HMSET key mapkey-1 val-1 mapkey-2 val-2 # create/update multiple hash-map valuesHyperLogLogs
Stores and counts unique entries in a set in a memory optimized way.
PFADD key a a b c # add 4x items to a hyperloglog PFCOUNT key # 3 (num of unique items)