]> git.saurik.com Git - redis.git/blame - src/t_zset.c
When REDIS_CLOSE_AFTER_REPLY is set, there may never be new replies
[redis.git] / src / t_zset.c
CommitLineData
e2641e09 1#include "redis.h"
2
3#include <math.h>
4
5/*-----------------------------------------------------------------------------
6 * Sorted set API
7 *----------------------------------------------------------------------------*/
8
9/* ZSETs are ordered sets using two data structures to hold the same elements
10 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
11 * data structure.
12 *
13 * The elements are added to an hash table mapping Redis objects to scores.
14 * At the same time the elements are added to a skip list mapping scores
15 * to Redis objects (so objects are sorted by scores in this "view"). */
16
17/* This skiplist implementation is almost a C translation of the original
18 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
19 * Alternative to Balanced Trees", modified in three ways:
20 * a) this implementation allows for repeated values.
21 * b) the comparison is not just by key (our 'score') but by satellite data.
22 * c) there is a back pointer, so it's a doubly linked list with the back
23 * pointers being only at "level 1". This allows to traverse the list
24 * from tail to head, useful for ZREVRANGE. */
25
26zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
2159782b 27 zskiplistNode *zn = zmalloc(sizeof(*zn)+level*sizeof(struct zskiplistLevel));
e2641e09 28 zn->score = score;
29 zn->obj = obj;
30 return zn;
31}
32
33zskiplist *zslCreate(void) {
34 int j;
35 zskiplist *zsl;
36
37 zsl = zmalloc(sizeof(*zsl));
38 zsl->level = 1;
39 zsl->length = 0;
40 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
41 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
2159782b
PN
42 zsl->header->level[j].forward = NULL;
43 zsl->header->level[j].span = 0;
e2641e09 44 }
45 zsl->header->backward = NULL;
46 zsl->tail = NULL;
47 return zsl;
48}
49
50void zslFreeNode(zskiplistNode *node) {
51 decrRefCount(node->obj);
e2641e09 52 zfree(node);
53}
54
55void zslFree(zskiplist *zsl) {
2159782b 56 zskiplistNode *node = zsl->header->level[0].forward, *next;
e2641e09 57
e2641e09 58 zfree(zsl->header);
59 while(node) {
2159782b 60 next = node->level[0].forward;
e2641e09 61 zslFreeNode(node);
62 node = next;
63 }
64 zfree(zsl);
65}
66
67int zslRandomLevel(void) {
68 int level = 1;
69 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
70 level += 1;
71 return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
72}
73
69ef89f2 74zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj) {
e2641e09 75 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
76 unsigned int rank[ZSKIPLIST_MAXLEVEL];
77 int i, level;
78
79 x = zsl->header;
80 for (i = zsl->level-1; i >= 0; i--) {
81 /* store rank that is crossed to reach the insert position */
82 rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
2159782b
PN
83 while (x->level[i].forward &&
84 (x->level[i].forward->score < score ||
85 (x->level[i].forward->score == score &&
86 compareStringObjects(x->level[i].forward->obj,obj) < 0))) {
87 rank[i] += x->level[i].span;
88 x = x->level[i].forward;
e2641e09 89 }
90 update[i] = x;
91 }
92 /* we assume the key is not already inside, since we allow duplicated
93 * scores, and the re-insertion of score and redis object should never
94 * happpen since the caller of zslInsert() should test in the hash table
95 * if the element is already inside or not. */
96 level = zslRandomLevel();
97 if (level > zsl->level) {
98 for (i = zsl->level; i < level; i++) {
99 rank[i] = 0;
100 update[i] = zsl->header;
2159782b 101 update[i]->level[i].span = zsl->length;
e2641e09 102 }
103 zsl->level = level;
104 }
105 x = zslCreateNode(level,score,obj);
106 for (i = 0; i < level; i++) {
2159782b
PN
107 x->level[i].forward = update[i]->level[i].forward;
108 update[i]->level[i].forward = x;
e2641e09 109
110 /* update span covered by update[i] as x is inserted here */
2159782b
PN
111 x->level[i].span = update[i]->level[i].span - (rank[0] - rank[i]);
112 update[i]->level[i].span = (rank[0] - rank[i]) + 1;
e2641e09 113 }
114
115 /* increment span for untouched levels */
116 for (i = level; i < zsl->level; i++) {
2159782b 117 update[i]->level[i].span++;
e2641e09 118 }
119
120 x->backward = (update[0] == zsl->header) ? NULL : update[0];
2159782b
PN
121 if (x->level[0].forward)
122 x->level[0].forward->backward = x;
e2641e09 123 else
124 zsl->tail = x;
125 zsl->length++;
69ef89f2 126 return x;
e2641e09 127}
128
129/* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
130void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
131 int i;
132 for (i = 0; i < zsl->level; i++) {
2159782b
PN
133 if (update[i]->level[i].forward == x) {
134 update[i]->level[i].span += x->level[i].span - 1;
135 update[i]->level[i].forward = x->level[i].forward;
e2641e09 136 } else {
2159782b 137 update[i]->level[i].span -= 1;
e2641e09 138 }
139 }
2159782b
PN
140 if (x->level[0].forward) {
141 x->level[0].forward->backward = x->backward;
e2641e09 142 } else {
143 zsl->tail = x->backward;
144 }
2159782b 145 while(zsl->level > 1 && zsl->header->level[zsl->level-1].forward == NULL)
e2641e09 146 zsl->level--;
147 zsl->length--;
148}
149
150/* Delete an element with matching score/object from the skiplist. */
151int zslDelete(zskiplist *zsl, double score, robj *obj) {
152 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
153 int i;
154
155 x = zsl->header;
156 for (i = zsl->level-1; i >= 0; i--) {
2159782b
PN
157 while (x->level[i].forward &&
158 (x->level[i].forward->score < score ||
159 (x->level[i].forward->score == score &&
160 compareStringObjects(x->level[i].forward->obj,obj) < 0)))
161 x = x->level[i].forward;
e2641e09 162 update[i] = x;
163 }
164 /* We may have multiple elements with the same score, what we need
165 * is to find the element with both the right score and object. */
2159782b 166 x = x->level[0].forward;
e2641e09 167 if (x && score == x->score && equalStringObjects(x->obj,obj)) {
168 zslDeleteNode(zsl, x, update);
169 zslFreeNode(x);
170 return 1;
171 } else {
172 return 0; /* not found */
173 }
174 return 0; /* not found */
175}
176
177/* Delete all the elements with score between min and max from the skiplist.
178 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
179 * Note that this function takes the reference to the hash table view of the
180 * sorted set, in order to remove the elements from the hash table too. */
181unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) {
182 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
183 unsigned long removed = 0;
184 int i;
185
186 x = zsl->header;
187 for (i = zsl->level-1; i >= 0; i--) {
2159782b
PN
188 while (x->level[i].forward && x->level[i].forward->score < min)
189 x = x->level[i].forward;
e2641e09 190 update[i] = x;
191 }
192 /* We may have multiple elements with the same score, what we need
193 * is to find the element with both the right score and object. */
2159782b 194 x = x->level[0].forward;
e2641e09 195 while (x && x->score <= max) {
2159782b 196 zskiplistNode *next = x->level[0].forward;
69ef89f2 197 zslDeleteNode(zsl,x,update);
e2641e09 198 dictDelete(dict,x->obj);
199 zslFreeNode(x);
200 removed++;
201 x = next;
202 }
203 return removed; /* not found */
204}
205
206/* Delete all the elements with rank between start and end from the skiplist.
207 * Start and end are inclusive. Note that start and end need to be 1-based */
208unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
209 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
210 unsigned long traversed = 0, removed = 0;
211 int i;
212
213 x = zsl->header;
214 for (i = zsl->level-1; i >= 0; i--) {
2159782b
PN
215 while (x->level[i].forward && (traversed + x->level[i].span) < start) {
216 traversed += x->level[i].span;
217 x = x->level[i].forward;
e2641e09 218 }
219 update[i] = x;
220 }
221
222 traversed++;
2159782b 223 x = x->level[0].forward;
e2641e09 224 while (x && traversed <= end) {
2159782b 225 zskiplistNode *next = x->level[0].forward;
69ef89f2 226 zslDeleteNode(zsl,x,update);
e2641e09 227 dictDelete(dict,x->obj);
228 zslFreeNode(x);
229 removed++;
230 traversed++;
231 x = next;
232 }
233 return removed;
234}
235
236/* Find the first node having a score equal or greater than the specified one.
237 * Returns NULL if there is no match. */
238zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
239 zskiplistNode *x;
240 int i;
241
242 x = zsl->header;
243 for (i = zsl->level-1; i >= 0; i--) {
2159782b
PN
244 while (x->level[i].forward && x->level[i].forward->score < score)
245 x = x->level[i].forward;
e2641e09 246 }
247 /* We may have multiple elements with the same score, what we need
248 * is to find the element with both the right score and object. */
2159782b 249 return x->level[0].forward;
e2641e09 250}
251
252/* Find the rank for an element by both score and key.
253 * Returns 0 when the element cannot be found, rank otherwise.
254 * Note that the rank is 1-based due to the span of zsl->header to the
255 * first element. */
256unsigned long zslistTypeGetRank(zskiplist *zsl, double score, robj *o) {
257 zskiplistNode *x;
258 unsigned long rank = 0;
259 int i;
260
261 x = zsl->header;
262 for (i = zsl->level-1; i >= 0; i--) {
2159782b
PN
263 while (x->level[i].forward &&
264 (x->level[i].forward->score < score ||
265 (x->level[i].forward->score == score &&
266 compareStringObjects(x->level[i].forward->obj,o) <= 0))) {
267 rank += x->level[i].span;
268 x = x->level[i].forward;
e2641e09 269 }
270
271 /* x might be equal to zsl->header, so test if obj is non-NULL */
272 if (x->obj && equalStringObjects(x->obj,o)) {
273 return rank;
274 }
275 }
276 return 0;
277}
278
279/* Finds an element by its rank. The rank argument needs to be 1-based. */
280zskiplistNode* zslistTypeGetElementByRank(zskiplist *zsl, unsigned long rank) {
281 zskiplistNode *x;
282 unsigned long traversed = 0;
283 int i;
284
285 x = zsl->header;
286 for (i = zsl->level-1; i >= 0; i--) {
2159782b 287 while (x->level[i].forward && (traversed + x->level[i].span) <= rank)
e2641e09 288 {
2159782b
PN
289 traversed += x->level[i].span;
290 x = x->level[i].forward;
e2641e09 291 }
292 if (traversed == rank) {
293 return x;
294 }
295 }
296 return NULL;
297}
298
299/*-----------------------------------------------------------------------------
300 * Sorted set commands
301 *----------------------------------------------------------------------------*/
302
69ef89f2
PN
303/* This generic command implements both ZADD and ZINCRBY. */
304void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double score, int incr) {
e2641e09 305 robj *zsetobj;
306 zset *zs;
69ef89f2 307 zskiplistNode *znode;
e2641e09 308
e2641e09 309 zsetobj = lookupKeyWrite(c->db,key);
310 if (zsetobj == NULL) {
311 zsetobj = createZsetObject();
312 dbAdd(c->db,key,zsetobj);
313 } else {
314 if (zsetobj->type != REDIS_ZSET) {
315 addReply(c,shared.wrongtypeerr);
316 return;
317 }
318 }
319 zs = zsetobj->ptr;
320
69ef89f2
PN
321 /* Since both ZADD and ZINCRBY are implemented here, we need to increment
322 * the score first by the current score if ZINCRBY is called. */
323 if (incr) {
e2641e09 324 /* Read the old score. If the element was not present starts from 0 */
69ef89f2
PN
325 dictEntry *de = dictFind(zs->dict,ele);
326 if (de != NULL)
327 score += *(double*)dictGetEntryVal(de);
328
329 if (isnan(score)) {
beb7756d 330 addReplyError(c,"resulting score is not a number (NaN)");
e2641e09 331 /* Note that we don't need to check if the zset may be empty and
332 * should be removed here, as we can only obtain Nan as score if
333 * there was already an element in the sorted set. */
334 return;
335 }
e2641e09 336 }
337
69ef89f2
PN
338 /* We need to remove and re-insert the element when it was already present
339 * in the dictionary, to update the skiplist. Note that we delay adding a
340 * pointer to the score because we want to reference the score in the
341 * skiplist node. */
342 if (dictAdd(zs->dict,ele,NULL) == DICT_OK) {
343 dictEntry *de;
344
345 /* New element */
e2641e09 346 incrRefCount(ele); /* added to hash */
69ef89f2 347 znode = zslInsert(zs->zsl,score,ele);
e2641e09 348 incrRefCount(ele); /* added to skiplist */
69ef89f2
PN
349
350 /* Update the score in the dict entry */
351 de = dictFind(zs->dict,ele);
352 redisAssert(de != NULL);
353 dictGetEntryVal(de) = &znode->score;
5b4bff9c 354 touchWatchedKey(c->db,c->argv[1]);
e2641e09 355 server.dirty++;
69ef89f2
PN
356 if (incr)
357 addReplyDouble(c,score);
e2641e09 358 else
359 addReply(c,shared.cone);
360 } else {
361 dictEntry *de;
69ef89f2
PN
362 robj *curobj;
363 double *curscore;
364 int deleted;
e2641e09 365
69ef89f2 366 /* Update score */
e2641e09 367 de = dictFind(zs->dict,ele);
368 redisAssert(de != NULL);
69ef89f2
PN
369 curobj = dictGetEntryKey(de);
370 curscore = dictGetEntryVal(de);
e2641e09 371
69ef89f2
PN
372 /* When the score is updated, reuse the existing string object to
373 * prevent extra alloc/dealloc of strings on ZINCRBY. */
374 if (score != *curscore) {
375 deleted = zslDelete(zs->zsl,*curscore,curobj);
e2641e09 376 redisAssert(deleted != 0);
69ef89f2
PN
377 znode = zslInsert(zs->zsl,score,curobj);
378 incrRefCount(curobj);
379
380 /* Update the score in the current dict entry */
381 dictGetEntryVal(de) = &znode->score;
5b4bff9c 382 touchWatchedKey(c->db,c->argv[1]);
e2641e09 383 server.dirty++;
e2641e09 384 }
69ef89f2
PN
385 if (incr)
386 addReplyDouble(c,score);
e2641e09 387 else
388 addReply(c,shared.czero);
389 }
390}
391
392void zaddCommand(redisClient *c) {
393 double scoreval;
673e1fb7 394 if (getDoubleFromObjectOrReply(c,c->argv[2],&scoreval,NULL) != REDIS_OK) return;
75b41de8 395 c->argv[3] = tryObjectEncoding(c->argv[3]);
e2641e09 396 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
397}
398
399void zincrbyCommand(redisClient *c) {
400 double scoreval;
673e1fb7 401 if (getDoubleFromObjectOrReply(c,c->argv[2],&scoreval,NULL) != REDIS_OK) return;
75b41de8 402 c->argv[3] = tryObjectEncoding(c->argv[3]);
e2641e09 403 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
404}
405
406void zremCommand(redisClient *c) {
407 robj *zsetobj;
408 zset *zs;
409 dictEntry *de;
69ef89f2 410 double curscore;
e2641e09 411 int deleted;
412
413 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
414 checkType(c,zsetobj,REDIS_ZSET)) return;
415
416 zs = zsetobj->ptr;
75b41de8 417 c->argv[2] = tryObjectEncoding(c->argv[2]);
e2641e09 418 de = dictFind(zs->dict,c->argv[2]);
419 if (de == NULL) {
420 addReply(c,shared.czero);
421 return;
422 }
423 /* Delete from the skiplist */
69ef89f2
PN
424 curscore = *(double*)dictGetEntryVal(de);
425 deleted = zslDelete(zs->zsl,curscore,c->argv[2]);
e2641e09 426 redisAssert(deleted != 0);
427
428 /* Delete from the hash table */
429 dictDelete(zs->dict,c->argv[2]);
430 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
431 if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
5b4bff9c 432 touchWatchedKey(c->db,c->argv[1]);
e2641e09 433 server.dirty++;
434 addReply(c,shared.cone);
435}
436
437void zremrangebyscoreCommand(redisClient *c) {
438 double min;
439 double max;
440 long deleted;
441 robj *zsetobj;
442 zset *zs;
443
444 if ((getDoubleFromObjectOrReply(c, c->argv[2], &min, NULL) != REDIS_OK) ||
445 (getDoubleFromObjectOrReply(c, c->argv[3], &max, NULL) != REDIS_OK)) return;
446
447 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
448 checkType(c,zsetobj,REDIS_ZSET)) return;
449
450 zs = zsetobj->ptr;
451 deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict);
452 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
453 if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
5b4bff9c 454 if (deleted) touchWatchedKey(c->db,c->argv[1]);
e2641e09 455 server.dirty += deleted;
456 addReplyLongLong(c,deleted);
457}
458
459void zremrangebyrankCommand(redisClient *c) {
460 long start;
461 long end;
462 int llen;
463 long deleted;
464 robj *zsetobj;
465 zset *zs;
466
467 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
468 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
469
470 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
471 checkType(c,zsetobj,REDIS_ZSET)) return;
472 zs = zsetobj->ptr;
473 llen = zs->zsl->length;
474
475 /* convert negative indexes */
476 if (start < 0) start = llen+start;
477 if (end < 0) end = llen+end;
478 if (start < 0) start = 0;
e2641e09 479
d0a4e24e
PN
480 /* Invariant: start >= 0, so this test will be true when end < 0.
481 * The range is empty when start > end or start >= length. */
e2641e09 482 if (start > end || start >= llen) {
483 addReply(c,shared.czero);
484 return;
485 }
486 if (end >= llen) end = llen-1;
487
488 /* increment start and end because zsl*Rank functions
489 * use 1-based rank */
490 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
491 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
492 if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
5b4bff9c 493 if (deleted) touchWatchedKey(c->db,c->argv[1]);
e2641e09 494 server.dirty += deleted;
495 addReplyLongLong(c, deleted);
496}
497
498typedef struct {
499 dict *dict;
500 double weight;
501} zsetopsrc;
502
503int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
504 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
505 unsigned long size1, size2;
506 size1 = d1->dict ? dictSize(d1->dict) : 0;
507 size2 = d2->dict ? dictSize(d2->dict) : 0;
508 return size1 - size2;
509}
510
511#define REDIS_AGGR_SUM 1
512#define REDIS_AGGR_MIN 2
513#define REDIS_AGGR_MAX 3
514#define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
515
516inline static void zunionInterAggregate(double *target, double val, int aggregate) {
517 if (aggregate == REDIS_AGGR_SUM) {
518 *target = *target + val;
d9e28bcf
PN
519 /* The result of adding two doubles is NaN when one variable
520 * is +inf and the other is -inf. When these numbers are added,
521 * we maintain the convention of the result being 0.0. */
522 if (isnan(*target)) *target = 0.0;
e2641e09 523 } else if (aggregate == REDIS_AGGR_MIN) {
524 *target = val < *target ? val : *target;
525 } else if (aggregate == REDIS_AGGR_MAX) {
526 *target = val > *target ? val : *target;
527 } else {
528 /* safety net */
529 redisPanic("Unknown ZUNION/INTER aggregate type");
530 }
531}
532
533void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
534 int i, j, setnum;
535 int aggregate = REDIS_AGGR_SUM;
536 zsetopsrc *src;
537 robj *dstobj;
538 zset *dstzset;
69ef89f2 539 zskiplistNode *znode;
e2641e09 540 dictIterator *di;
541 dictEntry *de;
8c1420ff 542 int touched = 0;
e2641e09 543
544 /* expect setnum input keys to be given */
545 setnum = atoi(c->argv[2]->ptr);
546 if (setnum < 1) {
3ab20376
PN
547 addReplyError(c,
548 "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
e2641e09 549 return;
550 }
551
552 /* test if the expected number of keys would overflow */
553 if (3+setnum > c->argc) {
554 addReply(c,shared.syntaxerr);
555 return;
556 }
557
558 /* read keys to be used for input */
559 src = zmalloc(sizeof(zsetopsrc) * setnum);
560 for (i = 0, j = 3; i < setnum; i++, j++) {
561 robj *obj = lookupKeyWrite(c->db,c->argv[j]);
562 if (!obj) {
563 src[i].dict = NULL;
564 } else {
565 if (obj->type == REDIS_ZSET) {
566 src[i].dict = ((zset*)obj->ptr)->dict;
567 } else if (obj->type == REDIS_SET) {
568 src[i].dict = (obj->ptr);
569 } else {
570 zfree(src);
571 addReply(c,shared.wrongtypeerr);
572 return;
573 }
574 }
575
576 /* default all weights to 1 */
577 src[i].weight = 1.0;
578 }
579
580 /* parse optional extra arguments */
581 if (j < c->argc) {
582 int remaining = c->argc - j;
583
584 while (remaining) {
585 if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
586 j++; remaining--;
587 for (i = 0; i < setnum; i++, j++, remaining--) {
673e1fb7
PN
588 if (getDoubleFromObjectOrReply(c,c->argv[j],&src[i].weight,
589 "weight value is not a double") != REDIS_OK)
590 {
591 zfree(src);
e2641e09 592 return;
673e1fb7 593 }
e2641e09 594 }
595 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
596 j++; remaining--;
597 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
598 aggregate = REDIS_AGGR_SUM;
599 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
600 aggregate = REDIS_AGGR_MIN;
601 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
602 aggregate = REDIS_AGGR_MAX;
603 } else {
604 zfree(src);
605 addReply(c,shared.syntaxerr);
606 return;
607 }
608 j++; remaining--;
609 } else {
610 zfree(src);
611 addReply(c,shared.syntaxerr);
612 return;
613 }
614 }
615 }
616
617 /* sort sets from the smallest to largest, this will improve our
618 * algorithm's performance */
619 qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);
620
621 dstobj = createZsetObject();
622 dstzset = dstobj->ptr;
623
624 if (op == REDIS_OP_INTER) {
625 /* skip going over all entries if the smallest zset is NULL or empty */
626 if (src[0].dict && dictSize(src[0].dict) > 0) {
627 /* precondition: as src[0].dict is non-empty and the zsets are ordered
628 * from small to large, all src[i > 0].dict are non-empty too */
629 di = dictGetIterator(src[0].dict);
630 while((de = dictNext(di)) != NULL) {
50a9fad5 631 double score, value;
e2641e09 632
50a9fad5 633 score = src[0].weight * zunionInterDictValue(de);
e2641e09 634 for (j = 1; j < setnum; j++) {
635 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
636 if (other) {
637 value = src[j].weight * zunionInterDictValue(other);
50a9fad5 638 zunionInterAggregate(&score, value, aggregate);
e2641e09 639 } else {
640 break;
641 }
642 }
643
50a9fad5 644 /* accept entry only when present in every source dict */
645 if (j == setnum) {
e2641e09 646 robj *o = dictGetEntryKey(de);
50a9fad5 647 znode = zslInsert(dstzset->zsl,score,o);
e2641e09 648 incrRefCount(o); /* added to skiplist */
69ef89f2
PN
649 dictAdd(dstzset->dict,o,&znode->score);
650 incrRefCount(o); /* added to dictionary */
e2641e09 651 }
652 }
653 dictReleaseIterator(di);
654 }
655 } else if (op == REDIS_OP_UNION) {
656 for (i = 0; i < setnum; i++) {
657 if (!src[i].dict) continue;
658
659 di = dictGetIterator(src[i].dict);
660 while((de = dictNext(di)) != NULL) {
50a9fad5 661 double score, value;
e2641e09 662
50a9fad5 663 /* skip key when already processed */
664 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL)
665 continue;
666 score = src[i].weight * zunionInterDictValue(de);
e2641e09 667
668 /* because the zsets are sorted by size, its only possible
669 * for sets at larger indices to hold this entry */
670 for (j = (i+1); j < setnum; j++) {
671 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
672 if (other) {
673 value = src[j].weight * zunionInterDictValue(other);
50a9fad5 674 zunionInterAggregate(&score, value, aggregate);
e2641e09 675 }
676 }
677
678 robj *o = dictGetEntryKey(de);
50a9fad5 679 znode = zslInsert(dstzset->zsl,score,o);
e2641e09 680 incrRefCount(o); /* added to skiplist */
69ef89f2
PN
681 dictAdd(dstzset->dict,o,&znode->score);
682 incrRefCount(o); /* added to dictionary */
e2641e09 683 }
684 dictReleaseIterator(di);
685 }
686 } else {
687 /* unknown operator */
688 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
689 }
690
8c1420ff 691 if (dbDelete(c->db,dstkey)) {
692 touchWatchedKey(c->db,dstkey);
693 touched = 1;
694 server.dirty++;
695 }
e2641e09 696 if (dstzset->zsl->length) {
697 dbAdd(c->db,dstkey,dstobj);
698 addReplyLongLong(c, dstzset->zsl->length);
8c1420ff 699 if (!touched) touchWatchedKey(c->db,dstkey);
cbf7e107 700 server.dirty++;
e2641e09 701 } else {
702 decrRefCount(dstobj);
703 addReply(c, shared.czero);
704 }
705 zfree(src);
706}
707
708void zunionstoreCommand(redisClient *c) {
709 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
710}
711
712void zinterstoreCommand(redisClient *c) {
713 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
714}
715
716void zrangeGenericCommand(redisClient *c, int reverse) {
717 robj *o;
718 long start;
719 long end;
720 int withscores = 0;
721 int llen;
722 int rangelen, j;
723 zset *zsetobj;
724 zskiplist *zsl;
725 zskiplistNode *ln;
726 robj *ele;
727
728 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
729 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
730
731 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
732 withscores = 1;
733 } else if (c->argc >= 5) {
734 addReply(c,shared.syntaxerr);
735 return;
736 }
737
738 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
739 || checkType(c,o,REDIS_ZSET)) return;
740 zsetobj = o->ptr;
741 zsl = zsetobj->zsl;
742 llen = zsl->length;
743
744 /* convert negative indexes */
745 if (start < 0) start = llen+start;
746 if (end < 0) end = llen+end;
747 if (start < 0) start = 0;
e2641e09 748
d0a4e24e
PN
749 /* Invariant: start >= 0, so this test will be true when end < 0.
750 * The range is empty when start > end or start >= length. */
e2641e09 751 if (start > end || start >= llen) {
e2641e09 752 addReply(c,shared.emptymultibulk);
753 return;
754 }
755 if (end >= llen) end = llen-1;
756 rangelen = (end-start)+1;
757
758 /* check if starting point is trivial, before searching
759 * the element in log(N) time */
760 if (reverse) {
761 ln = start == 0 ? zsl->tail : zslistTypeGetElementByRank(zsl, llen-start);
762 } else {
763 ln = start == 0 ?
2159782b 764 zsl->header->level[0].forward : zslistTypeGetElementByRank(zsl, start+1);
e2641e09 765 }
766
767 /* Return the result in form of a multi-bulk reply */
0537e7bf 768 addReplyMultiBulkLen(c,withscores ? (rangelen*2) : rangelen);
e2641e09 769 for (j = 0; j < rangelen; j++) {
770 ele = ln->obj;
771 addReplyBulk(c,ele);
772 if (withscores)
773 addReplyDouble(c,ln->score);
2159782b 774 ln = reverse ? ln->backward : ln->level[0].forward;
e2641e09 775 }
776}
777
778void zrangeCommand(redisClient *c) {
779 zrangeGenericCommand(c,0);
780}
781
782void zrevrangeCommand(redisClient *c) {
783 zrangeGenericCommand(c,1);
784}
785
786/* This command implements both ZRANGEBYSCORE and ZCOUNT.
787 * If justcount is non-zero, just the count is returned. */
788void genericZrangebyscoreCommand(redisClient *c, int justcount) {
789 robj *o;
790 double min, max;
791 int minex = 0, maxex = 0; /* are min or max exclusive? */
792 int offset = 0, limit = -1;
793 int withscores = 0;
794 int badsyntax = 0;
795
796 /* Parse the min-max interval. If one of the values is prefixed
797 * by the "(" character, it's considered "open". For instance
798 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
799 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
800 if (((char*)c->argv[2]->ptr)[0] == '(') {
801 min = strtod((char*)c->argv[2]->ptr+1,NULL);
802 minex = 1;
803 } else {
804 min = strtod(c->argv[2]->ptr,NULL);
805 }
806 if (((char*)c->argv[3]->ptr)[0] == '(') {
807 max = strtod((char*)c->argv[3]->ptr+1,NULL);
808 maxex = 1;
809 } else {
810 max = strtod(c->argv[3]->ptr,NULL);
811 }
812
813 /* Parse "WITHSCORES": note that if the command was called with
814 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
815 * enter the following paths to parse WITHSCORES and LIMIT. */
816 if (c->argc == 5 || c->argc == 8) {
817 if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
818 withscores = 1;
819 else
820 badsyntax = 1;
821 }
822 if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
823 badsyntax = 1;
824 if (badsyntax) {
3ab20376 825 addReplyError(c,"wrong number of arguments for ZRANGEBYSCORE");
e2641e09 826 return;
827 }
828
829 /* Parse "LIMIT" */
830 if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
831 addReply(c,shared.syntaxerr);
832 return;
833 } else if (c->argc == (7 + withscores)) {
834 offset = atoi(c->argv[5]->ptr);
835 limit = atoi(c->argv[6]->ptr);
836 if (offset < 0) offset = 0;
837 }
838
839 /* Ok, lookup the key and get the range */
840 o = lookupKeyRead(c->db,c->argv[1]);
841 if (o == NULL) {
842 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
843 } else {
844 if (o->type != REDIS_ZSET) {
845 addReply(c,shared.wrongtypeerr);
846 } else {
847 zset *zsetobj = o->ptr;
848 zskiplist *zsl = zsetobj->zsl;
849 zskiplistNode *ln;
b301c1fc
PN
850 robj *ele;
851 void *replylen = NULL;
e2641e09 852 unsigned long rangelen = 0;
853
854 /* Get the first node with the score >= min, or with
855 * score > min if 'minex' is true. */
856 ln = zslFirstWithScore(zsl,min);
2159782b 857 while (minex && ln && ln->score == min) ln = ln->level[0].forward;
e2641e09 858
859 if (ln == NULL) {
860 /* No element matching the speciifed interval */
861 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
862 return;
863 }
864
865 /* We don't know in advance how many matching elements there
866 * are in the list, so we push this object that will represent
867 * the multi-bulk length in the output buffer, and will "fix"
868 * it later */
b301c1fc
PN
869 if (!justcount)
870 replylen = addDeferredMultiBulkLength(c);
e2641e09 871
872 while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
873 if (offset) {
874 offset--;
2159782b 875 ln = ln->level[0].forward;
e2641e09 876 continue;
877 }
878 if (limit == 0) break;
879 if (!justcount) {
880 ele = ln->obj;
881 addReplyBulk(c,ele);
882 if (withscores)
883 addReplyDouble(c,ln->score);
884 }
2159782b 885 ln = ln->level[0].forward;
e2641e09 886 rangelen++;
887 if (limit > 0) limit--;
888 }
889 if (justcount) {
890 addReplyLongLong(c,(long)rangelen);
891 } else {
b301c1fc 892 setDeferredMultiBulkLength(c,replylen,
e2641e09 893 withscores ? (rangelen*2) : rangelen);
894 }
895 }
896 }
897}
898
899void zrangebyscoreCommand(redisClient *c) {
900 genericZrangebyscoreCommand(c,0);
901}
902
903void zcountCommand(redisClient *c) {
904 genericZrangebyscoreCommand(c,1);
905}
906
907void zcardCommand(redisClient *c) {
908 robj *o;
909 zset *zs;
910
911 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
912 checkType(c,o,REDIS_ZSET)) return;
913
914 zs = o->ptr;
b70d3555 915 addReplyLongLong(c,zs->zsl->length);
e2641e09 916}
917
918void zscoreCommand(redisClient *c) {
919 robj *o;
920 zset *zs;
921 dictEntry *de;
922
923 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
924 checkType(c,o,REDIS_ZSET)) return;
925
926 zs = o->ptr;
75b41de8 927 c->argv[2] = tryObjectEncoding(c->argv[2]);
e2641e09 928 de = dictFind(zs->dict,c->argv[2]);
929 if (!de) {
930 addReply(c,shared.nullbulk);
931 } else {
932 double *score = dictGetEntryVal(de);
933
934 addReplyDouble(c,*score);
935 }
936}
937
938void zrankGenericCommand(redisClient *c, int reverse) {
939 robj *o;
940 zset *zs;
941 zskiplist *zsl;
942 dictEntry *de;
943 unsigned long rank;
944 double *score;
945
946 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
947 checkType(c,o,REDIS_ZSET)) return;
948
949 zs = o->ptr;
950 zsl = zs->zsl;
75b41de8 951 c->argv[2] = tryObjectEncoding(c->argv[2]);
e2641e09 952 de = dictFind(zs->dict,c->argv[2]);
953 if (!de) {
954 addReply(c,shared.nullbulk);
955 return;
956 }
957
958 score = dictGetEntryVal(de);
959 rank = zslistTypeGetRank(zsl, *score, c->argv[2]);
960 if (rank) {
961 if (reverse) {
962 addReplyLongLong(c, zsl->length - rank);
963 } else {
964 addReplyLongLong(c, rank-1);
965 }
966 } else {
967 addReply(c,shared.nullbulk);
968 }
969}
970
971void zrankCommand(redisClient *c) {
972 zrankGenericCommand(c, 0);
973}
974
975void zrevrankCommand(redisClient *c) {
976 zrankGenericCommand(c, 1);
977}