sort
SORT
Apply for Redis Developer Course
|
Redis Regular Inspection / Technical Support
|
Redis Enterprise Server
|
|---|
Get data sorted
Simple usage is sort key.
The data types you can use as key are list, set, and sorted set.
Let's put data in a set, which you cannot normally view sorted, and sort it.
Example
| Command> | sadd myurl Google.com Facebook.com Youtube.com Yahoo.com Baidu.com |
| Result> | 5 |
| Command> | sort myurl alpha use alpha when the sort target is not a number |
| Result> |
0) Baidu.com 1) Facebook.com 2) Google.com 3) Yahoo.com 4) Youtube.com |
| Command> | sort myurl alpha desc use desc to sort in reverse order |
| Result> |
0) Youtube.com 1) Yahoo.com 2) Google.com 3) Facebook.com 4) Baidu.com |
Using the limit option
limit offset count
Example
| Command> | sort myurl alpha limit 0 3 |
| Result> |
0) Baidu.com 1) Facebook.com 2) Google.com |
| Command> | sort myurl alpha limit 3 10 |
| Result> |
0) Yahoo.com 1) Youtube.com |
Using the get option
Use get to retrieve a value from another key.
For example, to match Google.com in myurl with rank-Google.com and get the value of rank-Google.com, use get rank-*.
Think of it as a join in a relational database.
Prepare data by entering website ranks
Example
| Command> | mset rank-Google.com 1 rank-Facebook.com 2 rank-Youtube.com 3 rank-Yahoo.com 4 rank-Baidu.com 5 |
| Result> | OK |
| Command> | sort myurl get rank-* alpha |
| Result> |
0) 5 1) 2 2) 1 3) 4 4) 3 |
Using the get # option
To include the sorted element itself, use the special GET form get #.
Example
| Command> | sort myurl get # get rank-* alpha |
| Result> |
0) Baidu.com 1) 5 2) Facebook.com 3) 2 4) Google.com 5) 1 6) Yahoo.com 7) 4 8) Youtube.com 9) 3 |
Using the by option
Sort by the value of the specified key.
Sort by the value of rank-*.
Example
| Command> | sort myurl by rank-* get # get rank-* alpha |
| Result> |
0) Google.com 1) 1 2) Facebook.com 3) 2 4) Youtube.com 5) 3 6) Yahoo.com 7) 4 8) Baidu.com 9) 5 |
Get two or more fields
Let's retrieve two or more fields using get.
Prepare data by entering Daily Pageviews per Visitor
Example
| Command> | mset pv-Google.com 19.60 pv-Facebook.com 11.62 pv-Youtube.com 4.58 pv-Yahoo.com 7.44 pv-Baidu.com 8.87 |
| Result> | OK |
| Command> | sort myurl by pv-* get # get pv-* get rank-* desc |
| Result> |
0) Google.com 1) 19.60 2) 1 3) Facebook.com 4) 11.62 5) 2 6) Baidu.com 7) 8.87 8) 5 9) Yahoo.com 10) 7.44 11) 4 12) Youtube.com 13) 4.58 14) 3 |
The examples above were also made using Hash, List, and ZSet.
Syntax
SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination]
- Available since version 1.0.0.
- Time complexity is O(N+M*log(M)).
| Related commands | SCAN |
| Clients for Java | Jedis, Lettuce, Redisson | Clients for C | Hiredis |
| << SCAN | SORT | SORT hash >> |
|---|
