search
HomeBackend DevelopmentC#.Net TutorialRedis tutorial (6): Sorted-Sets data type

1. Overview:

Sorted-Sets and Sets types are very similar. They are both collections of strings and do not allow duplicate members to appear in a Set. The main difference between them is that each member in Sorted-Sets will have a score associated with it, and Redis uses the score to sort the members in the set from small to large. However, it should be noted that although the members in Sorted-Sets must be unique, the scores can be repeated.
Adding, deleting or updating a member in a Sorted-Set is a very fast operation, and its time complexity is the logarithm of the number of members in the set. Since the members in Sorted-Sets are ordered in the set, even accessing members located in the middle of the set is still very efficient. In fact, this feature of Redis is difficult to implement in many other types of databases. In other words, in order to achieve the same efficiency as Redis at this point, it is very difficult to model in other databases. of.

2. Related command list:

T

##ZINCRBYkey increment member O(log(N))Time complexity. The N represents the number of members in the Sorted-Sets. This command will increase the specified score for the specified member in the specified Key. If the member does not exist, the command will add the member and assume its initial score is 0, and then increase its score. Add increment. If the Key does not exist, this command will create the Key and its associated Sorted-Sets, and contain the members specified by the parameter, whose scores are related to the increment parameter. The error message will be returned. The new score as a string ##ZRANGEkey start stop [WITHSCORES]
Command prototype Time complexity Command description Return value
ZADD key score member [score] [member] O(log(N)) N in time complexity represents the number of members in Sorted-Sets. Add all members specified in the parameters and their scores to the Sorted-Set of the specified key. In this command, we can specify multiple sets of scores/members as parameters. If a member in the parameter already exists when added, this command will update the member's score to the new value and reorder the member based on the new value. If the key does not exist, this command will create a new Sorted-Sets Value for the key and insert the score/member pair into it. If the key already exists, but the associated Value is not of type Sorted-Sets, the relevant error message will be returned. The number of members actually inserted in this operation.
ZCARD key O(1) Get the number of members contained in the Sorted-Sets associated with the Key. Returns the number of members in Sorted-Sets. If the Key does not exist, returns 0.
ZCOUNTkey min max O(log(N)+M) N in time complexity represents the number of members in Sorted-Sets , M represents the number of elements between min and max. This command is used to get the number of members whose score is between min and max. An additional explanation for the min and max parameters is that -inf and +inf represent the highest and lowest values ​​of the scores in Sorted-Sets respectively. By default, the range represented by min and max is a closed interval range, that is, members within min The number of members in the specified range
O(log(N )+M) The N in the time complexity represents the number of members in the Sorted-Set, and M represents the number of members returned. This command returns the members whose order is within the range specified by the parameters start and stop, where start and stop parameters are both 0-based, that is, 0 represents the first member and -1 represents the last member. If start is greater than the maximum index value in the Sorted-Set, or start > stop, an empty set will be deleted. Return. If stop is greater than the maximum index value, the command will return the last member of the set from start. If the command has the optional parameter WITHSCORES option, the command will include the score value of each member in the returned result, such as value1,score1,value2,score2.... Returns the list of members whose index is between start and stop.
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count] O(log(N)+M) Time complexity N represents the number of members in the Sorted-Set, and M represents the number of members returned. This command will return all members with scores between min and max, that is, members that satisfy the expression min Returns a list of members whose scores are within the specified range.
ZRANK key member O(log(N)) The N in the time complexity represents the number of members in the Sorted-Set. The members in the Sorted-Set are stored in order from low to high scores. This command will return the position value of the member specified in the parameter, where 0 represents the first member, which is the member with the lowest score in the Sorted-Set. If the member exists, return its position index value. Otherwise return nil.
ZREM key member [member ...] O(M log(N)) N in time complexity represents Sorted-Set The number of members in M ​​represents the number of deleted members. This command will remove the members specified in the parameters, and members that do not exist will be ignored. If the Value associated with the Key is not a Sorted-Set, the corresponding error message will be returned. The actual number of deleted members.
ZREVRANGE key startsstop[WITHSCORES] O(log(N)+M) N in time complexity represents Sorted-Set The number of members, M represents the number of members returned. The function of this command is basically the same as ZRANGE. The only difference is that this command obtains the members at the specified position through reverse sorting, that is, from high to low. If members have the same score, they are sorted in descending lexicographic order. Returns the specified member list.
ZREVRANKkey member O(log(N)) The N in the time complexity represents the number of members in the Sorted-Set. The function of this command is basically the same as ZRANK. The only difference is that the index obtained by this command is the position after sorting from high to low. Similarly, 0 represents the first element, which is the member with the highest score. If the member exists, return its position index value. Otherwise return nil.
ZSCOREkey member O(1) Get the score of the specified member of the specified Key If the member exists, use Returns its score as a string, otherwise returns nil.
ZREVRANGEBYSCOREkey max min [WITHSCORES] [LIMIT offset count] O(log(N)+M) N in time complexity Represents the number of members in the Sorted-Set, and M represents the number of returned members. Except that the sorting method of this command is based on the score sorting from high to low, other functions and parameter meanings are the same as ZRANGEBYSCORE. Returns a list of members whose scores are within the specified range.
ZREMRANGEBYRANKkey start stop O(log(N)+M) The N in the time complexity represents the number of members in the Sorted-Set , M represents the number of deleted members. Delete the member whose index position is between start and stop. Both start and stop are 0-based, that is, 0 represents the member with the lowest score, and -1 represents the last member, which is the member with the highest score. The number of deleted members.
ZREMRANGEBYSCOREkey min max O(log(N)+M) N in time complexity represents the number of members in Sorted-Set , M represents the number of deleted members. Delete all members whose scores are between min and max, that is, all members that satisfy the expression min The number of deleted members.
##3. Command examples:

1. ZADD/ZCARD/ZCOUNT/ZREM/ZINCRBY/ZSCORE/ZRANGE/ZRANK:

 #在Shell的命令行下启动Redis客户端工具。
    /> redis-cli
    #添加一个分数为1的成员。
    redis 127.0.0.1:6379> zadd myzset 1 "one"
    (integer) 1
    #添加两个分数分别是2和3的两个成员。
    redis 127.0.0.1:6379> zadd myzset 2 "two" 3 "three"
    (integer) 2
    #0表示第一个成员,-1表示最后一个成员。WITHSCORES选项表示返回的结果中包含每个成员及其分数,否则只返回成员。
    redis 127.0.0.1:6379> zrange myzset 0 -1 WITHSCORES
    1) "one"
    2) "1"
    3) "two"
    4) "2"
    5) "three"
    6) "3"
    #获取成员one在Sorted-Set中的位置索引值。0表示第一个位置。
    redis 127.0.0.1:6379> zrank myzset one
    (integer) 0
    #成员four并不存在,因此返回nil。
    redis 127.0.0.1:6379> zrank myzset four
    (nil)
    #获取myzset键中成员的数量。    
    redis 127.0.0.1:6379> zcard myzset
    (integer) 3
    #返回与myzset关联的Sorted-Set中,分数满足表达式1 <= score <= 2的成员的数量。
    redis 127.0.0.1:6379> zcount myzset 1 2
    (integer) 2
    #删除成员one和two,返回实际删除成员的数量。
    redis 127.0.0.1:6379> zrem myzset one two
    (integer) 2
    #查看是否删除成功。
    redis 127.0.0.1:6379> zcard myzset
    (integer) 1
    #获取成员three的分数。返回值是字符串形式。
    redis 127.0.0.1:6379> zscore myzset three
    "3"
    #由于成员two已经被删除,所以该命令返回nil。
    redis 127.0.0.1:6379> zscore myzset two
    (nil)
    #将成员one的分数增加2,并返回该成员更新后的分数。
    redis 127.0.0.1:6379> zincrby myzset 2 one
    "3"
    #将成员one的分数增加-1,并返回该成员更新后的分数。
    redis 127.0.0.1:6379> zincrby myzset -1 one
    "2"
    #查看在更新了成员的分数后是否正确。
    redis 127.0.0.1:6379> zrange myzset 0 -1 WITHSCORES
    1) "one"
    2) "2"
    3) "two"
    4) "2"
    5) "three"
    6) "3"

