How to get index of latest element in List Redis?

PiligrimBilim picture PiligrimBilim · Jan 5, 2015 · Viewed 8k times · Source

How to get index of latest element in List Redis? For example in List is stored id's of messages, I need get last ID message and return index this element.

Answer

jjm picture jjm · Jan 5, 2015

In Redis, the index -1 always refers to the last element in a LIST

This is a much better idea that trying to find the index from the start of the list (LLEN would be the way to get this), because if someone inserts or removes an item after you get the index but before you access the element, something's gonna break.

To get the last element of a Redis list, you can use the LINDEX key -1 command. You can also atomically remove the last element of a list with the LPOP key command.

Documentation for all of the Redis commands can be found at http://redis.io/commands.