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> 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:

redis> lpush website ""
(integer) 1
redis> Lpush website ""
( Integer) 2
redis> Lpush website ""
(integer) 3

# Default (by number)
redis> sort website
1 ""
2) ""
3) ""

# sorted by character redis> sort
website alpha< c13/>1) ""
2) ""
3) ""

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> rpush Rank 1 3 5 7 9
(integer) 5
redis> Rpush Rank 2 4 6 8

# returns the smallest 5 values in the list
Redis> 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> 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> lpush uid 1
(integer) 1
redis> SET user_name_1 admin
redis> SET user_level_1 9999

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

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

# mary
Redis > Lpush UID 4
(integer) 4
redis> SET user_name_4 Mary
Redis Gt SET user_level_4

By option

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

Redis> 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> 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> 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> 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> SORT uid get user_level_* get user_name_*
1) "9999"       # level
2) "admin"      # name< C12/>3) "4"
"Jack" 5 "" 6 ""
Peter "
7" "8" "

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> 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
)) "

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> 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> 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" "

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> hmset user_info_1 name admin level 9999
OK redis> hmset user_info_2

na Me Jack level

redis> hmset user_info_3 name Peter level

Redis 9> hmset user_info_4 name Mary level

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> SORT uid by user_info_*->level
1) "2"
2) "3"
3) "4"
4) "1"

Redis> 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> rpush numbers 1 3 5 7 9
(integer) 5
redis> Rpush numbers 2 4 6 8
redis> lrange numbers 0-1
1) "1" 2
) "3" 3)
"5" 4) "7" 5) "9"
6) "2"
7) "4" 8
) "6" 9
) "8"
ten "
redis> SORT numbers STORE sor Ted-numbers
(integer) 10

# sorted Results
redis> 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: 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.