How to get index of latest element in List Redis?
Solution 1
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.
Solution 2
To get the last element you can also use:
lrange mylist -1 -1
Related videos on Youtube
PiligrimBilim
Updated on June 04, 2022Comments
-
PiligrimBilim almost 2 years
How to get index of latest element in List Redis? For example in
List
is stored id's of messages, I need getlast ID
message and returnindex
this element. -
PiligrimBilim over 9 yearsThank you a lot. But is not lear enough for me. For example there is a list
MESSAGES
:0 - 101, 1 - 102, 2 - 103
. I get last element:LRANGE MESSAGES -1 -1
. It is value:103
How get index2
? -
jjm over 9 yearsIf you actually want the last index, rather than the last element, you can just use LLEN and subtract one from the result. Note that this might not be the last index for long if other processes or threads are accessing your Redis instance.
-
PiligrimBilim over 9 yearsIt will be
$variable = LLEN MESSAGES; $variable = $variable - 1
? -
jjm over 9 yearsWhat language are you using?
-
PiligrimBilim over 9 yearsI use PHP and library
PHPREDIS
-
jjm over 9 yearsNo experience with that but according to the docs, you can just do something like
$lastIndex = $redis->lSize('MESSAGES') - 1;
-
PiligrimBilim over 9 yearsGood, so if then I want to get elements from LIST from this last index and up, how will be? Fox example:
1, 2, 3, 4, 5
. I get last index3
and after added4, 5
element. Then I need get latest elements from 3 these are:4, 5
-
PiligrimBilim over 9 yearsI think it will be:
LRANGE MESSAGES _lastIndex - 1
How do you think? -
jjm over 9 yearsTry it and find out :-)