How to Use Redis SORT sorting commands

Source: Internet
Author: User
Tags redis server

How to Use Redis SORT sorting commands

I believe that you do not know much about Redis SORT sorting commands. Therefore, I have compiled some methods and examples of using Redis SORT sorting commands. I hope the examples can help you.

Redis SORT is a SORT Command provided by Redis. Tags in the set are unordered and can be sorted by SORT. For example:

Redis> SADD jihe 5

(Integer) 1

Redis> SADD jihe 1

(Integer) 1

Redis> SADD jihe 2

(Integer) 1

Redis> SADD jihe 8

(Integer) 1

Redis> SORT jihe

1) "1"

2) "2"

3) "5"

4) "8"

If you use Redis SORT to SORT data by letters instead of numbers, you need to use

SORT jihe ALPHA

If the ALPHA parameter is not added, an error is returned, indicating: (error) ERR One or more scores can't be converted into double. We can also use the DESC of a relational database for reverse sorting and LIMIT offset count to LIMIT the number of obtained results.

SORT jihe desc limit 0 2

You can also add the BY parameter to the Redis SORT command. A statement can have only one BY parameter. In this case, SORT will not SORT by its own values, such as (, and a, A, g, and B), but will SORT by fields in the specified key. For example:

SORT tag: redis: article BY article: *-> time DESC

Explanation: according to the value in tag: redis: article (tag is the redis article ID), a new key is combined into a value in article :( ag: redis: article ): time. Get the list of articles whose tags are redis IDs and sort them by their release time.

The Redis SORT command also has a GET parameter. The GET parameter is similar to the associated query in a relational database. For example, to query the list of redis Article IDs, sort the list in descending order based on the release time, and then obtain the title of each article. GET can have multiple:

SORT tag: redis: article BY article: *-> time desc get article: *-> title GET article: *-> time GET #

GET # means to return the article ID. You can write GET article: *-> id or GET #.

Another parameter of the Redis SORT command is STORE, which stores sorted content to a new key. The type of the new key is the list type. If yes, the new key will be overwritten. In this case, you can use EXPIRE to set the cache:

SORT tag: redis: article BY article: *-> time desc get article: *-> title GET article: *-> time GET # STORE resultKey

Redis's SORT command is one of the most complex and powerful Redis commands, and the time complexity is O (n + mLOGm ). N is the length of the list to be sorted, and m is the number of elements returned. Reducing n and m improves SORT performance.

  Supplement:

1. applicable to all types of commands

EXISTS key determines whether a key EXISTS. If yes, 1 is returned; otherwise, 0 is returned;

DEL key: deletes a key or a series of keys. DEL key1 key2 key3 key4

TYPE key returns the Data TYPE of a key element (none: nonexistent, string: character, list, set, zset, hash)

KEYS pattern returns the list of matched KEYS (keys foo *: Search for KEYS starting with foo)

RANDOMKEY randomly obtains an existing key. If the current database is empty, an empty string is returned.

RENAME oldname newname: Change the key name. If the new key exists, it will be overwritten.

RENAMENX oldname newname: Change the key name. If the name exists, the change fails.

DBSIZE returns the total number of keys of the current database.

EXPIRE sets the expiration time (in seconds) for a key. (EXPIRE bruce 1000: sets the key of bruce to be automatically deleted after seconds.) Note: if the key has not expired yet, if the value is changed, the value is cleared.

How long does TTL wait for a key to expire? The returned time is seconds.

SELECT index SELECT database

MOVE key dbindex: MOVE the specified key from the current database to the target database dbindex. 1 is returned; otherwise, 0 is returned (the source database does not have a key or the target database already has a key with the same name );

FLUSHDB clears all keys in the current database

FLUSHALL clears all keys in all databases

2. string processing command

SET key value sets the string value for a key. SET keyname datalength data (SET bruce 10 paitoubing: Save a string paitoubing with a key of burce and a string of 10 to the database). The maximum data size cannot exceed 1 GB.

GET key obtains the value of a key. If the key does not exist, "nil" is returned. If the key value is not of the string type, an error is returned.

GETSET key value can be understood as the value of the obtained key and then SET this value for more convenient operations (SET bruce 10 paitoubing, in this case, you need to modify bruce to 1234567890 and obtain the previous data paitoubing, GETSET bruce 10 1234567890)

MGET key1 key2... KeyN returns the values of multiple keys at a time.

The difference between SETNX key value SETNX and SET is that SET can create and update the key value. If SETNX does not exist, the key and value data are created.

MSET key1 value1 key2 value2... KeyN valueN sets multiple keys and values at a time in one atomic operation.

MSETNX key1 value1 key2 value2... KeyN valueN sets multiple keys and values at a time in one atomic operation (if the target key does not exist, if more than one key already exists, it fails)

INCR key auto-increment key value

INCRBY key integer enables auto-increment of key values.

DECR key auto-Subtract key value

DECRBY key integer: used to reduce the value of a key.

3. lists commands

