Home > redis > Getting last N element(s) from a list in redis

Getting last N element(s) from a list in redis

Somehow I couldn’t find anywhere on how to achieve this: getting the last N elements from a list in redis, not even on Redis command docs. Well I just figured out the easiest way, say to get last 3 elements from list users:

redis 127.0.0.1:6379> rpush users tom
(integer) 1
redis 127.0.0.1:6379> rpush users ray
(integer) 2
redis 127.0.0.1:6379> rpush users coolguy
(integer) 3
redis 127.0.0.1:6379> rpush users bob
(integer) 4
redis 127.0.0.1:6379> rpush users alice
(integer) 5
redis 127.0.0.1:6379> lrange users -3 -1
1) "coolguy"
2) "bob"
3) "alice"
redis 127.0.0.1:6379> 

Just a couple of things worth noting:

  • start should always to be no larger than end in command lrange list_name start end
  • so the formula to get last N elements from a list is lrange list_name -N -1 where N>=1
Advertisements
Categories: redis
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: