Redis type [string, list, set, sorted set, hash]

Source: Internet
Author: User
Tags key string

1. Keys
Redis is inherently a key-value db, so let's start by looking at his key.
First, the key is also a string type, but the key cannot include the boundary character; Because key is not a binary safe string, keys such as "My Key" and "mykey\n" that contain spaces and line breaks are not allowed.
Note:
By the way, the use of binary characters is not restricted within Redis, which is limited by the Redis protocol. "\ r \ n" is used as a special character in the protocol format.
Some of the commands in the Redis 1.2 protocol have begun to use the new protocol format (such as Mset). In short, the inclusion of boundary characters as illegal key bar, so as to avoid being entangled by the bug.
In addition to the introduction of a format convention for key, Object-type:id:field. Like User:1000:password,blog:xxidxx:title.
And the length of the key is best not too long. The reason is obviously the memory ah, and the lookup time relatively short key is also slower.
But also recommended short key, such as u:1000:pwd, such as. Obviously, the above user:1000:password is very readable.

2. String type
The string is the most basic type of Redis, and the string type is binary safe.
This means that a Redis string can contain any data. For example, JPG images or serialized objects. From an internal implementation, a string can be treated as a byte array with a maximum limit of 1G bytes.
The following is the definition of a string type.
struct SDSHDR {
Long Len;
Long free;
Char buf[];
};
BUF is a char array for storing the actual string contents. In fact, char is equivalent to Byte in C #, which is a byte
Len is the length of the BUF array, and free is the number of available bytes remaining in the array.
This makes it possible to understand why the string type is binary safe. Because it's essentially a byte array. Of course it can contain any data.
In addition, the string type can be handled by a partial command as an int. such as incr and other commands,
Other types of Redis like list,set,sorted set, hash they contain elements and can only be of type string.
If you use only string types, Redis can be seen as a memcached with persistent features. Of course, Redis has a lot more to do with string types than memcached.

3. List type
The Redis list type is actually a doubly linked list in which each child element is a string type. So [Lr]push and [Lr]pop] the algorithm time complexity of the command is O
The list will also record the length of the linked list. So the Llen operation is also o. The maximum length of the linked list is (2 of 32 square-1).
We can add delete elements from the head or tail of the list by Push,pop operation. This allows the list to be used as either a stack or as a queue.
The interesting thing is that the pop operation of the list is also blocked version. When we [Lr]pop a list object, if the list is empty, or does not exist, it returns nil immediately. But blocking versions of B[lr]pop can be blocked,
Of course, you can add a timeout, and you will return nil after the time-out. Why block versions of Pop, primarily to avoid polling.
Example if we use list to implement a Task Force column. The thread that performs the task can call a blocked version of Pop to
Get a task this avoids polling to check for the presence of a task. The worker thread can return immediately when the task comes, or it can avoid the delay caused by polling.


4. Set type
Redis's set is an unordered collection of type string. The set element can contain a maximum of (2 of 32 square-1) elements.
The set is implemented by hash table, so the complexity of adding, deleting, and finding is O. The hash table is automatically resized as it is added or removed.
It is important to note that when adjusting the hash table size, synchronization (acquisition of write locks) is required to block other read and write operations.
It may be possible to use a skip list instead of a jump table to implement a skip table that has already been used in sorted set.
For the Set collection type in addition to the basic add-delete operation, other useful operations include the collection Union, the intersection (intersection),
Subtraction (difference).

5.Sorted Set Type
As with set sorted set is also a collection of elements of type string, but each element is associated with a double type of score. The implementation of the sorted set is a mixture of skip list and hash table

When an element is added to the collection, an element-to-score mapping is added to the hash table, so the cost of getting score for a given element is O,
Another score-to-element mapping is added to the skip list and sorted by score, so the elements in the collection can be ordered sequentially.
Add, the cost of the delete operation is the same as the cost of the O and Skip list, and the Redis skip list implementation uses a doubly linked list so that the elements can be taken from the tail in reverse order.
The most common use of sorted set is to use it as an index. We can store the fields to be sorted as score, the object's ID when the element is stored.

6.Hash Set Type
Redis Hash is a string-type field and value mapping table. Its addition, delete operations are o.hash especially suitable for storing objects.
Compared to Gencun each word of an object into a single string type. Storing an object in a hash type consumes less memory and makes it easier to access the entire object.

