The Redis Sort command

Source: Internet
Author: User
Tags redis

SORT key [by mode] [LIMIT offset count] [get mode [get pattern ...]] [ASC | DESC] [ALPHA] [STORE destination]

Returns or saves the sorted elements in the given list, collection, and ordered collection key.

Sorting defaults to numbers as objects, values are interpreted as double-precision floating-point numbers, and comparisons are made.


First. General sort Usage

The simplest sort use method is the sort key and the sort key DESC:

The sort key returns the result of sorting key values from small to large.

The sort key DESC returns the result of sorting key values from large to small.


Assuming the Today_cost list holds today's cost amounts, you can sort it by using the sort command:


# Cost Amount List
redis> lpush today_cost 1.5 8
(integer) 4

# sort redis>
sort today_cost
1) "1.5"2) "8"
3) "4" "

#" # reverse order
redis 127.0.0.1:6379> sort today_cost DESC
1) "
2" C12/>3) "8"
4) "1.5"

Second, Using the ALPHA modifier to sort a string

Because the sort command defaults to sort objects as numbers, you need to explicitly add an ALPHA modifier after the sort command when you want to sort the string:


# URL
redis> lpush website "www.reddit.com"
(integer) 1
redis> Lpush website "www.slashdot.com"
( Integer) 2
redis> Lpush website "www.infoq.com"
(integer) 3

# Default (by number)
redis> sort website
1 "www.infoq.com"
2) "www.slashdot.com"
3) "www.reddit.com"

# sorted by character redis> sort
website alpha< c13/>1) "www.infoq.com"
2) "www.reddit.com"
3) "Www.slashdot.com"

If the system sets the LC_COLLATE environment variable correctly, Redis can recognize UTF-8 encoding.


 Third, use the LIMIT modifier to limit return results


The number of returned elements after sorting can be limited by the LIMIT modifier, which accepts offset and count two parameters:

OFFSET specifies the number of elements to skip.

COUNT specifies how many objects to return after skipping the specified element of offset.


The following example returns the first 5 objects of the sorted result (offset 0 means that no elements are skipped).


# Add test data with list value of 1
redis 127.0.0.1:6379> rpush Rank 1 3 5 7 9
(integer) 5
redis 127.0.0.1:6379> Rpush Rank 2 4 6 8
(integer)

# returns the smallest 5 values in the list
Redis 127.0.0.1:6379> SORT rank LIMIT 0 5 1) "1
" 2
) "2 "
3)" 3 "
4" "4"
5) "5"

You can use multiple modifiers in combination. The following example returns the first 5 objects sorted from large to small.


Redis 127.0.0.1:6379> SORT Rank LIMIT 0 5 DESC
1) "Ten"
2) "9" 3
) "8"
4) "7" 5
) "6"
Fourth. use external key to sort

You can use the data of the external key as a weight instead of the default direct contrast key value to sort.

Suppose you now have user data as follows:

UID User_name_{uid} User_level_{uid}

1 admin 9999

2, Jack 10.

3 Peter 25

4 Mary 70


The following code enters the data into the Redis:


# admin
Redis 127.0.0.1:6379> lpush uid 1
(integer) 1
redis 127.0.0.1:6379> SET user_name_1 admin
OK
redis 127.0.0.1:6379> SET user_level_1 9999
OK

# jack
redis 127.0.0.1:6379> lpush uid 2
( Integer) 2
redis 127.0.0.1:6379> set user_name_2 jack
OK
redis 127.0.0.1:6379> set user_level_2 10< C12/>ok

# peter
Redis 127.0.0.1:6379> lpush uid 3
(integer) 3
redis 127.0.0.1:6379> SET user_ Name_3 Peter
OK
redis 127.0.0.1:6379> SET user_level_3
OK

# mary
Redis 127.0.0.1:6379 > Lpush UID 4
(integer) 4
redis 127.0.0.1:6379> SET user_name_4 Mary
OK
Redis 127.0.0.1:6379& Gt SET user_level_4
OK

By option


By default, the sort uid is sorted directly by the values in the UID:


Redis 127.0.0.1:6379> SORT uid
1 "1"      # admin
2) "2"      # Jack 3 "3
"      # peter
4) "4" c34/># Mary

By using the By option, you can have the UID sort by the elements of the other key.


For example, the following code allows the UID key to be sorted according to the size of the User_level_{uid}:


Redis 127.0.0.1:6379> SORT uid by user_level_*
1) "2"      # jack, level =
2] "3"      # peter, level = 253) "4"      # Mary, Level =
4) ' 1 '      # Admin, level = 9999

User_level_* is a placeholder that first takes out the value in the UID and then uses that value to find the corresponding key.


For example, when you sort the UID list, the program takes the UID values 1, 2, 3, 4, and then uses the values of User_level_1, user_level_2, User_level_3, and user_level_4 as the sort UID The weight.


Get options

Using the Get option, you can retrieve the corresponding key value based on the result of the sort.

For example, the following code first sorts the UID and then takes out the value of the key User_name_{uid}:


Redis 127.0.0.1:6379> SORT uid get user_name_*
1) "admin"
2) "Jack"
3 "Peter"
4) "Mary"

Combined with by and get


By combining by and get, you can make the sort results appear in a more intuitive way.

