Database Reference
In-Depth Information
implement “any” or “all” variants of membership queries, multiple
SISMEMBER
commands must be issued, which is accomplished using Redis'
scripting capabilities, discussed later in this section.
Redis also supports set operations between different set objects in the
database. The
SUNION
,
SINTER
, and
SDIFF
commands return a bulk reply
containing, respectively, the union, intersection, or difference of two sets.
It is also possible to store the result into another set by adding the
STORE
modifier to each of the commands. For example, to store the union of two
sets into a third set, you use the
SUNIONSTORE
command. You can obtain
the size of any set using the
SCARD
command.
Sorted Sets add a score to each element of the set, which defines the sort
order for the elements within the set. This is useful for maintaining
leaderboards and other similar structures. Generally, the commands for
updating a sorted set are the same as those used for a normal set, but
prefixed by a
Z
instead of an
S
and taking an extra “score” argument. In
the case of the
ZADD
command, the score comes before each element to be
added. If the element already exists, the existing score is updated with the
new score.
The union and intersection operations are supported by sorted sets as the
ZUNIONSTORE
and
ZINTERSTORE
commands. These operations work a bit
differently than their unsorted counterparts because they have to handle the
possibility of a shared element having two different scores. Both operations
take an optional
WEIGHTS
parameter, which defines a multiplicative factor
to apply to the score of each set. For example,
WEIGHTS 2 3
would
multiply the first set's scores by 2 and the second set's scores by 3. By
default, these two scores would be added together for each element present
in both sets. This can be modified by the optional
AGGREGATE
parameter.
This parameter takes a value of
SUM
(the default),
MIN
, or
MAX
. When
SUM
is
selected the scores of elements contained in two or more sets will be added
together after their weight has been applied. When
MIN
is used, the smallest
weighted value is used. For
MAX
, the largest weighted value is used.
Sorted sets introduce a few new commands related to using the scores
associated with each element. The
ZINCRBY
command increments the score
of an element in the set. If the element is not present, it is assumed to have
a score of 0.0 and is inserted into the sorted set at that time.