You have to work really hard to look effortless!

Wechat search public number [long Coding road], together From Zero To Hero!

preface

Sorted a Set is a mixed data type similar to a List and Hash. Like a set, an ordered set consists of unique, non-repeating string elements, so in a sense an ordered set is also a set. But the elements in the set are not sorted. Each element in an ordered set is associated with a floating-point value, called a fraction, and the elements in the set are sorted by fraction size. Ordered collections are also similar to hash data types because each element maps to a value (fraction).

The ordering rules of ordered sets are as follows:

  • Two elements A and B have different scores, ifA.Score>B.Score, thenA>B
  • A and B have the same number of elements, if the string is ordered lexicographicallyA>B, thenA>B

ZADD

Available version: >= 1.2.0

Time complexity: M*O(log(N)), where M is the number of new elements and N is the number of existing elements in the ordered set

The command format

ZADD key [NX|XX] [GT|LT] [CH] [INCR] score member [score member ...]
Copy the code

Command description

  • Will one or moremember,scoreData pairs are added tokeyThe corresponding ordered set
  • If the specifiedmemberThe score is updated and reinserted when it already exists in the ordered setmemberElement to ensure that the element is in the correct position
  • ifkeyThe corresponding ordered set does not exist, and an empty ordered set is created first
  • scoreCan be a string representation of an integer or a double floating-point number,+inf-infIt’s a valid value.
  • ifkeyThe corresponding value type is notSorted SetTo return to the Error

Optional parameters

  • XX: only the existing elements are updated, and no new elements are added
  • NX: Add new elements, not update existing elements
  • LT: New elements will be added; For existing elements, when newscorevalueLess thanThe currentscoreValue is updated
  • GT: New elements are added; For existing elements, when newscorevalueIs greater thanThe currentscoreValue is updated
  • CH: Changes the calculation logic of the return value. By default, the number of newly added elements is returned. If this parameter is provided, the number of changed elements is returned: the sum of the number of newly added elements and the number of elements whose score value is updated. If the element already exists and the new Score value is the same as the current score value, it will not be counted
  • INCR: the command after this parameter is provided is similarZINCRBYTo add a value to the score, only one member and score are allowed

Note: The GT, LT, and NX options are mutually exclusive.

Integer value Score range

Ordered collections represent the score value as a 64-bit floating-point number of type double and can represent integers from -(2^53) to +(2^53). In more practical applications, all integers between -9007199254740992 and 9007199254740992 are perfectly represented. Larger integers or fractions are expressed exponentially, so it is possible to get only larger integers or approximate floating point numbers.

The return value

  • Integer values:
    • Return the number of new elements (excluding elements updated with score) when no optional parameter is provided.
    • provideCHParameter, returns the number of elements changed (new and updated)
  • String: providedINCRParameter that returns a string
    • The updated element is newscorevalue
    • NX,XXParameter is not updated, returns nil

The sample

#1. Do not add elements with optional parameters
127.0.0.1:6379> zadd myzset 1 one
(integer) 1
127.0.0.1:6379> zadd myzset 2 two
(integer) 1
#Iterating over the element does not return score127.0.0.1:6379> ZRANGE myzset 0-1 1) "one" 2) "two"#Iterating over the element, returning score127.0.0.1:6379> ZRANGE myzset 0-1 WITHSCORES 1) "one" 2) "1" 3) "two" 4) "2"

#2. Add the same element repeatedly, and the Score will be updated
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> zadd myzset 1 one
(integer) 1
#The number of new elements is returned by default127.0.0.1:6379> zadd myzset 2 one (integer) 0 127.0.0.1:6379> ZRANGE myzset 0-1 WITHSCORES 1) "one" 2) "2"#Add the CH argument to return the number of elements changed127.0.0.1:6379> zadd myzset ch 3 one (integer) 1 127.0.0.1:6379> ZRANGE myzset 0-1 WITHSCORES 1) "one" 2) "3"

