5 /*-----------------------------------------------------------------------------
7 *----------------------------------------------------------------------------*/
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
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"). */
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. */
26 zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
27 zskiplistNode
*zn
= zmalloc(sizeof(*zn
)+level
*sizeof(struct zskiplistLevel
));
33 zskiplist
*zslCreate(void) {
37 zsl
= zmalloc(sizeof(*zsl
));
40 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
41 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++) {
42 zsl
->header
->level
[j
].forward
= NULL
;
43 zsl
->header
->level
[j
].span
= 0;
45 zsl
->header
->backward
= NULL
;
50 void zslFreeNode(zskiplistNode
*node
) {
51 decrRefCount(node
->obj
);
55 void zslFree(zskiplist
*zsl
) {
56 zskiplistNode
*node
= zsl
->header
->level
[0].forward
, *next
;
60 next
= node
->level
[0].forward
;
67 int zslRandomLevel(void) {
69 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
71 return (level
<ZSKIPLIST_MAXLEVEL
) ? level
: ZSKIPLIST_MAXLEVEL
;
74 zskiplistNode
*zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
75 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
76 unsigned int rank
[ZSKIPLIST_MAXLEVEL
];
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];
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
;
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
++) {
100 update
[i
] = zsl
->header
;
101 update
[i
]->level
[i
].span
= zsl
->length
;
105 x
= zslCreateNode(level
,score
,obj
);
106 for (i
= 0; i
< level
; i
++) {
107 x
->level
[i
].forward
= update
[i
]->level
[i
].forward
;
108 update
[i
]->level
[i
].forward
= x
;
110 /* update span covered by update[i] as x is inserted here */
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;
115 /* increment span for untouched levels */
116 for (i
= level
; i
< zsl
->level
; i
++) {
117 update
[i
]->level
[i
].span
++;
120 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
121 if (x
->level
[0].forward
)
122 x
->level
[0].forward
->backward
= x
;
129 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
130 void zslDeleteNode(zskiplist
*zsl
, zskiplistNode
*x
, zskiplistNode
**update
) {
132 for (i
= 0; i
< zsl
->level
; i
++) {
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
;
137 update
[i
]->level
[i
].span
-= 1;
140 if (x
->level
[0].forward
) {
141 x
->level
[0].forward
->backward
= x
->backward
;
143 zsl
->tail
= x
->backward
;
145 while(zsl
->level
> 1 && zsl
->header
->level
[zsl
->level
-1].forward
== NULL
)
150 /* Delete an element with matching score/object from the skiplist. */
151 int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
152 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
156 for (i
= zsl
->level
-1; i
>= 0; i
--) {
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
;
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. */
166 x
= x
->level
[0].forward
;
167 if (x
&& score
== x
->score
&& equalStringObjects(x
->obj
,obj
)) {
168 zslDeleteNode(zsl
, x
, update
);
172 return 0; /* not found */
174 return 0; /* not found */
177 /* Struct to hold a inclusive/exclusive range spec. */
180 int minex
, maxex
; /* are min or max exclusive? */
183 static int zslValueGteMin(double value
, zrangespec
*spec
) {
184 return spec
->minex
? (value
> spec
->min
) : (value
>= spec
->min
);
187 static int zslValueLteMax(double value
, zrangespec
*spec
) {
188 return spec
->maxex
? (value
< spec
->max
) : (value
<= spec
->max
);
191 static int zslValueInRange(double value
, zrangespec
*spec
) {
192 return zslValueGteMin(value
,spec
) && zslValueLteMax(value
,spec
);
195 /* Returns if there is a part of the zset is in range. */
196 int zslIsInRange(zskiplist
*zsl
, zrangespec
*range
) {
199 /* Test for ranges that will always be empty. */
200 if (range
->min
> range
->max
||
201 (range
->min
== range
->max
&& (range
->minex
|| range
->maxex
)))
204 if (x
== NULL
|| !zslValueGteMin(x
->score
,range
))
206 x
= zsl
->header
->level
[0].forward
;
207 if (x
== NULL
|| !zslValueLteMax(x
->score
,range
))
212 /* Find the first node that is contained in the specified range.
213 * Returns NULL when no element is contained in the range. */
214 zskiplistNode
*zslFirstInRange(zskiplist
*zsl
, zrangespec range
) {
218 /* If everything is out of range, return early. */
219 if (!zslIsInRange(zsl
,&range
)) return NULL
;
222 for (i
= zsl
->level
-1; i
>= 0; i
--) {
223 /* Go forward while *OUT* of range. */
224 while (x
->level
[i
].forward
&&
225 !zslValueGteMin(x
->level
[i
].forward
->score
,&range
))
226 x
= x
->level
[i
].forward
;
229 /* The tail is in range, so the previous block should always return a
230 * node that is non-NULL and the last one to be out of range. */
231 x
= x
->level
[0].forward
;
232 redisAssert(x
!= NULL
&& zslValueInRange(x
->score
,&range
));
236 /* Find the last node that is contained in the specified range.
237 * Returns NULL when no element is contained in the range. */
238 zskiplistNode
*zslLastInRange(zskiplist
*zsl
, zrangespec range
) {
242 /* If everything is out of range, return early. */
243 if (!zslIsInRange(zsl
,&range
)) return NULL
;
246 for (i
= zsl
->level
-1; i
>= 0; i
--) {
247 /* Go forward while *IN* range. */
248 while (x
->level
[i
].forward
&&
249 zslValueLteMax(x
->level
[i
].forward
->score
,&range
))
250 x
= x
->level
[i
].forward
;
253 /* The header is in range, so the previous block should always return a
254 * node that is non-NULL and in range. */
255 redisAssert(x
!= NULL
&& zslValueInRange(x
->score
,&range
));
259 /* Delete all the elements with score between min and max from the skiplist.
260 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
261 * Note that this function takes the reference to the hash table view of the
262 * sorted set, in order to remove the elements from the hash table too. */
263 unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, zrangespec range
, dict
*dict
) {
264 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
265 unsigned long removed
= 0;
269 for (i
= zsl
->level
-1; i
>= 0; i
--) {
270 while (x
->level
[i
].forward
&& (range
.minex
?
271 x
->level
[i
].forward
->score
<= range
.min
:
272 x
->level
[i
].forward
->score
< range
.min
))
273 x
= x
->level
[i
].forward
;
277 /* Current node is the last with score < or <= min. */
278 x
= x
->level
[0].forward
;
280 /* Delete nodes while in range. */
281 while (x
&& (range
.maxex
? x
->score
< range
.max
: x
->score
<= range
.max
)) {
282 zskiplistNode
*next
= x
->level
[0].forward
;
283 zslDeleteNode(zsl
,x
,update
);
284 dictDelete(dict
,x
->obj
);
292 /* Delete all the elements with rank between start and end from the skiplist.
293 * Start and end are inclusive. Note that start and end need to be 1-based */
294 unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
295 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
296 unsigned long traversed
= 0, removed
= 0;
300 for (i
= zsl
->level
-1; i
>= 0; i
--) {
301 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) < start
) {
302 traversed
+= x
->level
[i
].span
;
303 x
= x
->level
[i
].forward
;
309 x
= x
->level
[0].forward
;
310 while (x
&& traversed
<= end
) {
311 zskiplistNode
*next
= x
->level
[0].forward
;
312 zslDeleteNode(zsl
,x
,update
);
313 dictDelete(dict
,x
->obj
);
322 /* Find the rank for an element by both score and key.
323 * Returns 0 when the element cannot be found, rank otherwise.
324 * Note that the rank is 1-based due to the span of zsl->header to the
326 unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
328 unsigned long rank
= 0;
332 for (i
= zsl
->level
-1; i
>= 0; i
--) {
333 while (x
->level
[i
].forward
&&
334 (x
->level
[i
].forward
->score
< score
||
335 (x
->level
[i
].forward
->score
== score
&&
336 compareStringObjects(x
->level
[i
].forward
->obj
,o
) <= 0))) {
337 rank
+= x
->level
[i
].span
;
338 x
= x
->level
[i
].forward
;
341 /* x might be equal to zsl->header, so test if obj is non-NULL */
342 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
349 /* Finds an element by its rank. The rank argument needs to be 1-based. */
350 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
352 unsigned long traversed
= 0;
356 for (i
= zsl
->level
-1; i
>= 0; i
--) {
357 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) <= rank
)
359 traversed
+= x
->level
[i
].span
;
360 x
= x
->level
[i
].forward
;
362 if (traversed
== rank
) {
369 /* Populate the rangespec according to the objects min and max. */
370 static int zslParseRange(robj
*min
, robj
*max
, zrangespec
*spec
) {
372 spec
->minex
= spec
->maxex
= 0;
374 /* Parse the min-max interval. If one of the values is prefixed
375 * by the "(" character, it's considered "open". For instance
376 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
377 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
378 if (min
->encoding
== REDIS_ENCODING_INT
) {
379 spec
->min
= (long)min
->ptr
;
381 if (((char*)min
->ptr
)[0] == '(') {
382 spec
->min
= strtod((char*)min
->ptr
+1,&eptr
);
383 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
386 spec
->min
= strtod((char*)min
->ptr
,&eptr
);
387 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
390 if (max
->encoding
== REDIS_ENCODING_INT
) {
391 spec
->max
= (long)max
->ptr
;
393 if (((char*)max
->ptr
)[0] == '(') {
394 spec
->max
= strtod((char*)max
->ptr
+1,&eptr
);
395 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
398 spec
->max
= strtod((char*)max
->ptr
,&eptr
);
399 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
406 /*-----------------------------------------------------------------------------
407 * Ziplist-backed sorted set API
408 *----------------------------------------------------------------------------*/
410 double zzlGetScore(unsigned char *sptr
) {
417 redisAssert(sptr
!= NULL
);
418 redisAssert(ziplistGet(sptr
,&vstr
,&vlen
,&vlong
));
421 memcpy(buf
,vstr
,vlen
);
423 score
= strtod(buf
,NULL
);
431 /* Compare element in sorted set with given element. */
432 int zzlCompareElements(unsigned char *eptr
, unsigned char *cstr
, unsigned int clen
) {
436 unsigned char vbuf
[32];
439 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
441 /* Store string representation of long long in buf. */
442 vlen
= ll2string((char*)vbuf
,sizeof(vbuf
),vlong
);
446 minlen
= (vlen
< clen
) ? vlen
: clen
;
447 cmp
= memcmp(vstr
,cstr
,minlen
);
448 if (cmp
== 0) return vlen
-clen
;
452 unsigned int zzlLength(robj
*zobj
) {
453 unsigned char *zl
= zobj
->ptr
;
454 return ziplistLen(zl
)/2;
457 unsigned char *zzlFind(robj
*zobj
, robj
*ele
, double *score
) {
458 unsigned char *zl
= zobj
->ptr
;
459 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
461 ele
= getDecodedObject(ele
);
462 while (eptr
!= NULL
) {
463 sptr
= ziplistNext(zl
,eptr
);
464 redisAssert(sptr
!= NULL
);
466 if (ziplistCompare(eptr
,ele
->ptr
,sdslen(ele
->ptr
))) {
467 /* Matching element, pull out score. */
468 if (score
!= NULL
) *score
= zzlGetScore(sptr
);
473 /* Move to next element. */
474 eptr
= ziplistNext(zl
,sptr
);
481 /* Delete (element,score) pair from ziplist. Use local copy of eptr because we
482 * don't want to modify the one given as argument. */
483 int zzlDelete(robj
*zobj
, unsigned char *eptr
) {
484 unsigned char *zl
= zobj
->ptr
;
485 unsigned char *p
= eptr
;
487 /* TODO: add function to ziplist API to delete N elements from offset. */
488 zl
= ziplistDelete(zl
,&p
);
489 zl
= ziplistDelete(zl
,&p
);
494 int zzlInsertAt(robj
*zobj
, robj
*ele
, double score
, unsigned char *eptr
) {
495 unsigned char *zl
= zobj
->ptr
;
501 redisAssert(ele
->encoding
== REDIS_ENCODING_RAW
);
502 scorelen
= d2string(scorebuf
,sizeof(scorebuf
),score
);
504 zl
= ziplistPush(zl
,ele
->ptr
,sdslen(ele
->ptr
),ZIPLIST_TAIL
);
505 zl
= ziplistPush(zl
,(unsigned char*)scorebuf
,scorelen
,ZIPLIST_TAIL
);
507 /* Keep offset relative to zl, as it might be re-allocated. */
509 zl
= ziplistInsert(zl
,eptr
,ele
->ptr
,sdslen(ele
->ptr
));
512 /* Insert score after the element. */
513 redisAssert((sptr
= ziplistNext(zl
,eptr
)) != NULL
);
514 zl
= ziplistInsert(zl
,sptr
,(unsigned char*)scorebuf
,scorelen
);
521 /* Insert (element,score) pair in ziplist. This function assumes the element is
522 * not yet present in the list. */
523 int zzlInsert(robj
*zobj
, robj
*ele
, double score
) {
524 unsigned char *zl
= zobj
->ptr
;
525 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
528 ele
= getDecodedObject(ele
);
529 while (eptr
!= NULL
) {
530 sptr
= ziplistNext(zl
,eptr
);
531 redisAssert(sptr
!= NULL
);
532 s
= zzlGetScore(sptr
);
535 /* First element with score larger than score for element to be
536 * inserted. This means we should take its spot in the list to
537 * maintain ordering. */
538 zzlInsertAt(zobj
,ele
,score
,eptr
);
540 } else if (s
== score
) {
541 /* Ensure lexicographical ordering for elements. */
542 if (zzlCompareElements(eptr
,ele
->ptr
,sdslen(ele
->ptr
)) < 0) {
543 zzlInsertAt(zobj
,ele
,score
,eptr
);
548 /* Move to next element. */
549 eptr
= ziplistNext(zl
,sptr
);
552 /* Push on tail of list when it was not yet inserted. */
554 zzlInsertAt(zobj
,ele
,score
,NULL
);
560 /*-----------------------------------------------------------------------------
561 * Sorted set commands
562 *----------------------------------------------------------------------------*/
564 /* This generic command implements both ZADD and ZINCRBY. */
565 void zaddGenericCommand(redisClient
*c
, int incr
) {
566 static char *nanerr
= "resulting score is not a number (NaN)";
567 robj
*key
= c
->argv
[1];
571 double score
, curscore
= 0.0;
573 if (getDoubleFromObjectOrReply(c
,c
->argv
[2],&score
,NULL
) != REDIS_OK
)
576 zobj
= lookupKeyWrite(c
->db
,key
);
578 zobj
= createZsetZiplistObject();
579 dbAdd(c
->db
,key
,zobj
);
581 if (zobj
->type
!= REDIS_ZSET
) {
582 addReply(c
,shared
.wrongtypeerr
);
587 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
590 /* Prefer non-encoded element when dealing with ziplists. */
592 if ((eptr
= zzlFind(zobj
,ele
,&curscore
)) != NULL
) {
596 addReplyError(c
,nanerr
);
597 /* Don't need to check if the sorted set is empty, because
598 * we know it has at least one element. */
603 /* Remove and re-insert when score changed. */
604 if (score
!= curscore
) {
605 redisAssert(zzlDelete(zobj
,eptr
) == REDIS_OK
);
606 redisAssert(zzlInsert(zobj
,ele
,score
) == REDIS_OK
);
608 signalModifiedKey(c
->db
,key
);
612 if (incr
) /* ZINCRBY */
613 addReplyDouble(c
,score
);
615 addReply(c
,shared
.czero
);
617 redisAssert(zzlInsert(zobj
,ele
,score
) == REDIS_OK
);
619 signalModifiedKey(c
->db
,key
);
622 if (incr
) /* ZINCRBY */
623 addReplyDouble(c
,score
);
625 addReply(c
,shared
.cone
);
627 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
628 zset
*zs
= zobj
->ptr
;
629 zskiplistNode
*znode
;
632 ele
= c
->argv
[3] = tryObjectEncoding(c
->argv
[3]);
633 de
= dictFind(zs
->dict
,ele
);
635 curobj
= dictGetEntryKey(de
);
636 curscore
= *(double*)dictGetEntryVal(de
);
641 addReplyError(c
,nanerr
);
642 /* Don't need to check if the sorted set is empty, because
643 * we know it has at least one element. */
648 /* Remove and re-insert when score changed. We can safely delete
649 * the key object from the skiplist, since the dictionary still has
650 * a reference to it. */
651 if (score
!= curscore
) {
652 redisAssert(zslDelete(zs
->zsl
,curscore
,curobj
));
653 znode
= zslInsert(zs
->zsl
,score
,curobj
);
654 incrRefCount(curobj
); /* Re-inserted in skiplist. */
655 dictGetEntryVal(de
) = &znode
->score
; /* Update score ptr. */
657 signalModifiedKey(c
->db
,key
);
661 if (incr
) /* ZINCRBY */
662 addReplyDouble(c
,score
);
664 addReply(c
,shared
.czero
);
666 znode
= zslInsert(zs
->zsl
,score
,ele
);
667 incrRefCount(ele
); /* Inserted in skiplist. */
668 redisAssert(dictAdd(zs
->dict
,ele
,&znode
->score
) == DICT_OK
);
669 incrRefCount(ele
); /* Added to dictionary. */
671 signalModifiedKey(c
->db
,key
);
674 if (incr
) /* ZINCRBY */
675 addReplyDouble(c
,score
);
677 addReply(c
,shared
.cone
);
680 redisPanic("Unknown sorted set encoding");
684 void zaddCommand(redisClient
*c
) {
685 zaddGenericCommand(c
,0);
688 void zincrbyCommand(redisClient
*c
) {
689 zaddGenericCommand(c
,1);
692 void zremCommand(redisClient
*c
) {
693 robj
*key
= c
->argv
[1];
694 robj
*ele
= c
->argv
[2];
697 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
698 checkType(c
,zobj
,REDIS_ZSET
)) return;
700 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
703 if ((eptr
= zzlFind(zobj
,ele
,NULL
)) != NULL
) {
704 redisAssert(zzlDelete(zobj
,eptr
) == REDIS_OK
);
705 if (zzlLength(zobj
) == 0) dbDelete(c
->db
,key
);
707 addReply(c
,shared
.czero
);
710 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
711 zset
*zs
= zobj
->ptr
;
715 de
= dictFind(zs
->dict
,ele
);
717 /* Delete from the skiplist */
718 score
= *(double*)dictGetEntryVal(de
);
719 redisAssert(zslDelete(zs
->zsl
,score
,ele
));
721 /* Delete from the hash table */
722 dictDelete(zs
->dict
,ele
);
723 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
724 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
726 addReply(c
,shared
.czero
);
730 redisPanic("Unknown sorted set encoding");
733 signalModifiedKey(c
->db
,key
);
735 addReply(c
,shared
.cone
);
738 void zremrangebyscoreCommand(redisClient
*c
) {
744 /* Parse the range arguments. */
745 if (zslParseRange(c
->argv
[2],c
->argv
[3],&range
) != REDIS_OK
) {
746 addReplyError(c
,"min or max is not a double");
750 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
751 checkType(c
,o
,REDIS_ZSET
)) return;
754 deleted
= zslDeleteRangeByScore(zs
->zsl
,range
,zs
->dict
);
755 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
756 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,c
->argv
[1]);
757 if (deleted
) signalModifiedKey(c
->db
,c
->argv
[1]);
758 server
.dirty
+= deleted
;
759 addReplyLongLong(c
,deleted
);
762 void zremrangebyrankCommand(redisClient
*c
) {
770 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
771 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
773 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
774 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
776 llen
= zs
->zsl
->length
;
778 /* convert negative indexes */
779 if (start
< 0) start
= llen
+start
;
780 if (end
< 0) end
= llen
+end
;
781 if (start
< 0) start
= 0;
783 /* Invariant: start >= 0, so this test will be true when end < 0.
784 * The range is empty when start > end or start >= length. */
785 if (start
> end
|| start
>= llen
) {
786 addReply(c
,shared
.czero
);
789 if (end
>= llen
) end
= llen
-1;
791 /* increment start and end because zsl*Rank functions
792 * use 1-based rank */
793 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
794 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
795 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,c
->argv
[1]);
796 if (deleted
) signalModifiedKey(c
->db
,c
->argv
[1]);
797 server
.dirty
+= deleted
;
798 addReplyLongLong(c
, deleted
);
806 int qsortCompareZsetopsrcByCardinality(const void *s1
, const void *s2
) {
807 zsetopsrc
*d1
= (void*) s1
, *d2
= (void*) s2
;
808 unsigned long size1
, size2
;
809 size1
= d1
->dict
? dictSize(d1
->dict
) : 0;
810 size2
= d2
->dict
? dictSize(d2
->dict
) : 0;
811 return size1
- size2
;
814 #define REDIS_AGGR_SUM 1
815 #define REDIS_AGGR_MIN 2
816 #define REDIS_AGGR_MAX 3
817 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
819 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
820 if (aggregate
== REDIS_AGGR_SUM
) {
821 *target
= *target
+ val
;
822 /* The result of adding two doubles is NaN when one variable
823 * is +inf and the other is -inf. When these numbers are added,
824 * we maintain the convention of the result being 0.0. */
825 if (isnan(*target
)) *target
= 0.0;
826 } else if (aggregate
== REDIS_AGGR_MIN
) {
827 *target
= val
< *target
? val
: *target
;
828 } else if (aggregate
== REDIS_AGGR_MAX
) {
829 *target
= val
> *target
? val
: *target
;
832 redisPanic("Unknown ZUNION/INTER aggregate type");
836 void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
838 int aggregate
= REDIS_AGGR_SUM
;
842 zskiplistNode
*znode
;
847 /* expect setnum input keys to be given */
848 setnum
= atoi(c
->argv
[2]->ptr
);
851 "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
855 /* test if the expected number of keys would overflow */
856 if (3+setnum
> c
->argc
) {
857 addReply(c
,shared
.syntaxerr
);
861 /* read keys to be used for input */
862 src
= zmalloc(sizeof(zsetopsrc
) * setnum
);
863 for (i
= 0, j
= 3; i
< setnum
; i
++, j
++) {
864 robj
*obj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
868 if (obj
->type
== REDIS_ZSET
) {
869 src
[i
].dict
= ((zset
*)obj
->ptr
)->dict
;
870 } else if (obj
->type
== REDIS_SET
) {
871 src
[i
].dict
= (obj
->ptr
);
874 addReply(c
,shared
.wrongtypeerr
);
879 /* default all weights to 1 */
883 /* parse optional extra arguments */
885 int remaining
= c
->argc
- j
;
888 if (remaining
>= (setnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
890 for (i
= 0; i
< setnum
; i
++, j
++, remaining
--) {
891 if (getDoubleFromObjectOrReply(c
,c
->argv
[j
],&src
[i
].weight
,
892 "weight value is not a double") != REDIS_OK
)
898 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
900 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
901 aggregate
= REDIS_AGGR_SUM
;
902 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
903 aggregate
= REDIS_AGGR_MIN
;
904 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
905 aggregate
= REDIS_AGGR_MAX
;
908 addReply(c
,shared
.syntaxerr
);
914 addReply(c
,shared
.syntaxerr
);
920 /* sort sets from the smallest to largest, this will improve our
921 * algorithm's performance */
922 qsort(src
,setnum
,sizeof(zsetopsrc
),qsortCompareZsetopsrcByCardinality
);
924 dstobj
= createZsetObject();
925 dstzset
= dstobj
->ptr
;
927 if (op
== REDIS_OP_INTER
) {
928 /* skip going over all entries if the smallest zset is NULL or empty */
929 if (src
[0].dict
&& dictSize(src
[0].dict
) > 0) {
930 /* precondition: as src[0].dict is non-empty and the zsets are ordered
931 * from small to large, all src[i > 0].dict are non-empty too */
932 di
= dictGetIterator(src
[0].dict
);
933 while((de
= dictNext(di
)) != NULL
) {
936 score
= src
[0].weight
* zunionInterDictValue(de
);
937 for (j
= 1; j
< setnum
; j
++) {
938 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
940 value
= src
[j
].weight
* zunionInterDictValue(other
);
941 zunionInterAggregate(&score
,value
,aggregate
);
947 /* Only continue when present in every source dict. */
949 robj
*o
= dictGetEntryKey(de
);
950 znode
= zslInsert(dstzset
->zsl
,score
,o
);
951 incrRefCount(o
); /* added to skiplist */
952 dictAdd(dstzset
->dict
,o
,&znode
->score
);
953 incrRefCount(o
); /* added to dictionary */
956 dictReleaseIterator(di
);
958 } else if (op
== REDIS_OP_UNION
) {
959 for (i
= 0; i
< setnum
; i
++) {
960 if (!src
[i
].dict
) continue;
962 di
= dictGetIterator(src
[i
].dict
);
963 while((de
= dictNext(di
)) != NULL
) {
966 /* skip key when already processed */
967 if (dictFind(dstzset
->dict
,dictGetEntryKey(de
)) != NULL
)
970 /* initialize score */
971 score
= src
[i
].weight
* zunionInterDictValue(de
);
973 /* because the zsets are sorted by size, its only possible
974 * for sets at larger indices to hold this entry */
975 for (j
= (i
+1); j
< setnum
; j
++) {
976 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
978 value
= src
[j
].weight
* zunionInterDictValue(other
);
979 zunionInterAggregate(&score
,value
,aggregate
);
983 robj
*o
= dictGetEntryKey(de
);
984 znode
= zslInsert(dstzset
->zsl
,score
,o
);
985 incrRefCount(o
); /* added to skiplist */
986 dictAdd(dstzset
->dict
,o
,&znode
->score
);
987 incrRefCount(o
); /* added to dictionary */
989 dictReleaseIterator(di
);
992 /* unknown operator */
993 redisAssert(op
== REDIS_OP_INTER
|| op
== REDIS_OP_UNION
);
996 if (dbDelete(c
->db
,dstkey
)) {
997 signalModifiedKey(c
->db
,dstkey
);
1001 if (dstzset
->zsl
->length
) {
1002 dbAdd(c
->db
,dstkey
,dstobj
);
1003 addReplyLongLong(c
, dstzset
->zsl
->length
);
1004 if (!touched
) signalModifiedKey(c
->db
,dstkey
);
1007 decrRefCount(dstobj
);
1008 addReply(c
, shared
.czero
);
1013 void zunionstoreCommand(redisClient
*c
) {
1014 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
1017 void zinterstoreCommand(redisClient
*c
) {
1018 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
1021 void zrangeGenericCommand(redisClient
*c
, int reverse
) {
1033 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1034 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1036 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
1038 } else if (c
->argc
>= 5) {
1039 addReply(c
,shared
.syntaxerr
);
1043 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
1044 || checkType(c
,o
,REDIS_ZSET
)) return;
1049 /* convert negative indexes */
1050 if (start
< 0) start
= llen
+start
;
1051 if (end
< 0) end
= llen
+end
;
1052 if (start
< 0) start
= 0;
1054 /* Invariant: start >= 0, so this test will be true when end < 0.
1055 * The range is empty when start > end or start >= length. */
1056 if (start
> end
|| start
>= llen
) {
1057 addReply(c
,shared
.emptymultibulk
);
1060 if (end
>= llen
) end
= llen
-1;
1061 rangelen
= (end
-start
)+1;
1063 /* check if starting point is trivial, before searching
1064 * the element in log(N) time */
1066 ln
= start
== 0 ? zsl
->tail
: zslGetElementByRank(zsl
, llen
-start
);
1069 zsl
->header
->level
[0].forward
: zslGetElementByRank(zsl
, start
+1);
1072 /* Return the result in form of a multi-bulk reply */
1073 addReplyMultiBulkLen(c
,withscores
? (rangelen
*2) : rangelen
);
1074 for (j
= 0; j
< rangelen
; j
++) {
1076 addReplyBulk(c
,ele
);
1078 addReplyDouble(c
,ln
->score
);
1079 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1083 void zrangeCommand(redisClient
*c
) {
1084 zrangeGenericCommand(c
,0);
1087 void zrevrangeCommand(redisClient
*c
) {
1088 zrangeGenericCommand(c
,1);
1091 /* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE and ZCOUNT.
1092 * If "justcount", only the number of elements in the range is returned. */
1093 void genericZrangebyscoreCommand(redisClient
*c
, int reverse
, int justcount
) {
1095 robj
*o
, *emptyreply
;
1099 int offset
= 0, limit
= -1;
1101 unsigned long rangelen
= 0;
1102 void *replylen
= NULL
;
1105 /* Parse the range arguments. */
1107 /* Range is given as [max,min] */
1108 maxidx
= 2; minidx
= 3;
1110 /* Range is given as [min,max] */
1111 minidx
= 2; maxidx
= 3;
1114 if (zslParseRange(c
->argv
[minidx
],c
->argv
[maxidx
],&range
) != REDIS_OK
) {
1115 addReplyError(c
,"min or max is not a double");
1119 /* Parse optional extra arguments. Note that ZCOUNT will exactly have
1120 * 4 arguments, so we'll never enter the following code path. */
1122 int remaining
= c
->argc
- 4;
1126 if (remaining
>= 1 && !strcasecmp(c
->argv
[pos
]->ptr
,"withscores")) {
1129 } else if (remaining
>= 3 && !strcasecmp(c
->argv
[pos
]->ptr
,"limit")) {
1130 offset
= atoi(c
->argv
[pos
+1]->ptr
);
1131 limit
= atoi(c
->argv
[pos
+2]->ptr
);
1132 pos
+= 3; remaining
-= 3;
1134 addReply(c
,shared
.syntaxerr
);
1140 /* Ok, lookup the key and get the range */
1141 emptyreply
= justcount
? shared
.czero
: shared
.emptymultibulk
;
1142 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],emptyreply
)) == NULL
||
1143 checkType(c
,o
,REDIS_ZSET
)) return;
1147 /* If reversed, get the last node in range as starting point. */
1149 ln
= zslLastInRange(zsl
,range
);
1151 ln
= zslFirstInRange(zsl
,range
);
1154 /* No "first" element in the specified interval. */
1156 addReply(c
,emptyreply
);
1160 /* We don't know in advance how many matching elements there are in the
1161 * list, so we push this object that will represent the multi-bulk length
1162 * in the output buffer, and will "fix" it later */
1164 replylen
= addDeferredMultiBulkLength(c
);
1166 /* If there is an offset, just traverse the number of elements without
1167 * checking the score because that is done in the next loop. */
1168 while(ln
&& offset
--) {
1169 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1172 while (ln
&& limit
--) {
1173 /* Abort when the node is no longer in range. */
1175 if (!zslValueGteMin(ln
->score
,&range
)) break;
1177 if (!zslValueLteMax(ln
->score
,&range
)) break;
1183 addReplyBulk(c
,ln
->obj
);
1185 addReplyDouble(c
,ln
->score
);
1188 /* Move to next node */
1189 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1193 addReplyLongLong(c
,(long)rangelen
);
1195 setDeferredMultiBulkLength(c
,replylen
,
1196 withscores
? (rangelen
*2) : rangelen
);
1200 void zrangebyscoreCommand(redisClient
*c
) {
1201 genericZrangebyscoreCommand(c
,0,0);
1204 void zrevrangebyscoreCommand(redisClient
*c
) {
1205 genericZrangebyscoreCommand(c
,1,0);
1208 void zcountCommand(redisClient
*c
) {
1209 genericZrangebyscoreCommand(c
,0,1);
1212 void zcardCommand(redisClient
*c
) {
1216 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
1217 checkType(c
,o
,REDIS_ZSET
)) return;
1220 addReplyLongLong(c
,zs
->zsl
->length
);
1223 void zscoreCommand(redisClient
*c
) {
1228 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
1229 checkType(c
,o
,REDIS_ZSET
)) return;
1232 c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
1233 de
= dictFind(zs
->dict
,c
->argv
[2]);
1235 addReply(c
,shared
.nullbulk
);
1237 double *score
= dictGetEntryVal(de
);
1239 addReplyDouble(c
,*score
);
1243 void zrankGenericCommand(redisClient
*c
, int reverse
) {
1251 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
1252 checkType(c
,o
,REDIS_ZSET
)) return;
1256 c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
1257 de
= dictFind(zs
->dict
,c
->argv
[2]);
1259 addReply(c
,shared
.nullbulk
);
1263 score
= dictGetEntryVal(de
);
1264 rank
= zslGetRank(zsl
, *score
, c
->argv
[2]);
1267 addReplyLongLong(c
, zsl
->length
- rank
);
1269 addReplyLongLong(c
, rank
-1);
1272 addReply(c
,shared
.nullbulk
);
1276 void zrankCommand(redisClient
*c
) {
1277 zrankGenericCommand(c
, 0);
1280 void zrevrankCommand(redisClient
*c
) {
1281 zrankGenericCommand(c
, 1);