How to get index of latest element in List Redis?

10,225

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 
Share:
10,225

Related videos on Youtube

PiligrimBilim
Author by

PiligrimBilim

Updated on June 04, 2022

Comments

  • PiligrimBilim
    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 get last ID message and return index this element.

  • PiligrimBilim
    PiligrimBilim over 9 years
    Thank you a lot. But is not lear enough for me. For example there is a listMESSAGES: 0 - 101, 1 - 102, 2 - 103. I get last element: LRANGE MESSAGES -1 -1. It is value: 103 How get index 2?
  • jjm
    jjm over 9 years
    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.
  • PiligrimBilim
    PiligrimBilim over 9 years
    It will be $variable = LLEN MESSAGES; $variable = $variable - 1?
  • jjm
    jjm over 9 years
    What language are you using?
  • PiligrimBilim
    PiligrimBilim over 9 years
    I use PHP and library PHPREDIS
  • jjm
    jjm over 9 years
    No experience with that but according to the docs, you can just do something like $lastIndex = $redis->lSize('MESSAGES') - 1;
  • PiligrimBilim
    PiligrimBilim over 9 years
    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
    PiligrimBilim over 9 years
    I think it will be: LRANGE MESSAGES _lastIndex - 1 How do you think?
  • jjm
    jjm over 9 years
    Try it and find out :-)