#3. The NX parameters127.0.0.1:6379> flushdb OK 127.0.0.1:6379> zadd myzset 1 one (integer) 1 127.0.0.1:6379> zadd myzset NX 2 one 0 127.0.0.1:6379> ZRANGE myzset 0-1 WITHSCORES 1) "one" 2) "1"
#4. XX parameters
127.0.0.1:6379> zadd myzset 3 three
(integer) 1
#Four does not exist, adding failed127.0.0.1:6379> zadd myzset XX 4 (INTEGER) 0#Three already exists and can be added successfully127.0.0.1:6379> zadd myzset XX 3.1 three (integer) 0 127.0.0.1:6379> zrange myzset 0-1 withscores 1) "one" 2) "1" 3) "Three" 4) "3.1000000000000001"

#GT and LT parameters
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> zadd myzset 5 five
(integer) 1
127.0.0.1:6379> zadd myzset 6 six
(integer) 1
#GT: 4 is not greater than 5. The update fails
127.0.0.1:6379>  zadd myzset GT 4 five
(integer) 0
#LT: 4 < 5, update succeeded127.0.0.1:6379> zadd myzset LT 4 six (integer) 0 127.0.0.1:6379> zrange myzset 0-1 withscores 1) "six" 2) "4" 3) "five" 4) "5"Copy the code

ZSCORE

Available version: >= 1.2.0

Time complexity: O(1)

The command format

ZSCORE key member
Copy the code

Command description

  • returnkeyIn the corresponding ordered set,memberThe correspondingscorevalue
  • If the set doesn’t exist, ormemberNot in the set, return nil

The return value

String: Score value corresponding to member

The sample

127.0.0.1:6379> zadd myset 18 user1:age (INTEGER) 1 127.0.0.1:1 > zscore myset user1:age "18"#Member does not exist
127.0.0.1:6379> zscore myset user0:age
(nil)
Copy the code

ZCARD

Available version: >= 1.2.0

Time complexity: O(1)

The command format

ZCARD key
Copy the code

Command description

  • returnkeyCardinality (length) of the corresponding ordered set

The return value

Integer value: ordered set length or 0 (ordered set does not exist)

The sample

127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> zadd myset 1 one
(integer) 1
127.0.0.1:6379> zadd myset 2 two
(integer) 1
127.0.0.1:6379> zcard myset
(integer) 2
Copy the code

ZCOUNT

Available versions: >= 2.0.0

Time complexity: O(log(N)), where N is the number of elements in an ordered array

The command format

ZCOUNT key min max
Copy the code

Command description

  • returnkeyIn the corresponding ordered set,scoreValues in theminmaxNumber of elements between

The return value

Integer value: number of elements

The sample

127.0.0.1:6379> zadd myzset 1 one
(integer) 1
127.0.0.1:6379> zadd myzset 2 two
(integer) 1
127.0.0.1:6379> zadd myzset 3 three
(integer) 1
127.0.0.1:6379> zadd myzset 4 four
(integer) 1

#There are three between 2 and 4
127.0.0.1:6379> zcount myzset 2 4
(integer) 3
Copy the code

ZRANGE

Available version: >= 1.2.0

Time complexity: O(log(N)+M), N is the number of elements in the ordered array, M is the number of returned elements

The command changes

REV, BYSCORE, BYLEX and LIMIT parameters have been added since version 6.2.0

The command format

ZRANGE key min max [BYSCORE|BYLEX] [REV] [LIMIT offset count] [WITHSCORES]
Copy the code

Command description

  • returnkeyThe elements in a specific range of the corresponding ordered set
  • ZRANGE can perform different types of range queries: according to index, score, and lexicographical order
  • Since version 6.2.0,ZRANGEYou can replace the following commandZREVRANGE,ZRANGEBYSCORE,ZREVRANGEBYSCORE,ZRANGEBYLEXZREVRANGEBYLEX

Common behaviors and options

By default, elements are sorted from lowest to highest score, and elements of the same score are sorted in lexicographical ascending order.

  • REV: reverse the sort, that is, from large to small, the dictionary order will also be reversed;
  • LIMIT: Returns a subset of the result set fromoffsetPosition starts to returncountValue (similar to * in SQLSELECT LIMIT offset, count*), which is returned when count is negativeoffsetEverything after that. Note: This parameter must be used together with BYSCORE or BYLEX. At the same time, Redis needs to iterate through offset elements to get the return value. If the offset is large, the complexity may reach O(N).
  • WITHSCORES: Returns the score value along with the element. Format for value1, score1,… , valueN scoreN;

