How would you get the last 10 keys redis?

20,986

Solution 1

You will need to maintain it as another list using the following commands.

Add new key to the front of the list  
LPUSH last10keys key

Retain only the last 10
LTRIM last10keys 0 9

Get the last keys - will return 10 or less
LRANGE mylist 0 9 

Solution 2

As a workaround if I don't want to change anything in the cache, I tail the AOF file to see what's the latest change there.

tail -f /var/lib/redis/appendonly.aof

From there, you can see the key, value and command used.

Share:
20,986

Related videos on Youtube

Siva
Author by

Siva

Updated on July 09, 2022

Comments

  • Siva
    Siva almost 2 years

    Let's say I have a database with 1,000,000 keys. Is there a way to know the last 10 keys from that database?

    • Tommaso Barbugli
      Tommaso Barbugli about 11 years
      nope, you have to implement it yourself
    • Siva
      Siva about 11 years
      And how would you go about doing this?
    • Tommaso Barbugli
      Tommaso Barbugli about 11 years
      you can store keys in a list or in a sorted set
    • Siva
      Siva about 11 years
      I see. So I would need make a list that stores all the available keys?
    • Tommaso Barbugli
      Tommaso Barbugli about 11 years
      well depending on the space you want to invest with this.I would keep the size of this list to a fixed length
    • Siva
      Siva about 11 years
      Would there be a way to even get the last key in the database?
    • Eli
      Eli about 11 years
      @Sivapriyan can you tell us more about what you need the last 10 keys in particular for? Maybe we can recommend a workaround. As Tommaso Barbugli said, to do what you want, you'd need to use a secondary structure like a list or a sorted set (slower) to get at the last n keys.
    • akonsu
      akonsu about 11 years
      what is "last" in "the last 10 keys"?
  • Zitrax
    Zitrax over 9 years
    This requires appendonly to be set to yes in the config file. That is not the default.