How get last data from sorted set?
Asked Answered
L

3

5

I saw a Redis tutorial. For my case there is a function: ZREVRANGEBYSCORE But I dont understand how get last one data via this function.

I tried ZREVRANGEBYSCORE myzset 0 1 for get last data row

Lynnell answered 11/11, 2014 at 20:20 Comment(0)
R
8

Assuming "last data" means the item with the largest score, use the ZREVRANGEBYSCORE command in the following manner:

ZREVRANGEBYSCORE <key> +inf -inf LIMIT 0 1
Ruiz answered 11/11, 2014 at 20:26 Comment(3)
Thank you, If I want use LIMIT, but that return all data, how be? LIMIT 0 -1?Lynnell
@AhmedFaud: That appears to work, or you could drop the LIMIT clause entirely (i.e. ZREVRANGEBYSCORE <key> +inf -inf).Ruiz
I want use LIMIT, but get all data, I can drop :)Lynnell
A
0

how about ZREVRANGEBYSCORE myzset 0 0?

redis> zadd score 100 Kenny 100 May 20 Mary 100 Doe 50 Foo
(integer) 5

redis> zrevrange score 0 0
1) "William"

redis> zrevrangebyscore score +inf -inf
1) "William"
2) "May"
3) "Kenny"
4) "Doe"
5) "Mary"

redis> zrevrangebyscore score +inf -inf withscores
 1) "William"
 2) "100"
 3) "May"
 4) "100"
 5) "Kenny"
 6) "100"
 7) "Doe"
 8) "100"
 9) "Mary"
10) "20"
Averir answered 9/7, 2021 at 10:14 Comment(0)
T
-1

My example on Node.js. Get last 5 elements from sorted set.

redis.zadd('key1', 0, 'val0');
redis.zadd('key1', 2, 'val2');
redis.zadd('key1', 3, 'val3');
redis.zadd('key1', 4, 'val4');
redis.zadd('key1', 6, 'val6');
redis.zadd('key1', 8, 'val8');
redis.zadd('key1', 11, 'val11');
redis.zadd('key1', 21, 'val21');

setTimeout(() => {

    redis.zrange('key1', -5, -1, (error, result) => {
        console.log('result:', result);
    });

}, 1000);
Tillman answered 14/5, 2021 at 14:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.