The index is used as the query scope

  • By default, the index is used as the range of returned elements.minandmaxIs the index range, 0 for the first element, 1 for the second element, and so on; These elements are returned in descending order of score. Since Redis defaults to order from lowest to highest, this command returns minth-max elements
  • The beginning and end of the range are closed intervals, that is, [min, Max];
  • The index can also be negative, with -1 for the last element, -2 for the penultimate element, and so on;
  • No error will be reported if the given index is out of the list range:
    • If min is greater than the maximum index of the list or greater than Max, return an empty collection
    • If Max is greater than the maximum index of the list, Redis sets Max = maximum index

The score is used as the query scope

  • When using theBYSCOREParameter, elements whose score values are between min and Max are returned in descending order of score;
  • Min and Max could be-inf+infWhich means minus infinity and plus infinity;
  • By default, both left and right are closed intervals, i.e., [min, Max]. If you want to use an open interval, you can add the ‘(‘ sign before the index
    • ZRANGE zset (1 5 BYSCORE)
    • ZRANGE zset (5 (10) BYSCORE returns (5,10)

The lexicographical order is used as the query scope

  • When using theBYLEXParameter, will return elements between min and Max in lexicographically sorted order, in descending order of score;
  • This parameter should be used only when all elements in an ordered array have the same score value. When the score is different, the return result of this command is uncertain;
  • Before min or Max, you need to provide the ‘(‘ or ‘[‘ sign to indicate an open or closed interval;
  • For min or Max, you can use the ‘+’ or ‘-‘ symbol to indicate a plus or minus infinity string; When all elements in an ordered collection have the same score value, useZRANGEBYLEX myzset - *Returns all elements;

The return value

Array: a list of elements in a range (if the WITHSCORES parameter is used, score is returned as well)

The sample

#Insert four pieces of data
127.0.0.1:6379> zadd myset 1 one
(integer) 1
127.0.0.1:6379> zadd myset 2 two
(integer) 1
127.0.0.1:6379> zadd myset 4 four
(integer) 1
127.0.0.1:6379> zadd myset 3 three
(integer) 1

#Default by index127.0.0.1:6379> zrange myset 0-1 1) "one" 2) "two" 3) "three" 4) "four"
#Default by index127.0.0.1:6379> zrange myset 0-1 1) "one" 2) "two" 3) "three" 4) "four"
#Default by index127.0.0.1:6379> zrange myset 12 1) "two" 2) "three"
#REV parameter, returned in descending order127.0.0.1:6379> zrange myset 0-1 rev 1) "four" 2) "three" 3) "two" 4) "one"
#WITHSCORES parameters127.0.0.1:6379> zrange myset 0-1 withscores 1) "one" 2) "1" 3) "two" 4) "2" 5) "three" 6) "3" 7) "four" 8) "4"
#Return elements with score values between [1,3]
127.0.0.1:6379> zrange myset 1 3 byscore
1) "one"
2) "two"
3) "three"

#Returns elements with a score value of [1,3]
127.0.0.1:6379> zrange myset 1 (3 byscore
1) "one"
2) "two"

