📜 ⬆️ ⬇️

We expand the functionality of the key-value store Redis

After some study of the Redis repository ( version 1.01 ) for use in a high-load project, the impressions remain good. But personally, I did not have one simple command - counting the number of keys by the pattern. Those. there are KEYS , but it returns an array with all the keys. That, you see, the size of the order of hundreds of millions of records will make the server think for a long time. If he has enough resources for that.

Having a little rummaged in the source code, a new COUNT command was introduced, which returns the number of entries on the pattern.

diff redis.c
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));
> }
>

')
diff redis-cli.c

98a99
> {"count",2,REDIS_CMD_INLINE},


diff redis.py

301a302,306
> def count(self, pattern):
> self.connect()
> self._write('COUNT %s\r\n' % pattern)
> return self.get_response()
>


Enjoy! ;-)

Source: https://habr.com/ru/post/72193/


All Articles