sider.sortedset — Sorted sets

See also

Redis Data Types
The Redis documentation that explains about its data types: strings, lists, sets, sorted sets and hashes.
class sider.sortedset.SortedSet(session, key, value_type=<class 'sider.types.ByteString'>)

The Python-sider representation of Redis sorted set value. It behaves in similar way to collections.Counter object which became a part of standard library since Python 2.7.

It implements collections.MutableMapping and collections.MutableSet protocols.

Mappings of Redis commands–SortedSet methods
Redis commands SortedSet methods
DEL SortedSet.clear()
ZADD = (SortedSet.__setitem__())
ZCARD len() (SortedSet.__len__())
ZINCRBY SortedSet.add(), SortedSet.discard(), SortedSet.update()
ZRANGE iter() (SortedSet.__iter__())
ZRANGE WITHSCORES SortedSet.items(), SortedSet.most_common(), SortedSet.least_common()
ZREM del (SortedSet.__delitem__()), SortedSet.discard()
ZSCORE SortedSet.__getitem__(), in (SortedSet.__contains__())
ZUNIONSTORE SortedSet.update()
N/A SortedSet.setdefault()
N/A SortedSet.pop()
N/A SortedSet.popitem()
__contains__(*args, **kwargs)

in operator. Tests whether the set contains the given operand member.

Parameters:member – the value to test
Returns:True if the sorted set contains the given operand member
Return type:bool

Note

This method internally uses ZSCORE command.

__delitem__(member)

Removes the member.

Parameters:

member – the member to delete

Raises:

Note

It is directly mapped to Redis ZREM command when it’s not on transaction. If it’s used with transaction, it internally uses ZSCORE and ZREM commands.

__getitem__(*args, **kwargs)

Gets the score of the given member.

Parameters:

member – the member to get its score

Returns:

the score of the member

Return type:

numbers.Real

Raises:

Note

It is directly mapped to Redis ZSCORE command.

__len__(*args, **kwargs)

Gets the cardinality of the sorted set.

Returns:the cardinality (the number of elements) of the sorted set
Return type:numbers.Integral

Note

It is directly mapped to Redis ZCARD command.

__setitem__(*args, **kwargs)

Sets the score of the member. Adds the member if it doesn’t exist.

Parameters:
  • member – the member to set its score
  • scorew – the score to set of the member
Raises exceptions.TypeError:
 

if the given member is not acceptable by its value_type or the given score is not a numbers.Real object

Note

It is directly mapped to Redis ZADD command.

add(*args, **kwargs)

Adds a new member or increases its score (default is 1).

Parameters:
  • member – the member to add or increase its score
  • score (numbers.Real) – the amount to increase the score. default is 1

Note

This method is directly mapped to ZINCRBY command.

clear(*args, **kwargs)

Removes all values from this sorted set.

Note

Under the hood it simply DEL the key.

discard(member, score=1, remove=0)

Opposite operation of add(). It decreases its score (default is 1). When its score get the remove number (default is 0) or less, it will be removed.

If you don’t want to remove it but only decrease its score, pass None into remove parameter.

If you want to remove member, not only decrease its score, use __delitem__() instead:

del sortedset[member]
Parameters:
  • member – the member to decreases its score
  • score (numbers.Real) – the amount to decrease the score. default is 1
  • remove (numbers.Real) – the threshold score to be removed. if None is passed, it doesn’t remove the member but only decreases its score (it makes score argument meaningless). default is 0.

Note

This method is directly mapped to ZINCRBY command when remove is None.

