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 inline int zslValueInMinRange(double value
, zrangespec
*spec
) {
184 return spec
->minex
? (value
> spec
->min
) : (value
>= spec
->min
);
187 static inline int zslValueInMaxRange(double value
, zrangespec
*spec
) {
188 return spec
->maxex
? (value
< spec
->max
) : (value
<= spec
->max
);
191 static inline int zslValueInRange(double value
, zrangespec
*spec
) {
192 return zslValueInMinRange(value
,spec
) && zslValueInMaxRange(value
,spec
);
195 /* Returns if there is a part of the zset is in range. */
196 int zslIsInRange(zskiplist
*zsl
, zrangespec
*range
) {
200 if (x
== NULL
|| !zslValueInMinRange(x
->score
,range
))
202 x
= zsl
->header
->level
[0].forward
;
203 if (x
== NULL
|| !zslValueInMaxRange(x
->score
,range
))
208 /* Find the first node that is contained in the specified range.
209 * Returns NULL when no element is contained in the range. */
210 zskiplistNode
*zslFirstInRange(zskiplist
*zsl
, zrangespec range
) {
214 /* If everything is out of range, return early. */
215 if (!zslIsInRange(zsl
,&range
)) return NULL
;
218 for (i
= zsl
->level
-1; i
>= 0; i
--) {
219 /* Go forward while *OUT* of range. */
220 while (x
->level
[i
].forward
&&
221 !zslValueInMinRange(x
->level
[i
].forward
->score
,&range
))
222 x
= x
->level
[i
].forward
;
225 /* The tail is in range, so the previous block should always return a
226 * node that is non-NULL and the last one to be out of range. */
227 x
= x
->level
[0].forward
;
228 redisAssert(x
!= NULL
&& zslValueInRange(x
->score
,&range
));
232 /* Find the last node that is contained in the specified range.
233 * Returns NULL when no element is contained in the range. */
234 zskiplistNode
*zslLastInRange(zskiplist
*zsl
, zrangespec range
) {
238 /* If everything is out of range, return early. */
239 if (!zslIsInRange(zsl
,&range
)) return NULL
;
242 for (i
= zsl
->level
-1; i
>= 0; i
--) {
243 /* Go forward while *IN* range. */
244 while (x
->level
[i
].forward
&&
245 zslValueInMaxRange(x
->level
[i
].forward
->score
,&range
))
246 x
= x
->level
[i
].forward
;
249 /* The header is in range, so the previous block should always return a
250 * node that is non-NULL and in range. */
251 redisAssert(x
!= NULL
&& zslValueInRange(x
->score
,&range
));
255 /* Delete all the elements with score between min and max from the skiplist.
256 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
257 * Note that this function takes the reference to the hash table view of the
258 * sorted set, in order to remove the elements from the hash table too. */
259 unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, zrangespec range
, dict
*dict
) {
260 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
261 unsigned long removed
= 0;
265 for (i
= zsl
->level
-1; i
>= 0; i
--) {
266 while (x
->level
[i
].forward
&& (range
.minex
?
267 x
->level
[i
].forward
->score
<= range
.min
:
268 x
->level
[i
].forward
->score
< range
.min
))
269 x
= x
->level
[i
].forward
;
273 /* Current node is the last with score < or <= min. */
274 x
= x
->level
[0].forward
;
276 /* Delete nodes while in range. */
277 while (x
&& (range
.maxex
? x
->score
< range
.max
: x
->score
<= range
.max
)) {
278 zskiplistNode
*next
= x
->level
[0].forward
;
279 zslDeleteNode(zsl
,x
,update
);
280 dictDelete(dict
,x
->obj
);
288 /* Delete all the elements with rank between start and end from the skiplist.
289 * Start and end are inclusive. Note that start and end need to be 1-based */
290 unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
291 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
292 unsigned long traversed
= 0, removed
= 0;
296 for (i
= zsl
->level
-1; i
>= 0; i
--) {
297 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) < start
) {
298 traversed
+= x
->level
[i
].span
;
299 x
= x
->level
[i
].forward
;
305 x
= x
->level
[0].forward
;
306 while (x
&& traversed
<= end
) {
307 zskiplistNode
*next
= x
->level
[0].forward
;
308 zslDeleteNode(zsl
,x
,update
);
309 dictDelete(dict
,x
->obj
);
318 /* Find the rank for an element by both score and key.
319 * Returns 0 when the element cannot be found, rank otherwise.
320 * Note that the rank is 1-based due to the span of zsl->header to the
322 unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
324 unsigned long rank
= 0;
328 for (i
= zsl
->level
-1; i
>= 0; i
--) {
329 while (x
->level
[i
].forward
&&
330 (x
->level
[i
].forward
->score
< score
||
331 (x
->level
[i
].forward
->score
== score
&&
332 compareStringObjects(x
->level
[i
].forward
->obj
,o
) <= 0))) {
333 rank
+= x
->level
[i
].span
;
334 x
= x
->level
[i
].forward
;
337 /* x might be equal to zsl->header, so test if obj is non-NULL */
338 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
345 /* Finds an element by its rank. The rank argument needs to be 1-based. */
346 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
348 unsigned long traversed
= 0;
352 for (i
= zsl
->level
-1; i
>= 0; i
--) {
353 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) <= rank
)
355 traversed
+= x
->level
[i
].span
;
356 x
= x
->level
[i
].forward
;
358 if (traversed
== rank
) {
365 /* Populate the rangespec according to the objects min and max. */
366 static int zslParseRange(robj
*min
, robj
*max
, zrangespec
*spec
) {
368 spec
->minex
= spec
->maxex
= 0;
370 /* Parse the min-max interval. If one of the values is prefixed
371 * by the "(" character, it's considered "open". For instance
372 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
373 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
374 if (min
->encoding
== REDIS_ENCODING_INT
) {
375 spec
->min
= (long)min
->ptr
;
377 if (((char*)min
->ptr
)[0] == '(') {
378 spec
->min
= strtod((char*)min
->ptr
+1,&eptr
);
379 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
382 spec
->min
= strtod((char*)min
->ptr
,&eptr
);
383 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
386 if (max
->encoding
== REDIS_ENCODING_INT
) {
387 spec
->max
= (long)max
->ptr
;
389 if (((char*)max
->ptr
)[0] == '(') {
390 spec
->max
= strtod((char*)max
->ptr
+1,&eptr
);
391 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
394 spec
->max
= strtod((char*)max
->ptr
,&eptr
);
395 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
403 /*-----------------------------------------------------------------------------
404 * Sorted set commands
405 *----------------------------------------------------------------------------*/
407 /* This generic command implements both ZADD and ZINCRBY. */
408 void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double score
, int incr
) {
411 zskiplistNode
*znode
;
413 zsetobj
= lookupKeyWrite(c
->db
,key
);
414 if (zsetobj
== NULL
) {
415 zsetobj
= createZsetObject();
416 dbAdd(c
->db
,key
,zsetobj
);
418 if (zsetobj
->type
!= REDIS_ZSET
) {
419 addReply(c
,shared
.wrongtypeerr
);
425 /* Since both ZADD and ZINCRBY are implemented here, we need to increment
426 * the score first by the current score if ZINCRBY is called. */
428 /* Read the old score. If the element was not present starts from 0 */
429 dictEntry
*de
= dictFind(zs
->dict
,ele
);
431 score
+= *(double*)dictGetEntryVal(de
);
434 addReplyError(c
,"resulting score is not a number (NaN)");
435 /* Note that we don't need to check if the zset may be empty and
436 * should be removed here, as we can only obtain Nan as score if
437 * there was already an element in the sorted set. */
442 /* We need to remove and re-insert the element when it was already present
443 * in the dictionary, to update the skiplist. Note that we delay adding a
444 * pointer to the score because we want to reference the score in the
446 if (dictAdd(zs
->dict
,ele
,NULL
) == DICT_OK
) {
450 incrRefCount(ele
); /* added to hash */
451 znode
= zslInsert(zs
->zsl
,score
,ele
);
452 incrRefCount(ele
); /* added to skiplist */
454 /* Update the score in the dict entry */
455 de
= dictFind(zs
->dict
,ele
);
456 redisAssert(de
!= NULL
);
457 dictGetEntryVal(de
) = &znode
->score
;
458 signalModifiedKey(c
->db
,c
->argv
[1]);
461 addReplyDouble(c
,score
);
463 addReply(c
,shared
.cone
);
471 de
= dictFind(zs
->dict
,ele
);
472 redisAssert(de
!= NULL
);
473 curobj
= dictGetEntryKey(de
);
474 curscore
= dictGetEntryVal(de
);
476 /* When the score is updated, reuse the existing string object to
477 * prevent extra alloc/dealloc of strings on ZINCRBY. */
478 if (score
!= *curscore
) {
479 deleted
= zslDelete(zs
->zsl
,*curscore
,curobj
);
480 redisAssert(deleted
!= 0);
481 znode
= zslInsert(zs
->zsl
,score
,curobj
);
482 incrRefCount(curobj
);
484 /* Update the score in the current dict entry */
485 dictGetEntryVal(de
) = &znode
->score
;
486 signalModifiedKey(c
->db
,c
->argv
[1]);
490 addReplyDouble(c
,score
);
492 addReply(c
,shared
.czero
);
496 void zaddCommand(redisClient
*c
) {
498 if (getDoubleFromObjectOrReply(c
,c
->argv
[2],&scoreval
,NULL
) != REDIS_OK
) return;
499 c
->argv
[3] = tryObjectEncoding(c
->argv
[3]);
500 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
503 void zincrbyCommand(redisClient
*c
) {
505 if (getDoubleFromObjectOrReply(c
,c
->argv
[2],&scoreval
,NULL
) != REDIS_OK
) return;
506 c
->argv
[3] = tryObjectEncoding(c
->argv
[3]);
507 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
510 void zremCommand(redisClient
*c
) {
517 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
518 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
521 c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
522 de
= dictFind(zs
->dict
,c
->argv
[2]);
524 addReply(c
,shared
.czero
);
527 /* Delete from the skiplist */
528 curscore
= *(double*)dictGetEntryVal(de
);
529 deleted
= zslDelete(zs
->zsl
,curscore
,c
->argv
[2]);
530 redisAssert(deleted
!= 0);
532 /* Delete from the hash table */
533 dictDelete(zs
->dict
,c
->argv
[2]);
534 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
535 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,c
->argv
[1]);
536 signalModifiedKey(c
->db
,c
->argv
[1]);
538 addReply(c
,shared
.cone
);
541 void zremrangebyscoreCommand(redisClient
*c
) {
547 /* Parse the range arguments. */
548 if (zslParseRange(c
->argv
[2],c
->argv
[3],&range
) != REDIS_OK
) {
549 addReplyError(c
,"min or max is not a double");
553 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
554 checkType(c
,o
,REDIS_ZSET
)) return;
557 deleted
= zslDeleteRangeByScore(zs
->zsl
,range
,zs
->dict
);
558 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
559 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,c
->argv
[1]);
560 if (deleted
) signalModifiedKey(c
->db
,c
->argv
[1]);
561 server
.dirty
+= deleted
;
562 addReplyLongLong(c
,deleted
);
565 void zremrangebyrankCommand(redisClient
*c
) {
573 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
574 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
576 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
577 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
579 llen
= zs
->zsl
->length
;
581 /* convert negative indexes */
582 if (start
< 0) start
= llen
+start
;
583 if (end
< 0) end
= llen
+end
;
584 if (start
< 0) start
= 0;
586 /* Invariant: start >= 0, so this test will be true when end < 0.
587 * The range is empty when start > end or start >= length. */
588 if (start
> end
|| start
>= llen
) {
589 addReply(c
,shared
.czero
);
592 if (end
>= llen
) end
= llen
-1;
594 /* increment start and end because zsl*Rank functions
595 * use 1-based rank */
596 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
597 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
598 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,c
->argv
[1]);
599 if (deleted
) signalModifiedKey(c
->db
,c
->argv
[1]);
600 server
.dirty
+= deleted
;
601 addReplyLongLong(c
, deleted
);
609 int qsortCompareZsetopsrcByCardinality(const void *s1
, const void *s2
) {
610 zsetopsrc
*d1
= (void*) s1
, *d2
= (void*) s2
;
611 unsigned long size1
, size2
;
612 size1
= d1
->dict
? dictSize(d1
->dict
) : 0;
613 size2
= d2
->dict
? dictSize(d2
->dict
) : 0;
614 return size1
- size2
;
617 #define REDIS_AGGR_SUM 1
618 #define REDIS_AGGR_MIN 2
619 #define REDIS_AGGR_MAX 3
620 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
622 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
623 if (aggregate
== REDIS_AGGR_SUM
) {
624 *target
= *target
+ val
;
625 /* The result of adding two doubles is NaN when one variable
626 * is +inf and the other is -inf. When these numbers are added,
627 * we maintain the convention of the result being 0.0. */
628 if (isnan(*target
)) *target
= 0.0;
629 } else if (aggregate
== REDIS_AGGR_MIN
) {
630 *target
= val
< *target
? val
: *target
;
631 } else if (aggregate
== REDIS_AGGR_MAX
) {
632 *target
= val
> *target
? val
: *target
;
635 redisPanic("Unknown ZUNION/INTER aggregate type");
639 void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
641 int aggregate
= REDIS_AGGR_SUM
;
645 zskiplistNode
*znode
;
650 /* expect setnum input keys to be given */
651 setnum
= atoi(c
->argv
[2]->ptr
);
654 "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
658 /* test if the expected number of keys would overflow */
659 if (3+setnum
> c
->argc
) {
660 addReply(c
,shared
.syntaxerr
);
664 /* read keys to be used for input */
665 src
= zmalloc(sizeof(zsetopsrc
) * setnum
);
666 for (i
= 0, j
= 3; i
< setnum
; i
++, j
++) {
667 robj
*obj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
671 if (obj
->type
== REDIS_ZSET
) {
672 src
[i
].dict
= ((zset
*)obj
->ptr
)->dict
;
673 } else if (obj
->type
== REDIS_SET
) {
674 src
[i
].dict
= (obj
->ptr
);
677 addReply(c
,shared
.wrongtypeerr
);
682 /* default all weights to 1 */
686 /* parse optional extra arguments */
688 int remaining
= c
->argc
- j
;
691 if (remaining
>= (setnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
693 for (i
= 0; i
< setnum
; i
++, j
++, remaining
--) {
694 if (getDoubleFromObjectOrReply(c
,c
->argv
[j
],&src
[i
].weight
,
695 "weight value is not a double") != REDIS_OK
)
701 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
703 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
704 aggregate
= REDIS_AGGR_SUM
;
705 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
706 aggregate
= REDIS_AGGR_MIN
;
707 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
708 aggregate
= REDIS_AGGR_MAX
;
711 addReply(c
,shared
.syntaxerr
);
717 addReply(c
,shared
.syntaxerr
);
723 /* sort sets from the smallest to largest, this will improve our
724 * algorithm's performance */
725 qsort(src
,setnum
,sizeof(zsetopsrc
),qsortCompareZsetopsrcByCardinality
);
727 dstobj
= createZsetObject();
728 dstzset
= dstobj
->ptr
;
730 if (op
== REDIS_OP_INTER
) {
731 /* skip going over all entries if the smallest zset is NULL or empty */
732 if (src
[0].dict
&& dictSize(src
[0].dict
) > 0) {
733 /* precondition: as src[0].dict is non-empty and the zsets are ordered
734 * from small to large, all src[i > 0].dict are non-empty too */
735 di
= dictGetIterator(src
[0].dict
);
736 while((de
= dictNext(di
)) != NULL
) {
739 score
= src
[0].weight
* zunionInterDictValue(de
);
740 for (j
= 1; j
< setnum
; j
++) {
741 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
743 value
= src
[j
].weight
* zunionInterDictValue(other
);
744 zunionInterAggregate(&score
,value
,aggregate
);
750 /* Only continue when present in every source dict. */
752 robj
*o
= dictGetEntryKey(de
);
753 znode
= zslInsert(dstzset
->zsl
,score
,o
);
754 incrRefCount(o
); /* added to skiplist */
755 dictAdd(dstzset
->dict
,o
,&znode
->score
);
756 incrRefCount(o
); /* added to dictionary */
759 dictReleaseIterator(di
);
761 } else if (op
== REDIS_OP_UNION
) {
762 for (i
= 0; i
< setnum
; i
++) {
763 if (!src
[i
].dict
) continue;
765 di
= dictGetIterator(src
[i
].dict
);
766 while((de
= dictNext(di
)) != NULL
) {
769 /* skip key when already processed */
770 if (dictFind(dstzset
->dict
,dictGetEntryKey(de
)) != NULL
)
773 /* initialize score */
774 score
= src
[i
].weight
* zunionInterDictValue(de
);
776 /* because the zsets are sorted by size, its only possible
777 * for sets at larger indices to hold this entry */
778 for (j
= (i
+1); j
< setnum
; j
++) {
779 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
781 value
= src
[j
].weight
* zunionInterDictValue(other
);
782 zunionInterAggregate(&score
,value
,aggregate
);
786 robj
*o
= dictGetEntryKey(de
);
787 znode
= zslInsert(dstzset
->zsl
,score
,o
);
788 incrRefCount(o
); /* added to skiplist */
789 dictAdd(dstzset
->dict
,o
,&znode
->score
);
790 incrRefCount(o
); /* added to dictionary */
792 dictReleaseIterator(di
);
795 /* unknown operator */
796 redisAssert(op
== REDIS_OP_INTER
|| op
== REDIS_OP_UNION
);
799 if (dbDelete(c
->db
,dstkey
)) {
800 signalModifiedKey(c
->db
,dstkey
);
804 if (dstzset
->zsl
->length
) {
805 dbAdd(c
->db
,dstkey
,dstobj
);
806 addReplyLongLong(c
, dstzset
->zsl
->length
);
807 if (!touched
) signalModifiedKey(c
->db
,dstkey
);
810 decrRefCount(dstobj
);
811 addReply(c
, shared
.czero
);
816 void zunionstoreCommand(redisClient
*c
) {
817 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
820 void zinterstoreCommand(redisClient
*c
) {
821 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
824 void zrangeGenericCommand(redisClient
*c
, int reverse
) {
836 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
837 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
839 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
841 } else if (c
->argc
>= 5) {
842 addReply(c
,shared
.syntaxerr
);
846 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
847 || checkType(c
,o
,REDIS_ZSET
)) return;
852 /* convert negative indexes */
853 if (start
< 0) start
= llen
+start
;
854 if (end
< 0) end
= llen
+end
;
855 if (start
< 0) start
= 0;
857 /* Invariant: start >= 0, so this test will be true when end < 0.
858 * The range is empty when start > end or start >= length. */
859 if (start
> end
|| start
>= llen
) {
860 addReply(c
,shared
.emptymultibulk
);
863 if (end
>= llen
) end
= llen
-1;
864 rangelen
= (end
-start
)+1;
866 /* check if starting point is trivial, before searching
867 * the element in log(N) time */
869 ln
= start
== 0 ? zsl
->tail
: zslGetElementByRank(zsl
, llen
-start
);
872 zsl
->header
->level
[0].forward
: zslGetElementByRank(zsl
, start
+1);
875 /* Return the result in form of a multi-bulk reply */
876 addReplyMultiBulkLen(c
,withscores
? (rangelen
*2) : rangelen
);
877 for (j
= 0; j
< rangelen
; j
++) {
881 addReplyDouble(c
,ln
->score
);
882 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
886 void zrangeCommand(redisClient
*c
) {
887 zrangeGenericCommand(c
,0);
890 void zrevrangeCommand(redisClient
*c
) {
891 zrangeGenericCommand(c
,1);
894 /* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE and ZCOUNT.
895 * If "justcount", only the number of elements in the range is returned. */
896 void genericZrangebyscoreCommand(redisClient
*c
, int reverse
, int justcount
) {
898 robj
*o
, *emptyreply
;
902 int offset
= 0, limit
= -1;
904 unsigned long rangelen
= 0;
905 void *replylen
= NULL
;
908 /* Parse the range arguments. */
910 /* Range is given as [max,min] */
911 maxidx
= 2; minidx
= 3;
913 /* Range is given as [min,max] */
914 minidx
= 2; maxidx
= 3;
917 if (zslParseRange(c
->argv
[minidx
],c
->argv
[maxidx
],&range
) != REDIS_OK
) {
918 addReplyError(c
,"min or max is not a double");
922 /* Parse optional extra arguments. Note that ZCOUNT will exactly have
923 * 4 arguments, so we'll never enter the following code path. */
925 int remaining
= c
->argc
- 4;
929 if (remaining
>= 1 && !strcasecmp(c
->argv
[pos
]->ptr
,"withscores")) {
932 } else if (remaining
>= 3 && !strcasecmp(c
->argv
[pos
]->ptr
,"limit")) {
933 offset
= atoi(c
->argv
[pos
+1]->ptr
);
934 limit
= atoi(c
->argv
[pos
+2]->ptr
);
935 pos
+= 3; remaining
-= 3;
937 addReply(c
,shared
.syntaxerr
);
943 /* Ok, lookup the key and get the range */
944 emptyreply
= justcount
? shared
.czero
: shared
.emptymultibulk
;
945 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],emptyreply
)) == NULL
||
946 checkType(c
,o
,REDIS_ZSET
)) return;
950 /* If reversed, get the last node in range as starting point. */
952 ln
= zslLastInRange(zsl
,range
);
954 ln
= zslFirstInRange(zsl
,range
);
957 /* No "first" element in the specified interval. */
959 addReply(c
,emptyreply
);
963 /* We don't know in advance how many matching elements there are in the
964 * list, so we push this object that will represent the multi-bulk length
965 * in the output buffer, and will "fix" it later */
967 replylen
= addDeferredMultiBulkLength(c
);
969 /* If there is an offset, just traverse the number of elements without
970 * checking the score because that is done in the next loop. */
971 while(ln
&& offset
--) {
972 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
975 while (ln
&& limit
--) {
976 /* Abort when the node is no longer in range. */
978 if (!zslValueInMinRange(ln
->score
,&range
)) break;
980 if (!zslValueInMaxRange(ln
->score
,&range
)) break;
986 addReplyBulk(c
,ln
->obj
);
988 addReplyDouble(c
,ln
->score
);
991 /* Move to next node */
992 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
996 addReplyLongLong(c
,(long)rangelen
);
998 setDeferredMultiBulkLength(c
,replylen
,
999 withscores
? (rangelen
*2) : rangelen
);
1003 void zrangebyscoreCommand(redisClient
*c
) {
1004 genericZrangebyscoreCommand(c
,0,0);
1007 void zrevrangebyscoreCommand(redisClient
*c
) {
1008 genericZrangebyscoreCommand(c
,1,0);
1011 void zcountCommand(redisClient
*c
) {
1012 genericZrangebyscoreCommand(c
,0,1);
1015 void zcardCommand(redisClient
*c
) {
1019 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
1020 checkType(c
,o
,REDIS_ZSET
)) return;
1023 addReplyLongLong(c
,zs
->zsl
->length
);
1026 void zscoreCommand(redisClient
*c
) {
1031 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
1032 checkType(c
,o
,REDIS_ZSET
)) return;
1035 c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
1036 de
= dictFind(zs
->dict
,c
->argv
[2]);
1038 addReply(c
,shared
.nullbulk
);
1040 double *score
= dictGetEntryVal(de
);
1042 addReplyDouble(c
,*score
);
1046 void zrankGenericCommand(redisClient
*c
, int reverse
) {
1054 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
1055 checkType(c
,o
,REDIS_ZSET
)) return;
1059 c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
1060 de
= dictFind(zs
->dict
,c
->argv
[2]);
1062 addReply(c
,shared
.nullbulk
);
1066 score
= dictGetEntryVal(de
);
1067 rank
= zslGetRank(zsl
, *score
, c
->argv
[2]);
1070 addReplyLongLong(c
, zsl
->length
- rank
);
1072 addReplyLongLong(c
, rank
-1);
1075 addReply(c
,shared
.nullbulk
);
1079 void zrankCommand(redisClient
*c
) {
1080 zrankGenericCommand(c
, 0);
1083 void zrevrankCommand(redisClient
*c
) {
1084 zrankGenericCommand(c
, 1);