RPUSH key value adds an element from the end of the List (if the sequence does not exist, it is created first. If there is a Key with the same name but not a sequence, an error is returned)

LPUSH key value adds an element from the List Header

LLEN key returns the length of a List.

LRANGE key start end returns the elements of the sequence from a custom range (LRANGE testlist 0 2; returns the first 0 1 2 elements of the sequence testlist)

LTRIM key start end Trim Data out of a certain range (LTRIM testlist 0 2; Retain 0 1 2 elements, and delete the remaining)

LINDEX key index returns the value of the sequence at a certain position (LINDEX testlist 0; returns the element of the sequence testlist where the position is 0)

The LSET key index value updates the value of an element at a certain position.

The LREM key count value deletes a certain number of elements matching the value from the header (count positive) or tail (count negative) of the List, and returns the number of deleted elements.

LPOP key pops up the first element of the List.

RPOP key pops up the last element of the List.

RPOPLPUSH srckey dstkey pops up the last element in _ srckey _ and pushes it to the _ dstkey _ header. If the key does not exist or the sequence is empty, "nil" is returned"

4. commands for processing sets (with unordered index sequences)

SADD key member adds elements to the SETS sequence. If the element (membe) does not exist, 1 is added successfully; otherwise, 0 is failed; (SADD testlist 3 n one)

SREM key member: deletes an element in the SETS sequence. If the element does not exist, the result is 0. Otherwise, the result is 1 (SREM testlist 3 N one)

SPOP key randomly pops up a member from the collection.

SMOVE srckey dstkey member moves an element of a set sequence to another set sequence (SMOVE testlist test 3n two; moves the element two from the sequence testlist to test, and there will be no two element in testlist)

SCARD key counts the number of elements in a sequence of SETS.

SISMEMBER key member knows whether the specified member exists in the collection

SINTER key1 key2... KeyN returns key1, key2 ,..., Intersection In keyN

SINTERSTORE dstkey key1 key2... KeyN splits key1, key2 ,..., Store the intersection in keyN to dstkey

SUNION key1 key2... KeyN returns key1, key2 ,..., Union of keyN

SUNIONSTORE dstkey key1 key2... KeyN splits key1, key2 ,..., KeyN union is stored in dstkey

SDIFF key1 key2... KeyN is based on key2 ,..., KeyN calculates the difference set of key1. Official example:

Key1 = x, a, B, c

Key2 = c

Key3 = a, d

SDIFF key1, key2, key3 => x, B

SDIFFSTORE dstkey key1 key2... KeyN is based on key2 ,..., The keyN calculates the difference set of key1 and saves it to the dstkey.

SMEMBERS key returns all elements of a sequence.

SRANDMEMBER key returns random elements of a sequence.

5. zsets)

ZADD key score member: Add a specified member to the sorted set. If the target exists, the score is updated (score, used for sorting)

ZREM key member deletes a specified member from an Ordered Set

ZINCRBY key increment member adds _ increment _ if a member exists. Otherwise, it sets a member whose score is _ increment _.

ZRANGE key start end: return the members of the specified range in ascending order.

ZREVRANGE key start end returns the members of the specified range after descending order.

ZRANGEBYSCORE key min max returns all ZCARD keys that match score> = min and score <= max. returns the number of elements in an ordered set. ZSCORE key element returns the SCORE value of a specified member. ZREMRANGEBYSCORE key min max is deleted. all members meeting the score> = min and score <= max Conditions

6. hash type

Command Parameters Description

HSET key field value Set the hash field to the specified value. Creates the hash if needed.

HGET key field Retrieve the value of the specified hash field.

Hmet key field1... FieldN Get the hash values associated to the specified fields.

HMSET key field1 value1... FieldN valueN Set the hash fields to their respective values.

HINCRBY key field integer Increment the integer value of the hash at key on field with integer.

HEXISTS key field Test for existence of a specified field in a hash

HDEL key field Remove the specified field from a hash

HLEN key Return the number of items in a hash.

HKEYS key Return all the fields in a hash.

HVALS key Return all the values in a hash.

HGETALL key Return all the fields and associated values in a hash.

7. Sort (List, Set, Sorted Set)

SORT key BY pattern LIMIT start end GET pattern ASC | desc alpha sorts the set or List according to the specified mode

SORT mylist DESC in descending order

SORT mylist LIMIT 0 10 starts from the serial number 0 and takes 10

SORT mylist LIMIT 0 10 alpha desc sort by first character

SORT mylist BY weight _ * STORE resultkey stores the returned results in the resultkey sequence (List)

8. Persistent Control

SAVE synchronously saves data to the disk

BGSAVE asynchronously saves data to the disk

LASTSAVE returns the last Unix timestamp successfully saved to the disk.

SHUTDOWN synchronously saves data to the server and closes the Redis server (SAVE + QUIT)

BGREWRITEAOF when the log file is too long to re-write the log file

9. Remote Control commands

INFO provides server information and statistical information

MONITOR outputs all received requests in real time

SLAVEOF modify copy Option

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.