For example, the following code first presses USER_LEVEL_{UID} to sort the UID list and then extracts the value of the corresponding User_name_{uid}:


Redis 127.0.0.1:6379> SORT uid by user_level_* get user_name_*
1] "Jack"       # level =
2) "Peter"      # Leve L =
3) "Mary"       # level =
4) ' admin ' # level      = 9999

The sorting results are now much more intuitive than using the sort uid by user_level_*.

Get multiple foreign keys

You can use multiple get options at the same time to obtain values for multiple foreign keys.

The following code obtains USER_LEVEL_{UID} and User_name_{uid} separately by UID:


Redis 127.0.0.1:6379> SORT uid get user_level_* get user_name_*
1) "9999"       # level
2) "admin"      # name< C12/>3) "4"
"Jack" 5 "" 6 ""
Peter "
7" "8" "
Mary"

Get has an extra parameter rule, and that is--you can get the value of the sorted key with #.


The following code returns the value of the UID, its corresponding user_level_*, and user_name_* as the result:


Redis 127.0.0.1:6379> SORT uid Get ~ user_level_* get user_name_*
1) "1"          # UID
2) "9999"       # Leve L
3 "admin"      # name
4) "2"
5) "Ten" 6 "
" Jack "
7)" 3 "
8)" 9 "
" Peter "
10 ) "4" (one
)) "
Mary"

Get foreign keys, but do not sort


By passing a nonexistent key as a parameter to the by option, you can let sort skip the sort operation and return the result directly:


Redis 127.0.0.1:6379> SORT uid by not-exists-key
1) "4"
2) "3"
3) "2"
4 "1"

This usage is of little practical use when used alone.

However, by matching this usage with the GET option, you can obtain multiple foreign keys without sorting, equivalent to performing a consolidated fetch operation (similar to the JOIN keyword for the SQL database).


The following code demonstrates how to obtain multiple foreign keys using sort, by, and get without causing a sort:


Redis 127.0.0.1:6379> SORT uid by Not-exists-key get # to user_level_* get user_name_*
1) "4"      # ID
2) "70"     # level
3 "Mary"   # Name
4) "3" 5) "(6)"
Peter "7"
2 "
8" "9"
"Jack" C16/>10) "1" (one
) "9999" "
admin"

To use a hash table as a parameter to get or by


In addition to the string keys, a hash table can be used as a parameter to a GET or by option.

For example, for the previously given user information table:


UID 	user_name_{uid} 	user_level_{uid
1 	admin 	9999
2 	Jack
3 	Peter
4 	Mary 	70

Instead of saving the user's name and level in the User_name_{uid} and user_level_{uid {Two string keys, we can save the user's name and level information with a hash table User_info_{uid} with the name domain and levels field:


Redis 127.0.0.1:6379> hmset user_info_1 name admin level 9999
OK redis 127.0.0.1:6379> hmset user_info_2

na Me Jack level
OK

redis 127.0.0.1:6379> hmset user_info_3 name Peter level
OK

Redis 127.0.0.1:637 9> hmset user_info_4 name Mary level
OK

After that, the by and get options can obtain the values of the fields in the hash table in Key->field format where key represents the Hashtable key, and field represents the domain of the Hashtable:


Redis 127.0.0.1:6379> SORT uid by user_info_*->level
1) "2"
2) "3"
3) "4"
4) "1"

Redis 127.0.0.1:6379> SORT uid by User_info_*->level get user_info_*->name
1) "Jack"
2 "Peter"
3 " Mary "
4" "admin"
Fifth. Save Sort Results 

By default, the sort operation simply returns the sorting result without any save operations.

You can save the sort result to a given key by assigning a key parameter to the STORE option.

If the specified key already exists, the original value will be overwritten by the sort result.


# test Data
redis 127.0.0.1:6379> rpush numbers 1 3 5 7 9
(integer) 5
redis 127.0.0.1:6379> Rpush numbers 2 4 6 8
(integer)
redis 127.0.0.1:6379> lrange numbers 0-1
1) "1" 2
) "3" 3)
"5" 4) "7" 5) "9"
6) "2"
7) "4" 8
) "6" 9
) "8"
ten "
redis 127.0.0.1:6379> SORT numbers STORE sor Ted-numbers
(integer) 10

# sorted Results
redis 127.0.0.1:6379> lrange sorted-numbers 0-1
1) "1"
2) "2" 3) "3" 4
) "4"
5 ) "5"
6) "6" 7) "7" 8 "" 8 "9)" 9 "10
)" 10 "

You can produce a result cache of a sort operation by saving the execution result of the sort command and setting the life time for the result by EXPIRE.


This avoids frequent calls to the sort operation: you need to invoke the sort operation only when the result set expires.

In addition, to properly implement this usage, you may need to lock to prevent multiple clients from caching simultaneously (that is, multiple clients, sort at the same time, and save as a result set), see the Setnx command.


Available versions:

>= 1.0.0

Complexity of Time:

O (N+m*log (m)), N is the number of elements within the list or collection to be sorted, and M is the number of elements to be returned.

Time complexity O (N) If you are only getting data using the get option of the sort command without sorting.


return value:

No STORE parameters are used to return the sort results in the form of a list.

Returns the number of elements of the sorted result using the STORE parameter.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.