The reason for saving memory is that when a new hash object is created, it is stored with Zipmap (also known as small hash).
This zipmap is not actually hash table, but zipmap compared to the normal hash implementation can save a lot of the hash itself needs some metadata storage overhead.
Although Zipmap's additions, deletions, and lookups are all O (n), there are not too many field numbers for general objects.
So the use of Zipmap is also very fast, that is, add delete average or O (1).
If the size of field or value exceeds a certain limit, Redis automatically replaces the zipmap with the normal hash implementation internally.
This restriction can be specified in the configuration file
Hash-max-zipmap-entries #配置字段最多64个
Hash-max-zipmap-value #配置value最大为512字节




Command:
1. Key-related commands
Exists key test Specifies whether key exists, returns 1 for presence, 0 does not exist
Del key1 key2 .... KeyN deletes the given key, returns the number of deleted keys, 0 means the given key does not exist
Type key returns the value type of the given key. The return none indicates that there is no key,string character type, the list linked list type set unordered collection type ...
The keys pattern returns all keys that match the specified pattern, given an example
Randomkey returns a randomly selected key from the current database and returns an empty string if the current database is empty
Rename Oldkey Newkey The atom is renamed a key, if newkey exists, it will be overwritten, return 1 indicates success, 0 fails. Maybe Oldkey doesn't exist, or it's the same as Newkey.
Renamenx Oldkey Newkey Ibid, but if Newkey exists return failure
Dbsize returns the number of keys for the current database
Expire key seconds Specifies the expiration time, in seconds, for the key. Returns 1 success, 0 indicates that key has been set to expire or does not exist
TTL key returns the remaining expiration seconds of a key that has set an expiration time-1 indicates that key does not exist or has not been set to expire
Select Db-index selects the database by index, the default connection database is all 0, and the default number of databases is 16. Returns 1 indicates success, 0 failed
Move key Db-index moves the key from the current database to the specified database. Returns 1 success. 0 if key does not exist or is already in the specified database
FLUSHDB Delete all keys in the current database, this method does not fail. Use with caution
Flushall all keys in all databases are deleted, this method does not fail. More cautious use


2. String-related commands
Set key value sets key corresponding to value of type string, returns 1 for success, 0 failure
Setnx key value Ibid, if key already exists, returns 0. NX is not exist's meaning
Get key gets the string value corresponding to key, if key does not exist return nil
Getset the value of key value atom, and returns the old value of key. If key does not exist return nil
Mget key1 Key2 ... keyN gets the value of more than one key at a time and returns nil if the corresponding key does not exist.
Mset key1 value1 ... keyN Valuen set the value of multiple keys at once, successfully returning 1 means that all values are set, and a failure return of 0 means that no value is set
Msetnx key1 value1 ... KeyN Valuen Ibid, but does not overwrite existing key
INCR Key does a Gaga operation on the value of key and returns the new value. Note INCR A value that is not an int returns an error incr a nonexistent key, setting key to 1
Decr key Ibid, but do is reduce the operation, DECR one does not exist key, then set key to 1
Incrby key integer with INCR, plus the specified value, key does not exist when the key is set, and that the original value is 0
Decrby key integer with DECR, minus the specified value. Decrby is purely for readability, we can achieve the same effect by Incrby a negative value, and vice versa.
Append key value appends value to the string value of the specified key, returning the length of the new string value.
SUBSTR Key Start End returns the string value of the truncated key, noting that the value of key is not modified.


