27

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?

Siva
  • 1,256
  • 3
  • 13
  • 29

4 Answers4

7

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 
gkamal
  • 20,777
  • 4
  • 60
  • 57
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.

Yang
  • 1,285
  • 1
  • 10
  • 14
1

You can use pipeline to get last inserted keys or specific keys from the Redis Database

Here is my code example :

r = redis.StrictRedis(host='localhost', port= 6379, db =0)
# Day1 hash for 24 hours 
# Key , Field , Value
r.hset("31/8/21", "12am", "/home/user/video1.mp4")
r.hset("31/8/21", "1am", "/home/user/video2.mp4")
r.hset("31/8/21", "2am", "/home/user/video3.mp4")
r.hset("31/8/21", "3am", "/home/user/video4.mp4")
r.hset("31/8/21", "4am", "/home/user/video5.mp4")
.
.
#Created sorted set for all the date hashes into single "date" key
r.sadd("date", "25/8/21")
r.sadd("date", "26/8/21")
r.sadd("date", "27/8/21")
r.sadd("date", "28/8/21")
r.sadd("date", "29/8/21")
r.sadd("date", "30/8/21")
r.sadd("date", "31/8/21")
r.save

@app.get("/lastweek")
def sortweek():
        lastweeklist = r.sort("date", 27, -1, alpha=True) #sorted set key > date
        pipe = r.pipeline()
        for keys in lastweeklist:
                pipe.hgetall(keys) #hvals
        week1 = []
        for week in pipe.execute():
                week1.append(week)
        return week1
Sumathi J
  • 180
  • 1
  • 7
0

Some commands has [LIMIT offset count] wich you can fill and get limited number of items.

like zrevrangebyscore key +inf 0 LIMIT 0 20 which gives you top 20 items of a sorted set.

AminSojoudi
  • 1,904
  • 2
  • 18
  • 42