Search code examples
phpredispredis

How to use dates as scores in a redis sorted set in PHP?


I have a dynamic array of tasks objects with reminder dates.

I have an idea to use a redis sorted set to implement a reminders "sorted" queue. The idea is to add tasks' reminder dates to a redis sorted set and periodically run checking if there are reminders in the set relevant to checking date/time(the current date/time for example).

My tool for operating redis is the Predis client. I put reminders in the set in the following way:

$redis->zadd('reminders', [strtotime($task->reminder_at) => $task->id]);  

To retreive the reminders that earlier than the current timestamp, I try to get them in the following way:

$currentTime = time();
$reminders = $redis->zrangebyscore('reminders', '-inf', $currentTime, ['withscores' => true]); 

But I get all the reminders, no matter if they are earlier than the current timestamp or not. I think it is maybe because of not correct comparison, but I can't understand why does it happen. Is is possible at all to use timestamps as scores in this case? I would like to get all the reminders, that are earlier or equal to the current timestamp(Or DateTime. No matter). What is wrong with my way of using a sorted set?


Solution

  • I am not a Redis expert/developer but the base idea is usually search works with array values

    You are trying to search based on the timestamp into the array but that array contains timestamps as keys, not values. So your code is not working

    Reverse the order and it will start working

    $redis->zadd('reminders', [$task->id => strtotime($task->reminder_at)]);