2. ZRANGEBYSCORE/ZREMRANGEBYSCORE/ZREMRANGEBYSCORE

 redis 127.0.0.1:6379> del myzset
    (integer) 1
    redis 127.0.0.1:6379> zadd myzset 1 one 2 two 3 three 4 four
    (integer) 4
    #获取分数满足表达式1 <= score <= 2的成员。
    redis 127.0.0.1:6379> zrangebyscore myzset 1 2
    1) "one"
    2) "two"
    #获取分数满足表达式1 < score <= 2的成员。
    redis 127.0.0.1:6379> zrangebyscore myzset (1 2
    1) "two"
    #-inf表示第一个成员,+inf表示最后一个成员,limit后面的参数用于限制返回成员的自己,
    #2表示从位置索引(0-based)等于2的成员开始,去后面3个成员。
    redis 127.0.0.1:6379> zrangebyscore myzset -inf +inf limit 2 3
    1) "three"
    2) "four"
    #删除分数满足表达式1 <= score <= 2的成员,并返回实际删除的数量。
    redis 127.0.0.1:6379> zremrangebyscore myzset 1 2
    (integer) 2
    #看出一下上面的删除是否成功。
    redis 127.0.0.1:6379> zrange myzset 0 -1
    1) "three"
    2) "four"
    #删除位置索引满足表达式0 <= rank <= 1的成员。
    redis 127.0.0.1:6379> zremrangebyrank myzset 0 1
    (integer) 2
    #查看上一条命令是否删除成功。
    redis 127.0.0.1:6379> zcard myzset
    (integer) 0

3. ZREVRANGE/ZREVRANGEBYSCORE/ZREVRANK:

 #为后面的示例准备测试数据。
    redis 127.0.0.1:6379> del myzset
    (integer) 0
    redis 127.0.0.1:6379> zadd myzset 1 one 2 two 3 three 4 four
    (integer) 4
    #以位置索引从高到低的方式获取并返回此区间内的成员。
    redis 127.0.0.1:6379> zrevrange myzset 0 -1 WITHSCORES
    1) "four"
    2) "4"
    3) "three"
    4) "3"
    5) "two"
    6) "2"
    7) "one"
    8) "1"
    #由于是从高到低的排序,所以位置等于0的是four,1是three,并以此类推。
    redis 127.0.0.1:6379> zrevrange myzset 1 3
    1) "three"
    2) "two"
    3) "one"
    #由于是从高到低的排序,所以one的位置是3。
    redis 127.0.0.1:6379> zrevrank myzset one
    (integer) 3
    #由于是从高到低的排序,所以four的位置是0。
    redis 127.0.0.1:6379> zrevrank myzset four
    (integer) 0
    #获取分数满足表达式3 >= score >= 0的成员,并以相反的顺序输出,即从高到底的顺序。
    redis 127.0.0.1:6379> zrevrangebyscore myzset 3 0
    1) "three"
    2) "two"
    3) "one"
    #该命令支持limit选项,其含义等同于zrangebyscore中的该选项,只是在计算位置时按照相反的顺序计算和获取。
    redis 127.0.0.1:6379> zrevrangebyscore myzset 4 0 limit 1 2
    1) "three"
    2) "two"

4. Application scope:


# 1). Can be used for the ranking list of a large-scale online game. Whenever the player's score changes, you can execute the ZADD command to update the player's score, and then use the ZRANGE command to obtain the user information of the TOP TEN points. Of course, we can also use the ZRANK command to obtain the player's ranking information through username. Finally, we will use the ZRANGE and ZRANK commands in combination to quickly obtain information about other users with similar points to a certain player.

2). The Sorted-Sets type can also be used to build index data.

The above is the content of Redis Tutorial (6): Sorted-Sets data type. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function