Skip to main content

Redis cheatsheet



Redis is considered a NoSQL database. I see it as a great and efficient in memory cache on steroids. I use it for storing results of large calculations so I can quickly display the results on a web page. I actually use it as a cache for a production instance of dashing.io.

Here's a good article about creating a dashboard using dashing.io - https://gocardless.com/blog/raspberry-pi-metric-dashboards/. Towards the bottom of the article check out the 'Persistance' section where there are instructions for adding Redis as the cache for dashing.

Website: http://redis.io/
Official Docker container: https://hub.docker.com/_/redis/
Docker command: docker run -d -p 6379:6379 -v `pwd`:/data --name redis-server redis

To run redis commands on the container, execute:
docker exec -it redis-server /bin/bash

That should get you to the bash shell on the container. Execute 'redis-cli' and you are ready to start creating your keys in redis.



Cheatsheet

#Start redis
redis-server
#Execute commands
redis-cli <command>
#String:
set mykey somevalue
get mykey
#nx - fail if the key already exists
set mykey newval nx
#xx - set value if the key already exists
set mykey newval xx
#incr - increment
set counter 100
incr counter
incr counter
#incrby - increment by
incrby counter 50
#mset - set multiple values
mset a 10 b 20 c 30
#mget - get multiple values
mget a b c
#exists - 1 = yes, 0 = no
set mykey hello
exists mykey
#del - delete
del mykey
#type - Display data type of key
type mykey
#expire
set key some-value
expire key 5 (expires in 5 seconds)
get key
set key 100 ex 10
#ttl - time remaining before the key expires
ttl key
#List: rpush - bottom, lpush - top, lrange - extract a range of items in the list
rpush mylist A
rpush mylist B
lpush mylist first
lrange mylist 0 -1 (list from zero to last element)
lrange mylist 0 -2 (list from zero to penultimate element i.e. last element minus one)
lrange mylist 0 -3 (list from zero to last element minus two)
#rpop - pop from the right (bottom)
rpop mylist
#ltrim - sets the range of elements as the new list value
ltrim mylist 0 2 (sets the range 0 to 2 as the new value of mylist)
#ltrim - retains only the first 1000 newest elements on the list
ltrim mylist 0 999
##Blocking operations on list - Producer consumer model. Producers call lpush. Consumers call rpop.
##brpop, blpop - return to the caller only when a new element is added to the list or when a user specified timeout is reached.
#Wait for elements in the list 'tasks', but return after 5 seconds if no elements are present
brpop tasks 5
#zero timeout means wait forever
brpop tasks 0
##blocking pop on multiple lists with timeout.
#Wait for multiple lists at the same time and get notified when the first list receives an element.
brpop tasks schedules 10
#Safer queues or rotating queues
rpoplpush (try it)
brpoplpush (try it)
##Hashes
#Create or add to a hash
hmset user:1000 username antirez birthyear 1977 verified 1
#Get single value from hash
hget user:1000 username
#Get all values as a list from hash
hgetall user:1000
#Get multiple values from hash
hmget user:1000 username birthyear no-such-field
#Increment integer value stored in a hash
hincrby user:1000 birthyear 10


##Sets:
#Add new elements to a set
sadd myset 1 2 3

#Return all elements of a set
smembers myset

#Check if an element exists in the set: 0 - no, 1 - yes
sismember myset 2

#Intersection of sets: List all objects with specific tag values
sinter tag:1:news tag:2:news tag:5:news

#Extract a random element from the set
spop myset

#Extract multiple random elements from the set
spop myset 3

#Union of sets
sunionstore set1 set2 set3

#Cardinality of the set: Number of elements in the set
scard myset

#Random element without removing from the set
srandmember myset

#Multiple random elements without removing from the set
srandmember myset 3

##Sorted sets
#Add elements to the sorted set: zadd <score or sort-key> <element>
zadd fruit 50 apples
zadd fruit 20 oranges
zadd fruit 400 bananas
zadd fruit 10 guavas
zadd fruit 5 papayas
zadd fruit 500 berries

#Show all elements in the sorted set in ascending order of score
zrange fruit 0 -1

#Show all elements in the sorted set in descending order of score
zrevrange fruit 0 -1

#Show sorted elements of the set with scores
zrange fruit 0 -1 withscores

#Show sorted elements up to a certain score inclusive: Show all fruit with count up to 20. Should display papayas, guavas and oranges in the order listed.
zrangebyscore fruit -inf 20

#Remove range of elements from the sorted set: Removes papayas, guavas and oranges
zremrangebyscore fruit 5 20

#Rank: Position of an element in the sorted set
zrank fruit apples

#Lexicographical scores
#Show all elements lexicographically starting with specific characters: Shows bananas, berries and oranges
zrangebylex fruit [b [o

#Delete mutliple keys with the same prefix
redis-cli keys prefix:* | xargs redis-cli DEL

Popular posts from this blog

A @trello board to get kids excited

My 8 year old just started his summer break. He did so well in school and I am proud of him. He skipped second grade, got into the gold honor roll in every quarter and got a medal for doing that. Last night, I promised to install a new app for him on his iPad mini. I installed Trello and created a board for him while he watched. I showed him how to create cards, add labels to them and move them from To Do, to Doing to Done. I had him create some cards and label them. He could not stop creating cards. I could not convince him to go to bed after that. He created cards for everything he wants to do in the summer and he is not done with creating cards. He even created a card to email a screenshot of his Trello board to his teacher.

Later last night, he was still awake in bed when I checked on him. He told me that he wanted to add three more labels - Math, Science and One-on-One. He wanted a label titled 'One-on-one' for tasks that he wants to do with me and he wants one-on-one att…

A @trello board to get kids excited - continued

This is a continuation of the previous post titled - A trello board to get kids excited. At the time of writing this post, the previous post had 198 page views. I wish people commented. I did get some positive feedback on Twitter. The Trello twitter account re-tweeted my tweet and also sent out a second tweet advertising the page. Thank you very much. I hope a lot of parents and kids benefited and had fun as a result.

Trello people: Idea - How about a 'Trello Kiddo'? Perhaps you could offer that to schools that give iPads for each kid to take home with them. Get them when they are young.

When a kid does something religiously, regularly and feels great about it and can't wait to tell everyone about it, you know you've done well as a parent. We realized that we needed a separate column to keep track of 'Special accomplishments'. Positive reinforcement that you can see with your eyes!

Some parents feel like they haven't done enough for their kids, particularly…

#Git starter cheat sheet

Initialize a local repo Run the following command in the folder where you would like to initialize a git repo.
git init
Get status It is a good practice to frequently run check on status during development. The following command points out the changes between the previous commit and current state of the folder.
git status
Add content To add an untracked file named ‘text.txt’ to the staging area, execute the following command.
git add text.txt
Syntax: git add <filename>
Commit changes To commit changes made to the folder, execute the following command. The message will be used as a commit message to associate this check-in with the message.
git commit –m “Add text.txt to the code base.”
Syntax: git commit –m “<Commit message>”
Add using wild card To add multiple files using a wild card character, execute the following command.
git add ‘*.txt’
Syntax: git add ‘<wildcard_character+string>’
Check history Review commit history using the following command.
git log
Add Remote re…