Redis Information Summary (ii) data type

Source: Internet
Author: User
Tags key string set set

1. Keys

Redis is inherently a key-value db, so let's first look at his key. First, 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

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,
Avoid being entangled by bugs.

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 I also recommend a short key,
Like U:1000:pwd, that kind of. Obviously, the above user:1000:password is very readable.

The following key-related commands are described below

Exits 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 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.

12345 structsdshdr {    long len;    long free;    charbuf[];};

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 processed by a partial command by Int. For example, INCR commands, detailed below. There are other types of redis like list,set,sorted set, hash

They contain both 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. As follows:

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. Here's an experiment, first emptying the current database, and then
Set K1,K2. K3 returns NIL when obtained

redis> Flushdb
Ok
Redis> dbsize
(integer) 0
Redis> set K1 A
Ok
Redis> Set K2 b
Ok
redis> mget K1 K2 K3
1. "A"
2. "B"
3. (nil)

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.

SUBSTR returns the string value of the truncated key, noting that the value of key is not modified. The subscript is starting from 0. (Redis does not include 2.0 after version 2.0, and the method used is the same as the GetRange parameter.) )
Append key value appends value to the string value of the specified key, returning the length of the new string value. Here's 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 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 (1)
The list will also record the length of the linked list. Therefore the Llen operation is also O (1). The maximum length of a linked list is (2 of 32 square-1). We can manipulate the head from the list by Push,pop
or trailing add delete element. 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
The list object is if the list is empty, or does not exist, it returns nil immediately. However, the blocked version of B[lr]pop can be blocked, of course, can be added to the timeout period, after the timeout will also return nil.

Why block versions of Pop, primarily to avoid polling. As a simple example, if we use list to implement a Task Force column. The thread that performs the task can invoke the blocked version of the pop to get the task so that the polling can be avoided 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.

OK here's a list-related command Lpush key string adds a string element to the header of the key corresponding to the list, returns 1 for success, 0 means that key exists and is not a list type
Rpush key string, with the trailing
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 means the last element of the countdown, key does not exist return empty list
LTrim key start end  intercept list, retain elements within the specified interval, successful return 1,key there is no return error
LSet key index value Sets the element value of the specified subscript in the list, successfully returning 1,key, or the subscript does not have a return error
Lrem key count value removes count and value elements from the key corresponding list. When Count is 0, all
Lpop key is removed from the head of the list and the element is deleted. If key corresponds to list does not exist or is empty returns nil, if key corresponding value is not list returned error
Rpop Ibid, but removed from tail
Blpop Key1...keyn Timeout A left-to-right scan returns a LPOP operation on the first non-empty list and returns, such as Blpop List1 list2 list3 0, if the list does not exist
List2,list3 is non-null and LIST2 is lpop and returns the element 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. A bit like a Unix Select or poll
Brpop with Blpop, one to remove from the head is to delete 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 list, and finally returns the removed element value, the entire operation is atomic. If Srckey is empty
or does not exist return nil

4. Set

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 (1). 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's union, intersection (intersection), and difference set (difference). Through these actions can easily realize the SNS in the Friend referral and blog tag function. Set-related commands are detailed below

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

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 (1), and another score-to-element mapping is added to the skip list and sorted by score. So you can get the elements in the collection in an orderly fashion. Add, the cost of the delete operation is the same as the cost of O (log (N)) 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. Here is the sorted set related command

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

Redis Hash is a string-type field and value mapping table. It is added, and the delete operation is O (1) ( average ). Hash is ideal 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

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个
Hash-max-zipmap-value #配置value最大为512字节
The following describes the 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 Information Summary (ii) data type

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.