Redis: How is the result of KEYS * sorted?
Asked Answered
I

1

6

I have a very simple php redis application which creates keys at certain events. All the keys are just counters and have an expire time of 24 hours. Basically a rolling window of 24 hours for every key to gather some statistics.

if ($redis->exists($key)) {
    $redis->incr($key); 
}
else {
    $redis->set($key, '1');
    $now = time(); // current timestamp
    $redis->expireAt($key, $now + 86400);
}

When I extract an overview of all my keys with $list = $redis->keys("*"); (or in a redis-cli console with keys *), I would suspect a chronological order by creation date. However this is not case. Neither are they ordered alphabetically, by value...

So my question is, how is this list sorted?

Intern answered 27/4, 2017 at 8:37 Comment(0)
S
12

First of all, don't use keys * it is debug function not designed for a production, you can kill your server... If you need enumerate all keys in DB in safe way, use SCAN function with LIMIT.

Anyway results of keys or scan is not sorted in any manner, order of results related to internal memory structure of redis's hashtable.

About your php script, you can do it by a single command, without exists set expireat just run:

SET key 1 EX 86400 NX

EX 86400 mean expire in 86400 (1 day) seconds from now

NX mean create a key only if it doesn't exists.

If this command return (nil) run regular INCR key its mean that the key already exists. BTW INCR command will not remove your expire settings.

Sundry answered 27/4, 2017 at 10:42 Comment(6)
An almost perfect reply - uproots an evil pattern, provides the answer to the question, and and teaches proper Redis - would have upvoted twice if I could. A final pseudo PHP example of what you've described would have made it perfect ;pAlcaide
Hi Itamar, have no idea what client he is using :) BTW It would be nice to have a cup of coffee on occasion in northern Tel Aviv. We are neighbours =)Sundry
Fair point about the client. I'd be happy to do it && pick the tab (assuming no dessert, naturally) - contact me and we'll make it happen.Alcaide
@Sundry I will get all the fields corresponding to the keyname with the command hkeys keyname, so are these fields sorted?What are the fields sorted by?Planula
@Planula Basically, all of the above applies to HSET, you have HSCAN which you will use if you a big HSET. Under the hood, the small HSETs are stored in memory as zip-list, so you will get the keys in the same order as you added them. But after passing the threshold of hash-max-ziplist-value 512 or hash-max-ziplist-entries 64 HSET will be converted to a real hash table, and then the keys will be returned to you in random order. More info: redis.com/ebook/part-2-core-concepts/…Sundry
I think you mean using SCAN function with COUNT instead of LIMIT.Chariness

© 2022 - 2024 — McMap. All rights reserved.