#Byscore, combined with the LIMIT offset count parameter127.0.0.1:6379> zrange myset 1 3 byscore limit 12 1) "two" 2) "three"
#Use the BYLEX parameter
127.0.0.1:6379> zrange myset [a (p bylex
1) "one"
Copy the code

ZRANGEBYSCORE

Available versions: >= 1.0.5

Time complexity: O(log(N)+M), N is the number of elements in the ordered array, M is the number of returned elements

The command format

ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
Copy the code

Command description

  • Return score value betweenminandmaxIn order from lowest to highest, and those with the same score are ordered lexicographically
  • LIMIT: Returns a subset of the result set fromoffsetPosition starts to returncountValue (similar to * in SQLSELECT LIMIT offset, count*), which is returned when count is negativeoffsetEverything after that. Note: When using this parameter, Redis needs to iterate through offset elements to get the return value. If the offset is large, the complexity may reach O(N).
  • WITHSCORES: Returns the score value along with the element.

After version 6.2.0, this command is considered to be deprecated. It is recommended to use the ZRANGE command with BYSCORE parameter.

Open and close range

  • By default, both left and right are closed intervals, i.e., [min, Max]. If you want to use an open interval, you can add the ‘(‘ sign before the index

    • ZRANGE zset (1 5 BYSCORE)

    • ZRANGE zset (5 (10) BYSCORE returns (5,10)

  • Min and Max can be -INF and + INF, which means minus infinity and plus infinity

The return value

Array: An array of elements in a range sorted in ascending order by fraction

The sample

127.0.0.1:6379> zadd myzset 1 one
(integer) 1
127.0.0.1:6379> zadd myzset 2 two
(integer) 1
127.0.0.1:6379> zadd myzset 3 three
(integer) 1

#Return all elements127.0.0.1:6379> zrangebyScore myzset - INF + INF 1) "one" 2) "two" 3) "three"
#With the WITHSCORES parameter
127.0.0.1:6379> zrangebyscore myzset -inf +inf withscores
1) "one"
2) "1"
3) "two"
4) "2"
5) "three"
6) "3"

127.0.0.1:6379> zrangebyscore myzset 2 3
1) "two"
2) "three"

#Left on the right off
127.0.0.1:6379> zrangebyscore myzset (2 3
1) "three"
Copy the code

ZRANGEBYLEX

Available version: >= 2.8.9

Time complexity: O(log(N)+M), N is the number of elements in the ordered array, M is the number of returned elements

The command format

ZRANGEBYLEX key min max [LIMIT offset count]
Copy the code

Command description

  • When all the elements in an ordered array have the same score value, this command sorts the elements in lexicographical order, and returns the elements between min and Max in ascending order by default.
  • If the score values are different, the returned elements are uncertain;
  • The memcmp() function of C language is used to order the elements from lowest to highest. If the common parts are the same, long strings are sorted higher;
  • LIMIT: Returns a subset of the result set fromoffsetPosition starts to returncountValue (similar to * in SQLSELECT LIMIT offset, count*), which is returned when count is negativeoffsetEverything after that. Note: When using this parameter, Redis needs to iterate through offset elements to get the return value. If the offset is large, the complexity may reach O(N).

After version 6.2.0, this command will be deprecated. You are advised to use the ZRANGE command with the BYLEX parameter.

interval

  • Min or MaxMust beUse the ‘(‘ or ‘[‘ symbol to indicate open or closed intervals;
  • For min or Max, you can also use the ‘+’ or ‘-‘ symbol to indicate a plus or minus infinity string; When all elements in an ordered collection have the same score value, useZRANGEBYLEX myzset - *Returns all elements;

The return value

Array: An array of elements in a range sorted in lexicographical ascending order

The sample

127.0.0.1:6379> ZADD myzset 0 a 0 b 0 c 0 d 0 e 0 f 0 g
(integer) 7
127.0.0.1:6379> ZRANGEBYLEX myzset - [c
1) "a"
2) "b"
3) "c"
127.0.0.1:6379> ZRANGEBYLEX myzset - (c
1) "a"
2) "b"
127.0.0.1:6379> ZRANGEBYLEX myzset [aaa (g
1) "b"
2) "c"
3) "d"
4) "e"
5) "f"
Copy the code

ZREVRANGE

Available version: >= 1.2.0

Time complexity: O(log(N)+M), N is the number of elements in the ordered array, M is the number of returned elements

The command format

ZREVRANGE key start stop [WITHSCORES]
Copy the code

Command description

  • Returns a specified range of elements in an ordered collection, sorted from highest to lowest by index value, and those of the same score in lexicographical reverse order
  • ZREVRANGEZRANGESimilar, only differentZREVRANGEFrom the highest to the lowest, andZRANGEFrom low to high
  • If you are usingWITHSCORESParameter, which prints out the element score

After version 6.2.0, the ZREVRANGE command is considered to be deprecated. It is recommended to use the ZRANGE command with the REV parameter.

