Extending Redis key-value functionality
After some study of the Redis repository ( version 1.01 ) for use in a highly loaded project, the impressions remain good. But personally, I did not have one simple command - counting the number of keys by a pattern. Those. there is KEYS , but it returns an array with all the keys. That, you see, with sizes of the order of hundreds of millions of records, the server will make you think for a long time. If he has enough resources for this.
Digging a bit in the source, a new COUNT command was introduced, which returns the number of records by pattern.
diff redis.c diff redis-cli.c diff redis.py Enjoy! ;-)
Digging a bit in the source, a new COUNT command was introduced, which returns the number of records by pattern.
diff redis.c diff redis-cli.c diff redis.py Enjoy! ;-)
352a353
> static void countCommand(redisClient *c);
441a443
> {"count",countCommand,2,REDIS_CMD_INLINE},
755c757
< if (!(loops % 5)) {
---
> if (!(loops % 30)) {
2502a2505,2528
> static void countCommand(redisClient *c) {
> dictIterator *di;
> dictEntry *de;
> sds pattern = c->argv[1]->ptr;
> int plen = sdslen(pattern);
> int numkeys = 0;
>
> di = dictGetIterator(c->db->dict);
> if (!di) oom("dictGetIterator");
> while((de = dictNext(di)) != NULL) {
> robj *keyobj = dictGetEntryKey(de);
>
> sds key = keyobj->ptr;
> if ((pattern[0] == '*' && pattern[1] == '\0') ||
> stringmatchlen(pattern,plen,key,sdslen(key),0)) {
> if (expireIfNeeded(c->db,keyobj) == 0) {
> numkeys++;
> }
> }
> }
> dictReleaseIterator(di);
> addReplySds(c, sdscatprintf(sdsempty(),":%lu\r\n", numkeys));
> }
>
98a99
> {"count",2,REDIS_CMD_INLINE},
301a302,306
> def count(self, pattern):
> self.connect()
> self._write('COUNT %s\r\n' % pattern)
> return self.get_response()
>