Redis Study Notes Data Type

Source: Internet
Author: User
Tags key string set set

This document describes various data types supported by redis, including string, list, set, sorted set, and hash.

 

1. Keys
Redis is essentially a key-value dB, so let's first look at its key. First, the key is also a string type, but the key cannot contain boundary characters.
Keys that contain spaces and line breaks are not allowed because they are not binary safe strings.
By the way, redis does not limit the use of binary characters, which is restricted by the redis protocol. "\ R \ n" is a special character in the Protocol format.
Some commands in redis 1.2 and later protocols have begun to use the new protocol format (such as mset ). At present, we should regard boundary characters as invalid keys,
Avoid being entangled by bugs.
In addition, object-type: ID: field is an introduction to a key Format Convention. For example, user: 1000: Password, blog: xxidxx: Title
The length of the key should not be too long. The reason is that the memory usage is obvious, and the query time is relatively short and the key usage is slower. However, too short keys are also recommended,
Such as U: 1000: Pwd. Obviously, the above User: 1000: password is not readable.

The following describes the key-related commands.
exits key tests whether the specified key exists. If the returned value is 1, 0 exists.
Del key1 key2 .... if the keyn deletes a given key, the number of deleted keys is returned. If the value is 0, no value exists for the given key.
type key returns the value type of the given key. If the return value is none, the key does not exist. The string character type. The list linked list type is set unordered...
keys pattern returns all keys matching the specified mode, the following is an example of
redis> set test DSF
OK
redis> set tast DSAF
OK
redis> set TIST adff
OK
redis> Keys T *
1. "TIST"
2. "tast"
3. "test"
redis> Keys T [Ia] st
1. "TIST"
2. "tast"
redis> Keys T? St
1. "TIST"
2. "tast"
3. "test"

randomkey: returns a randomly selected key from the current database. If the current database is empty, an empty string is returned.
rename the oldkey newkey atom to rename a key. If newkey exists, it will be overwritten. If 1 is returned, it indicates success and 0 fail. It may be that the oldkey does not exist or is the same as newkey
renamenx oldkey newkey is the same as above, however, if newkey exists, return failure
dbsize returns the number of keys in the current database
expire key seconds specifies the expiration time for the key, in seconds. Return 1 success, 0 indicates that the key has been set to expire or does not exist
TTL key returns the remaining expiration seconds of the key with the set expiration time-1 indicates that the key does not exist or has not been set to expire
select DB-index select the database through the index, the default number of connected databases is 0, and the default number of databases is 16. If 1 is returned, the operation is successful. If 0 is returned,
move key DB-index moves the key from the current database to the specified database. 1 is returned. 0 if the key does not exist or you have already deleted all the keys in the current database in the specified database
flushdb, this method will not fail. Use
flushall with caution to delete all keys in all databases. This method will not fail. More cautious

2. string type
string is the most basic type of redis, and the string type is binary secure. It means that the redis string can contain any data. For example, JPG images or serialized objects
. From the internal implementation, the string can be viewed as a byte array, and the maximum value is 1 GB. The following is the definition of the string type.
struct sdshdr {
long Len;
long free;
char Buf [];
};
Buf is a char array used to store the actual string content. In fact, byte in char and C # is equivalent, both of which are one byte
Len is the length of the Buf array, and free is the remaining number of available bytes in the array. We can understand why the string type is binary secure. Because it is essentially a byte array.
of course, it can contain any data. In addition, some commands of the string type can be processed by INT, such as incr. The following describes in detail. Other types of apsaradb for redis, such as list, set, sorted set, and hash
, can only contain elements of the string type.
if only the string type is used, redis can be regarded as memcached with the persistence feature. Of course, redis has more operations on the string type than memcached.

Set key value: set the value corresponding to the key to the string type value. If the return value is 1, the operation is successful, and the return value is 0.
The setnx key value is the same as the preceding one. If the key already exists, 0 is returned. NX means not exist
Get key obtains the string value corresponding to the key. If the key does not exist, Nil is returned.
GetSet key value atomic set key value, and return the old value of the key. If the key does not exist, Nil is returned.
Mget key1 key2... keyn obtains the values of multiple keys at a time. If the corresponding key does not exist, Nil is returned. The following is an experiment. First, clear the current database, and then
When K1 and k2are set, corresponding NIL is returned for K3.
Redis> flushdb
OK
Redis> dbsize
(Integer) 0
Redis> set K1
OK
Redis> set K2 B
OK
Redis> mget K1 K2 K3
1. ""
2. "B"
3. (nil)

