Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index of latest element in List Redis?

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.

like image 293
PiligrimBilim Avatar asked Jan 05 '15 20:01

PiligrimBilim


2 Answers

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.

like image 153
jjm Avatar answered Oct 26 '22 21:10

jjm


To get the last element you can also use:

lrange mylist -1 -1 
like image 22
AlwaysLearner Avatar answered Oct 26 '22 20:10

AlwaysLearner