Search code examples
ruby-on-railsrubyredisredis-cli

Fetch keys which are older than 10 days from redis


I am trying to fetch the keys from Redis which are older than 10 days. I am using Zrange to fetch the old keys which are saved based on timestamp. I am getting this error when I run the last command ERR value is not an integer or out of range.Any help is appreciated or can someone guide me if I am doing wrong way

These are the values/timestamp I have used while adding in redis

Time.current.to_i => 1676960645
(Time.current - 3.days).to_i => 1676701452
(Time.current - 13.days).to_i => 1675837471
(Time.current - 10.days).to_i => 1676096682

redis-cli
127.0.0.1:6379> ZADD myzset 1676960645 "current"
(integer) 1
127.0.0.1:6379> ZADD myzset 1676701452 "3 days ago"
(integer) 1
127.0.0.1:6379> ZADD myzset 1675837471 "13 days ago"
(integer) 1
127.0.0.1:6379> ZRANGE myzset )1676096682 1676960645
(error) ERR value is not an integer or out of range
127.0.0.1:6379> 

Version:

redis-cli -v
redis-cli 4.0.9

As per Guy Royse comments, I have updated the Redis to 7.0.8 and I still getting the same error

redis-server --version
Redis server v=7.0.8 sha=00000000:0 malloc=jemalloc-5.2.1 bits=64 build=c255d0976966edae
aniket@Linuxbeta:~$ redis-cli --version
redis-cli 7.0.8




    127.0.0.1:6379> ZADD myzset 1676960645 "current"
(integer) 1
127.0.0.1:6379> ZADD myzset 1676701452 "3 days ago"
(integer) 1
127.0.0.1:6379> ZADD myzset 1675837471 "13 days ago"
(integer) 1
127.0.0.1:6379> ZRANGE myzset (1676096682 1676960645 BYSCORE
(error) ERR value is not an integer or out of range

Solution

  • By default Sorted Set ranges are specified using the index of the members. The lowest score is 0, the next lowest is 1, etc. In this scenario, exclusion is neither needed nor permitted. To execute exclusively, you just use the index you actually want.

    What you are doing is asking for a range based on the score. With exclusivity. There are two problems with how this is being done:

    1. You need to tell Redis that you are not looking for a range by index but instead by score. You do this using the BYSCORE option on ZRANGE.

    2. You need to use a left parenthesis to specify exclusion, not a right one.

    The command you want is:

    127.0.0.1:6379> ZRANGE myzset (1676096682 1676960645 BYSCORE
    1) "3 days ago"
    2) "current"
    

    Hope this helps.