This document describes various data types supported by redis, including string, list, set, sorted set, and hash.
Technorati label: redis cache list Storage
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 key-related commands.
Exits key to test whether the specified key exists. If the return value is 1, the specified key exists, and the return value is 0.
Del key1 key2... keyn deletes a given key and returns the number of deleted keys. 0 indicates that none of the given keys exist.
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.
Randomkey returns a random key selected 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 fails. It may be that the oldkey does not exist or is the same as the newkey.
Renamenx oldkey newkey is the same as above, but if newkey exists, return failure
Dbsize returns the number of keys of the current database.
Expire key seconds specifies the expiration time for the key, in seconds. 1 is returned successfully. 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 specified expiration time.-1 indicates that the key does not exist or the expiration time has not been set.
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. 1 indicates success, 0 indicates failure
Move key DB-index: Move the key from the current database to the specified database. 1 is returned. 0 if the key does not exist or it is already in the specified database
Flushdb deletes all keys in the current database. This method will not fail. Use with caution
Flushall deletes 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: the value corresponding to the key is string type. If the return value is 1, the value is successful, and the return value is 0.
the setnx key value is the same as the preceding one. If the key already exists, returns 0. NX indicates not exist.
get key obtains the string value corresponding to the key. If the key does not exist, Nil is returned.
GetSet key value indicates the value of the set key, and return the old value of the key. If the key does not exist, nil
mget key1 key2... keyn is returned to obtain the values of multiple keys at a time. If the corresponding key does not exist, Nil is returned. The following is an experiment. First, empty the current database, and then
set K1, K2. return nil when K3 is obtained
Redis>Flushdb
OK
Redis>Dbsize
(Integer) 0
Redis>Set K1
OK
Redis>Set K2B
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. Substr returns the string value of the truncated key. Note that the key value is not modified. The subscript starts from 0. (redis Versions later than 2.0 do not include 2.0. The getrange parameter is the same .)
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
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 commandsAlgorithm Time 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
Redis's 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. It may soon be implemented using the Skip table (Skip List ).
The table has been used in sorted set. In addition to basic addition and deletion operations, other useful operations also include union and intersection of sets ),
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, an error is returned if the set corresponding to the key does not exist.
Srem key member removes the given element from the set corresponding to the key. If member does not exist in the set or the key does not exist, 0 is returned. If the key does not belong to the set type, 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 NIL is returned.
Srandmember key is the same as spop. An element in the set is randomly selected, but the element is not deleted.
Smove srckey dstkey member removes the Member from the srckey's corresponding set and adds it to the dstkey's corresponding set. The entire operation is atomic. If member does not exist in srckey, 0 is returned. If
An error is returned when the key is not of the set type.
Scard key returns the number of set elements. If 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 or 0 is returned, indicating that the member does not exist 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 under dstkey at the same time.
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 under dstkey.
Sdiff key1 key2. .. keyn returns the difference set of all given keys
Sdiffstore dstkey key1. .. keyn is the same as sdiff, and the difference set is saved under dstkey.
Smembers key returns all elements of the set corresponding to the key, and the result is unordered.
5 sorted set
Similar to set, sorted set is also a set of string 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 an element to 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 sequence. 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.
You can retrieve elements from the end 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 in member. If an element exists in the Set, the corresponding score is updated.
Zrem key member deletes the specified element. 1 indicates that the operation is successful. If the element does not exist, 0 is returned.
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 ranking (subscript) of the specified Element in the set. The elements in the set are sorted by score in ascending order.
Zrevrank key member is the same as above, but the elements in the set are sorted by score in ascending order.
The zrange key start end operation is similar to the lrange operation to specify the range elements from the collection. The returned result is an ordered result.
Zrevrange key start end is the same as above. The returned results are in reverse order of score.
Zrangebyscore key min Max returns the element of the score in the specified range in the collection.
Zcount key min Max returns the number of scores in the specified range in the set.
Zcard key returns the number of elements in the set.
The zscore key element returns the score corresponding to the given element.
Zremrangebyrank key min max deletes the elements in the specified range in the collection.
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.
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"
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.
From: http://www.cnblogs.com/xhan/archive/2011/02/02/1948891.html