Redis Compass (The List Datastructure) –Part 5

The redis list data-structure is really interesting, since it’s a linked-list it allows for extremely fast push operations i.e insertion of new elements at the end of the list.

Let’s say you are building the next big social networking app which allows users to perform “like” operations on videos that they of-course like, the user i.e poster of the video can see the various individuals that liked it, this type of data (list of the various individuals) would be a perfect fit for the list data-structure in redis since the most important operation is to enable extremely fast push of new “like data” especially when the video goes viral.

Getting Deeper

We will be examining the various operations that redis provides to enable various manipulation of the list data structure.

LPUSH Operation

The LPUSH operation allows us to add a new element to the left(beginning) of a list i.e the head of the list.  Let’s test it out, fire up your terminal, run:

if you have any error, cross-check with the steps here.  Fire up another terminal and run this:

it should open up a session for you to interface with redis, let’s try out some things

We simply created a list with the key “fruits” and ‘pushed’ apple and orange into it, the next thing is to view the contents of our list which in this case is “fruits”, that brings us to our next redis command;

LRANGE

This particular command takes two values(index), first one being the beginning index and the second being the ‘end’ index.  The indexes can also be a negative value e.g an index of -1 tells redis to start counting from the end, -2 means second to the end and so on.   To view all the values in list “fruits ” we say:

which means start from index 0 up to the last element(-1).

RPUSH

The RPUSH command allows us to add a new element to the end(right side) of a list, so if we have “orange”, “apple”, “peach” if we do this

LPOP & RPOP

Redis has this concept of “pop” which retrieves an element from the list and eliminates it from the list. LPOP retrieves and eliminates from the beginning(left) side of a list while a RPOP retrieves and eliminates from the end(right) side of a list.

Conclusion

That’s it for now, next we’d look at the Hash datastructures.  Have any questions? hit me up through the comments.  Thanks

 

 

One comment on “Redis Compass (The List Datastructure) –Part 5

Leave a Reply

Your email address will not be published. Required fields are marked *