9

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.

PiligrimBilim
  • 107
  • 1
  • 1
  • 4

2 Answers2

11

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.

jjm
  • 6,028
  • 2
  • 24
  • 27
  • Thank 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 index `2`? – PiligrimBilim Jan 05 '15 at 22:14
  • 1
    If 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. – jjm Jan 05 '15 at 22:17
  • It will be `$variable = LLEN MESSAGES; $variable = $variable - 1`? – PiligrimBilim Jan 05 '15 at 22:27
  • What language are you using? – jjm Jan 05 '15 at 22:30
  • I use PHP and library `PHPREDIS` – PiligrimBilim Jan 05 '15 at 22:40
  • No experience with that but according to the docs, you can just do something like `$lastIndex = $redis->lSize('MESSAGES') - 1;` – jjm Jan 05 '15 at 22:44
  • Good, 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 index `3` and after added `4, 5` element. Then I need get latest elements from 3 these are: `4, 5` – PiligrimBilim Jan 05 '15 at 22:52
  • I think it will be: `LRANGE MESSAGES _lastIndex - 1` How do you think? – PiligrimBilim Jan 05 '15 at 23:00
  • Try it and find out :-) – jjm Jan 05 '15 at 23:03
4

To get the last element you can also use:

lrange mylist -1 -1 
AlwaysLearner
  • 443
  • 5
  • 8