Mset key1 value1... keyn valuen multiple key values are set at a time. Success returns 1, indicating that all values are set. Failure Returns 0, indicating that no value is set.
Msetnx key1 value1... keyn valuen is the same as above, but the existing key is not overwritten.
Incr key adds the key value and returns a new value. Note that if incr is not an int value, an error is returned. If incr is a non-existent key, the key is set to 1.
The decr key is the same as the key, but the subtraction operation is performed. If a decr key does not exist, the key is set to-1.
Incrby key integer is the same as incr, and a specified value is added. If the key does not exist, the key is set and the original value is 0.
Decrby key integer is the same as decr, and the specified value is subtracted. Decrby is completely for readability. We can use a negative value of incrby to achieve the same effect, and vice versa.

Append key value appends value to the string value of the specified key, and returns the length of the new string value. The following is an example.
Redis> set K hello
OK
Redis> append K, world
(Integer) 11
Redis> get K
"Hello, world"

Substr key start end returns the string value of the truncated key. Note that the key value is not modified. The subscript starts from 0.
Redis> substr K 0 8
"Hello, wor"
Redis> get K
"Hello, world"

3. List

The list type of redis is actually a two-way linked list of the string type for each sub-element. So the [LR] Push and [LR] pop commandsAlgorithmTime complexity is O (1)
In addition, the list records the length of the linked list. Therefore, the llen operation is O (1). the maximum length of the linked list is (32 power-1 of 2 ). We can use the push and pop operations to extract the head of the linked list
Or add the deletion element at the end. This allows the list to be used as both a stack and a queue. It is interesting that the pop operation of list also has a blocking version. When we [LR] Pop
The list object is. If the list object is empty or does not exist, Nil is returned immediately. However, B [LR] Pop of the blocked version can be blocked. Of course, a timeout value can be added, and nil will be returned after the timeout.
. Why is pop blocked? It is mainly used to avoid polling. A simple example is to use list to implement a work queue. The thread that executes the task can call the pop of the blocked version.
In this way, you can avoid polling to check whether a task exists. When a task comes, the worker thread can return immediately or avoid the delay caused by polling. OK. The following describes the list-related commands.

Lpush key string adds a string element to the header of the list corresponding to the key. If the return value is 1, the result is successful. If the return value is 0, the key exists and is not of the list type.
Rpush key string is the same as above. Add it at the end
Llen key returns the length of the list corresponding to the key. If the key does not exist, 0 is returned. If the key type is not list, an error is returned.
Lrange key start end: returns the elements in the specified range. The subscript starts from 0, and the negative value indicates calculation from the end.-1 indicates the last element. If the key does not exist, an empty list is returned.
Ltrim key start end intercepts the list and retains the elements in the specified range. 1 is returned successfully. If the key does not exist, an error is returned.
When the lset key index value is set to the element value specified in the list, 1 is returned successfully. If the key or subscript does not exist, an error is returned.
The lrem key Count value deletes the same count and value elements from the list corresponding to the key. Delete all when count is 0
The lpop key deletes the element from the list header and returns the deletion element. If the list corresponding to the key does not exist or is null, Nil is returned. If the corresponding value of the key is not a list, an error is returned.
Rpop is the same as above, but deleted from the end
Blpop key1. .. keyn timeout from left to right scan and return lpop for the first non-empty list and return, such as blpop list1 list2 list3 0. If the list does not exist
If list2 and list3 are both non-empty, lpop is performed on list2 and elements deleted from list2. If all lists are empty or do not exist, the timeout seconds are blocked. If the value of timeout is 0, the system is blocked all the time.
If a client pushes any key in key1. .. keyn when blocking, the client that is first blocked on this key will return immediately. If timeout occurs, Nil is returned. A bit like select or poll in UNIX
Brpop is the same as blpop. One is to delete from the header and the other is to delete from the tail.

Rpoplpush srckey destkey removes elements from the end of the srckey list and adds them to the header of the list corresponding to the destkey. Finally, the removed element value is returned. The entire operation is atomic. If the srckey is empty
Or nil does not exist.

4. Set
the redis set is a unordered set of the string type. The Set element can contain a maximum of (32 to the power of 2-1) elements. Set is implemented through hash table, so the complexity of adding, deleting, and searching is O (1 ). The hash table is automatically adjusted with the addition or deletion. Note that synchronization (get write lock) is required when the hash table size is adjusted to block other read/write operations. The Skip table (Skip List) may be used soon to implement the
skip table already used in sorted set. Except for basic addition and deletion operations, other useful operations include union, intersection, and
difference ). Through these operations, you can easily implement the friend recommendation and blog tag FUNCTIONS In SNS. The following describes the set commands in detail.