The return value

Array: An array of elements in a range sorted in descending order

The sample

127.0.0.1:6379> zadd Revset 1 one (integer) 1 127.0.0.1:6379> zadd Revset 2 two (integer) 1 127.0.0.1:6379> Zadd Revset 3 three (INTEGER) 1 127.0.0.1:6379> zadd revset 4 Four (integer) 1 127.0.0.1:6379> zrevrange revset 0-1 1) "four" 2) "Three" 3) "two" 4) "one" 127.0.0.1:6379> Zrevrange revset-3-1 1) "three" 2) "two" 3) "One"
#Withscore This parameter is optional127.0.0.1:6379> zrevrange revset 0-1 withscores 1) "four" 2) "4" 3) "three" 4) "3" 5) "two" 6) "2" 7) "one" 8) "1"Copy the code

ZREVRANGEBYSCORE

Available version: >= 2.2.0

Time complexity: O(log(N)+M), N is the number of elements in the ordered array, M is the number of returned elements

The command format

ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count]
Copy the code

Command description

  • Return score value betweenmaxandminBetween, ordered from high to low; The same score is also returned in lexicographical order;
  • In addition to the different collation rules,ZREVRANGEBYSCOREandZRANGEBYSCOREFunctional consistency;

After version 6.2.0, the ZREVRANGE command is considered deprecated. It is recommended to use the ZRANGE command with BYSCORE and REV parameters.

The return value

Array: An array of elements in a range sorted in descending order

The sample

127.0.0.1:6379> zadd myzset 1 one
(integer) 1
127.0.0.1:6379> zadd myzset 2 two
(integer) 1
127.0.0.1:6379> zadd myzset 3 three
(integer) 1
127.0.0.1:6379> zadd myzset 4 four
(integer) 1

#Plus infinity to minus infinity127.0.0.1:6379> zrevRangeByScore myzset + INF - INF 1) "four" 2) "three" 3) "two" 4) "one"
#Default closed interval
127.0.0.1:6379> zrevrangebyscore myzset 3 1
1) "three"
2) "two"
3) "one"

#Before the closed after opening
127.0.0.1:6379> zrevrangebyscore myzset (3 1
1) "two"
2) "one"
Copy the code

ZREVRANGEBYLEX

Available version: >= 2.8.9

Time complexity: O(log(N)+M), N is the number of elements in the ordered array, M is the number of returned elements

The command format

ZREVRANGEBYLEX key max min [LIMIT offset count]
Copy the code

Command description

  • When all elements in an ordered array have the same score value, this command sorts the elements in lexicographical order, returning the elements between Max and min in descending order from highest to lowest.
  • In addition to sorting in reverse order,ZREVRANGEBYLEXandZRANGEBYLEXCommand consistency;

After version 6.2.0, the ZREVRANGEBYLEX command is considered deprecated. It is recommended to use the ZRANGE command with BYLEX and REV parameters.

The return value

Array: An array of elements in a range sorted in descending order

The sample

127.0.0.1:6379> ZADD myzset 0 a 0 b 0 c 0 d 0 e 0 f 0 g (INTEGER) 7 127.0.0.1:6379> zrevRangebylex myzset + -1) "g" 2) "f" 3) "e" 4) "d" 5) "c" 6) "b" 7) "a"
#Closed interval127.0.0.1:6379> ZREVRANGEBYLEX myzset [c-1] "c" 2) "b" 3) "a"
#Open interval127.0.0.1:6379> ZREVRANGEBYLEX myzset (c-1) "b" 2) "a" 127.0.0.1:6379> ZREVRANGEBYLEX myzset (g [aaa 1) "f" 2) "e" 3) "d" 4) "c" 5) "b"Copy the code

conclusion

This article describes some of the commands associated with ordered collections, including

  • ZADD: Adds elements
  • ZSCORE: Gets the element score value
  • ZCARD: Returns the collection length
  • ZCOUNT: returns the number of elements in a given interval
  • ZRANGE series: in ascending or descending order, traversing elements in a specified range

More and more

Personal blog: lifelmy.github. IO /

Wechat official Account: Long Coding road