3. List-related commands
Lpush key string adds a string element to the header of the key corresponding to the list, returns 1 for success, 0 indicates that key exists and is not a list type
Rpush key string Ibid, added at tail
Llen Key returns the length of the list, key does not exist return 0, if the key corresponding type is not a list return error
Lrange Key start end returns the element within the specified interval, the subscript starts at 0, the negative value is calculated from the back, 1 is the last element of the countdown, and key does not exist. Returns an empty list
LTrim key start end intercepts list, retains elements within specified interval, returns 1,key without return error
LSet Key index value sets the value of the element specified in the list, returns 1,key successfully, or the subscript does not have a return error
Lrem Key count value removes the same element as count and value from the key corresponding list. Count is 0 when you delete all
Lpop key removes the element from the head of the list and returns the deleted element. If key corresponds to list does not exist or is null returns NIL if key corresponding value is not list returned error
Rpop Ibid, but removed from the tail
Blpop Key1...keyn Timeout left-to-right scan returns a LPOP operation on the first non-empty list and returns, such as Blpop List1 list2 list3 0, if list does not exist
LIST2,LIST3 are non-null and do Lpop to list2 and return elements removed from List2. If all the lists are empty or nonexistent, the timeout second is blocked, and a timeout of 0 means that it is blocked.
When blocking, if a client has a push operation on any key in Key1...keyn, the first client that is blocked on that key will return immediately. If the timeout occurs, nil is returned. Sort of like a Unix select or poll.
Brpop with Blpop, one is removed from the head and one is removed from the tail
Rpoplpush Srckey Destkey Removes the element from the tail of the srckey corresponding list and adds it to the head of the destkey corresponding to the list, and finally returns the value of the removed element, the entire operation being atomic. If Srckey is empty
Or there is no return nil


4. Set-related commands
Sadd Key member adds a string element to the set set that corresponds to key, successfully returns 1 if the element and the corresponding set returned in the collection 0,key no return error
Srem Key member removes the given element from the key corresponding set, returns 1 successfully, if the member does not exist in the collection or the key does not exist return 0, if the key corresponding to a value other than the set type returns an error
Spop key deletes and returns the key corresponding to a random element in set, if set is empty or key does not exist return nil
Srandmember key with Spop, randomly takes an element in set, but does not delete the element
Smove Srckey Dstkey member remove Srckey from the member corresponding set and add it to the dstkey corresponding set, the entire operation is atomic. A successful return of 1 if member does not exist in Srckey returns 0 if
Key is not a set type return error
SCard Key returns the number of elements of set, if set is empty or key does not exist return 0
Sismember Key member determines whether the member is in set, there is a return 1,0 that does not exist or key does not exist
Sinter key1 Key2...keyn Returns the intersection of all given keys
Sinterstore Dstkey Key1...keyn with Sinter, but will also save the intersection to Dstkey
Sunion key1 Key2...keyn Returns the set of all the given keys
Sunionstore Dstkey Key1...keyn with Sunion, and simultaneously save and set to Dstkey
Sdiff key1 Key2...keyn Returns the difference set for all given keys
Sdiffstore Dstkey Key1...keyn with Sdiff, and simultaneously save the difference set to Dstkey under
Smembers key returns all elements of the set corresponding to the key, the result is unordered


5. Sorted set-related commands
Zadd key score member adds elements to the collection, the element exists in the collection and updates the corresponding score
Zrem Key member Delete the specified element, 1 indicates success, if the element does not exist return 0
Zincrby Key INCR member increases the score value of the corresponding member, then moves the element and keeps the skip list in order. Returns the updated score value
Zrank Key member returns the rank (subscript) of the specified element in the collection, and the elements in the collection are sorted by score from small to large
Zrevrank Key member Ibid, but the elements in the collection are sorted by score from large to small
Zrange key start end resembles the lrange operation to specify the element of the interval from the collection. Returns an ordered result
Zrevrange key Start end Ibid, return result is in reverse order of score
Zrangebyscore Key min Max returns the elements of score in a given interval in the collection
Zcount Key min Max returns the number of score at a given interval in the collection
Zcard Key returns the number of elements in the collection
Zscore key element returns the score corresponding to the given element
Zremrangebyrank key min Max deletes elements in the collection that rank in a given interval
Zremrangebyscore key min Max deletes elements from the collection score at a given interval


6. Hash related commands
Hset key field value sets the hash field to the specified value, and if key does not exist, first create
Hget key field gets the specified hash field
Hmget key FILED1....FIELDN Get all the specified hash filed
Hmset key filed1 value1 ... filedn valuen multiple field with hash set
Hincrby key field integer adds the specified hash filed plus the given value
Hexists key Field test Specifies whether the field exists
Hdel key field deletes the specified hash field
Hlen Key returns the number of field in the specified hash
Hkeys Key returns all field of hash
Hvals key returns all value of hash
Hgetall returns all filed and value of hash

Redis type [string, list, set, sorted set, hash]

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.