sadd key member adds a string element to the Set set corresponding to the key. 1 is returned successfully. If the element and 0 are returned in the set, if the set corresponding to the key does not exist, an error is returned.
Srem key member removes the given element from the set corresponding to the key. If the member does not exist in the set or the key does not exist, 0 is returned, if the key is not a set value, an error is returned.
the spop key is deleted and a random element in the set corresponding to the key is returned, if the set is null or the key does not exist, the returned nil
srandmember key is the same as the spop. An element in the set is randomly taken, but do not delete the element
smove srckey dstkey member removes the Member from the set corresponding to the srckey and adds it to the set corresponding to the dstkey. The entire operation is atomic. 1 is returned successfully. If member does not exist in the srckey, 0 is returned. If
key is not set type, an error is returned.
scard key returns the number of set elements, if the set is null or the key does not exist, 0 is returned.
sismember key member determines whether the Member is in the set. If yes, 1 is returned. If yes, 1 is null, or the key does not exist.
sinter key1 key2... keyn returns the intersection of all given keys
sinterstore dstkey key1... keyn is the same as sinter, but the intersection is saved to dstkey
sunion key1 key2... keyn returns the union of all given keys
sunionstore dstkey key1... keyn is the same as sunion, and the Union is saved to dstkey
sdiff key1 key2... keyn returns the difference set of all given keys
sdiffstore dstkey key1... keyn is the same as sdiff and saves the difference set to dstkey.
smembers key returns all elements of the set corresponding to the key. The result is unordered.

5 sorted set
sorted set, like set, is also a set of string-type elements, the difference is that each element is associated with a score of the double type. The implementation of sorted set is a mixture of Skip List and hash table
when an element is added to a set, the score ing from one element to the score is added to the hash table, therefore, the overhead for getting score from an element is O (1). the ing from another score to the element is added to the Skip List
and sorted by score, so we can get the elements in the set in order. The overhead of adding and deleting operations is the same as that of O (log (N) and Skip List. redis's Skip List uses a two-way linked list, in this way,
elements can be retrieved from the tail in reverse order. Sorted set is most frequently used as an index. We can store the fields to be sorted as scores, and the Object ID is stored as an element. The following are the commands related to sorted set

zadd key score: add an element to the set. If an element exists in the Set, the corresponding score is updated.
zrem key: delete a specified element. 1 indicates that the element is successfully deleted, if the element does not exist, 0 is returned.
zincrby key incr member increases the score value of the corresponding member, 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 set ), elements in the set are sorted by score from small to large
zrevrank key member is the same as above, however, the elements in the set are sorted by score in ascending order.
the zrange key start end operation is similar to the lrange operation. The returned result is an ordered result.
the zrevrange key start end is the same as the preceding one, the returned results are sorted in reverse order.
zrangebyscore key min Max returns the elements of the score in the given range in the set.
zcount key min Max returns the number of scores in the given range in the set.
zcard key returns the number of elements in the set.
zscore key element returns the score corresponding to the given element.
zremrangebyrank key min max deletes the elements ranked in the given range in the set.
zremrangebyscore key min max deletes the element of the score in the specified range in the set

6. Hash
Redis hash is a ing table of field and value of the string type. It is added and deleted by O (1 )(Average). Hash is particularly suitable for storing objects. Compared to saving each field of an object
Single string type. Storing an object in the hash type consumes less memory and makes it easier to access the entire object. Memory saving is because zipmap (also known as small hash) is used to store a new hash object. This zipmap is not actually a hash table, but zipmap can save a lot of metadata storage overhead for hash compared to normal hash implementation. Although zipmap's addition, deletion, and search operations are all O (n), the number of fields of general objects is not large. Therefore, the use of zipmap is also very fast, that is to say, the average addition and deletion is still O (1 ). If the size of field or value exceeds a certain limit, redis will automatically replace zipmap with a normal hash internally. This limit can be specified in the configuration file.

Hash-max-zipmap-entries 64 # up to 64 configuration fields
Hash-max-zipmap-value 512 # set the maximum value to 512 bytes.

The following describes hash commands.
Hset key field value: Set hash field to the specified value. If the key does not exist, create
Hget key field to get the specified hash Field
Hmet key filed1. .. fieldn get all the specified hash filed
Hmset key filed1 value1... filedn valuen simultaneously sets multiple hash Fields
Hincrby key field integer adds the specified hash filed Value
Hexists key field test whether the specified field exists
Hdel key field deletes the specified hash Field
Hlen key returns the number of specified hash Fields
Hkeys key returns all fields in the hash
Hvals key returns all hash values
Hgetall returns all the filed and value of the 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.