Otherwise, it internally uses ZSCORE plus ZINCRBY or :redis:`ZREM (total two commands) within a transaction.

items(*args, **kwargs)

Returns an ordered of pairs of elements and these scores.

Parameters:reverse (bool) – order result descendingly if it’s True. default is False which means ascending order
Returns:an ordered list of pairs. every pair looks like (element, score)
Return type:collections.Sequence

Note

This method is directly mapped to ZRANGE command and WITHSCORES option.

keys(reverse=False)

Gets its all elements. Equivalent to __iter__() except it returns an ordered Sequence instead of iterable.

Parameters:reverse (bool) – order result descendingly if it’s True. default is False which means ascending order
Returns:the ordered list of its all keys
Return type:collections.Sequence

Note

This method is directly mapped to Redis ZRANGE command.

least_common(*args, **kwargs)

Returns a list of the n least common (exactly, lowly scored) members and their counts (scores) from the least common to the most. If n is not specified, it returns all members in the set. Members with equal scores are ordered arbitarily.

Parameters:n (numbers.Integral) – the number of members to get
Returns:an ordered list of pairs. every pair looks like (element, score)
Return type:collections.Sequence

Note

This method is directly mapped to ZREVRANGE command and WITHSCORES option.

most_common(n=None, reverse=False)

Returns a list of the n most common (exactly, highly scored) members and their counts (scores) from the most common to the least. If n is not specified, it returns all members in the set. Members with equal scores are ordered arbitarily.

Parameters:n (numbers.Integral) – the number of members to get
Returns:an ordered list of pairs. every pair looks like (element, score)
Return type:collections.Sequence

Note

This method is directly mapped to ZRANGE command and WITHSCORES option.

pop(*args, **kwargs)

Populates a member of the set.

If key keyword argument or one or more positional arguments have present, it behaves like dict.pop() method:

Parameters:
  • key – the member to populate. it will be removed if it exists
  • default – the default value returned instead of the member (key) when it doesn’t exist. default is None
Returns:

the score of the member before the operation has been committed

Return type:

numbers.Real

Note

It internally uses ZSCORE, ZREM or ZINCRBY (total 2 commands) in a transaction.

If no positional arguments or no key keyword argument, it behaves like set.pop() method. Basically it does the same thing with popitem() except it returns just a popped value (while popitem() returns a pair of popped value and its score).

Parameters:desc (bool) – keyword only. by default, it populates the member of the lowest score, but if you pass True to this it will populates the highest instead. default is False
Returns:the populated member. it will be the lowest scored member or the highest scored member if desc is True
Raises exceptions.KeyError:
 when the set is empty

Note

It internally uses ZRANGE or ZREVRANGE, ZREM or ZINCRBY (total 2 commands) in a transaction.

See also

Method popitem()

If any case there are common keyword-only parameters:

Parameters:
  • score (numbers.Real) – keyword only. the amount to decrease the score. default is 1
  • remove (numbers.Real) – keyword only. the threshold score to be removed. if None is passed, it doesn’t remove the member but only decreases its score (it makes score argument meaningless). default is 0.
popitem(desc=False, score=1, remove=0)

Populates the lowest scored member (or the highest if desc is True) and its score.

It returns a pair of the populated member and its score. The score is a value before the operation has been committed.

Parameters:
  • desc (bool) – by default, it populates the member of the lowest score, but if you pass True to this parameter it will populates the highest instead. default is False
  • score (numbers.Real) – the amount to decrease the score. default is 1
  • remove (numbers.Real) – the threshold score to be removed. if None is passed, it doesn’t remove the member but only decreases its score (it makes score argument meaningless). default is 0.
Returns:

a pair of the populated member and its score. the first part of a pair will be the lowest scored member or the highest scored member if desc is True. the second part of a pair will be the score before the operation has been committed

Return type:

tuple

Raises exceptions.KeyError:
 

when the set is empty

Note

It internally uses ZRANGE or ZREVRANGE, ZREM or ZINCRBY (total 2 commands) in a transaction.

See also

Method pop()

setdefault(key, default=1)

Gets the score of the given key if it exists or adds key with default score.

Parameters:
  • key – the member to get its score
  • default (numbers.Real) – the score to be set if the key doesn’t exist. default is 1
Returns:

the score of the key after the operation has been committed

Return type:

numbers.Real

Note

It internally uses one or two commands. At first it sends ZSCORE command to check whether the key exists and get its score if it exists. If it doesn’t exist yet, it sends one more command: ZADD. It is atomically committed in a transaction.

update(*sets, **keywords)

Merge with passed sets and keywords. It’s behavior is almost equivalent to dict.update() and set.update() except it’s aware of scores.

For example, assume the initial elements and their scores of the set is (in notation of dictionary):

{'c': 1, 'a': 2, 'b': 3}

and you has updated it:

sortedset.update(set('acd'))

then it becomes (in notation of dictionary):

{'d': 1, 'c': 2, 'a': 3, 'b': 3}

You can pass mapping objects or keywords instead to specify scores to increment:

sortedset.update({'a': 1, 'b': 2})
sortedset.update(a=1, b=2)
sortedset.update(set('ab'), set('cd'),
                 {'a': 1, 'b': 2}, {'c': 1, 'd': 2},
                 a=1, b=2, c=1, d=2)
Parameters:
  • *sets – sets or mapping objects to merge with. mapping objects can specify scores by values
  • **keywords – if value_type takes byte strings you can specify elements and its scores by keyword arguments

Note

There’s an incompatibility with dict.update(). It always treats iterable of pairs as set of pairs, not mapping pairs, unlike dict.update(). It is for resolving ambiguity (remember value_type can take tuples or such things).

Note

Under the hood it uses multiple ZINCRBY commands and ZUNIONSTORE if there are one or more SortedSet objects in operands.

value_type = None

(sider.types.Bulk) The type of set elements.

values(*args, **kwargs)

Returns an ordered list of scores.

Parameters:reverse (bool) – order result descendingly if it’s True. default is False which means ascending order
Returns:an ordered list of scores
Return type:collections.Sequence

Note

This method internally uses ZRANGE command and WITHSCORES option.