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?
Asked
Active
Viewed 2.8k times
27
-
nope, you have to implement it yourself – Tommaso Barbugli May 15 '13 at 19:51
-
And how would you go about doing this? – Siva May 15 '13 at 19:52
-
you can store keys in a list or in a sorted set – Tommaso Barbugli May 15 '13 at 19:53
-
I see. So I would need make a list that stores all the available keys? – Siva May 15 '13 at 19:57
-
well depending on the space you want to invest with this.I would keep the size of this list to a fixed length – Tommaso Barbugli May 15 '13 at 19:58
-
Would there be a way to even get the last key in the database? – Siva May 15 '13 at 20:00
-
@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. – Eli May 15 '13 at 20:48
-
1what is "last" in "the last 10 keys"? – akonsu May 16 '13 at 04:01
4 Answers
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
-
1This requires appendonly to be set to yes in the config file. That is not the default. – Zitrax Oct 13 '14 at 08:22
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