Redis Tutorial 2--redis data types and related commands

Source: Internet
Author: User
Tags key string set set redis tutorial value store

The types of data that Redis supports include string, list, set, sorted set, and hash.

Redis-related commands can be viewed: http://redis.io/commands This is the official order manual, also has the Chinese translation: http://redis.readthedocs.org/en/2.4/index.html

1. Keys:

Redis is essentially a key-value store, so get to know its key first. First, the key is also a string type, but the key cannot include boundary characters. 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. 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.

The following key-related commands are described below:

Exits key

Tests whether the specified key exists, returns 1 for existence, 0 does not exist

Del key1 key2 .... KeyN

Deletes the given key, returns the number of deleted keys, and 0 indicates that the given key does not exist

Type key

Returns the value type of the given key. Return none indicates that no key,string character type exists, list linked list type set unordered collection type

Keys pattern

Returns all keys that match the specified pattern

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 atomic renaming of a key, if Newkey exists, will be overwritten, returning 1 for success, and 0 for failure. Maybe Oldkey doesn't exist, or it's the same as Newkey.

Renamenx Oldkey Newkey

Ditto, but if the newkey exists, the 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.

TTL key

Returns the remaining expiration seconds of a key that has set an expiration time-1 indicates that the key does not exist or has not been set for an expiration time

Select 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

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

This method does not fail if you delete all the keys in the current database. Use with caution

Flushall

This method does not fail if all keys in all databases are deleted. Use with caution

Simple example of key-related commands:

Redis 127.0.0.1:6379> Set Test DSF
Ok
Redis 127.0.0.1:6379> Set Tast Dsaf
Ok
Redis 127.0.0.1:6379> Set Tist ADFF
Ok
Redis 127.0.0.1:6379> Keys t*
1. "Tist"
2. "Tast"
3. "Test"
Redis 127.0.0.1:6379> Keys T[ia]st
1. "Tist"
2. "Tast"
Redis 127.0.0.1:6379> Keys T?st
1. "Tist"
2. "Tast"
3. "Test"

2. String:

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. Char 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 by Int. For example, incr and other commands, described in detail below. There are other types of redis like list,set,sorted set, hash they contain elements and can only be string types. If you use only string types, Redis can be seen as a memcached that adds persistence. Of course, Redis has a lot more to do with string types than memcached. As follows:

Set key value

Sets the value of the key corresponding to string type value, 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 the key, if key does not exist return nil

Getset Key value

The value of the atomic setting key 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 is an experiment, first emptying the current database, and then setting k1,k2. Get K3 corresponding return nil

Mset key1 value1 ... keyN valuen

Setting 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

Ditto, but does not overwrite existing key

INCR key

Make a Gaga operation on the value of key and return 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

Ditto, but do the minus and minus operation, DECR a key is not present, then set key to 1

Incrby Key Integer

With INCR, the specified value, key does not exist when the key is set, and the original value is considered to be 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. The subscript is starting from 0.

A simple example of string-related commands:

Redis 127.0.0.1:6379> Set Key Hello
Ok
Redis 127.0.0.1:6379> append K, world
(integer) 11
Redis 127.0.0.1:6379> Get K
"Hello,world"
Redis 127.0.0.1:6379> substr K 0 8
"Hello,wor"
Redis 127.0.0.1:6379> Get K
"Hello,world"
Redis 127.0.0.1:6379> Set K1 a
Ok
Redis 127.0.0.1:6379> set K2 b
Ok
Redis 127.0.0.1:6379> mget K1 K2 K3
1. "A"
2. "B"
3. (nil)

3. List:

The Redis list type is 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) and the list will 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 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 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.

The list-related commands are described below:

Lpush Key string

Adds a string element to the header of the list, returns the number of elements in the list after adding a new element, and 0 indicates that key exists and is not a list type

Rpush Key string

Ibid., add at tail

Llen Key

Returns the key corresponding to 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 in the specified interval, starting at 0, negative values are calculated from the back, 1 means the penultimate element, key does not exist return 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 count and value elements 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 Key

Ditto, but removed from the 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 LIST2 and returns the element deleted from Lpop. 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 list, and finally returns the removed element value, the entire operation is atomic. If the 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. 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 of the key corresponding to the successful return 1, if the element and the returned 0,key in the collection do not have a return error in the corresponding set

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 if 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 null or key does not exist return nil

Srandmember Key

Same as Spop, randomly takes an element in set, but does not delete the element

Smove Srckey Dstkey Member

Remove the member from the Srckey corresponding set and add it to the dstkey corresponding set, the entire operation is atomic. Successful return 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 a set if the set is empty or key does not exist return 0

Sismember Key Member

Determine if the member is in set, there is a return 1,0 that does not exist or the key does not exist

Sinter Key1 Key2...keyn

Returns the intersection of all given keys

Sinterstore Dstkey Key1...keyn

Same as sinter, but will simultaneously 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

Smembers Key

Returns the key corresponding to all the elements of the set, the result is unordered

5.Sorted Set:

Sorted set and set are also collections of elements of type string, but each element is associated with a double type of score. The implementation of the sorted set is a mix of skip list and hash table when the element is added to the collection, an element to the score map is added to the hash table, so the cost of getting the score for a given element is O (1), 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 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.

The following is the sorted set-related command:

Zadd Key Score Member

Adds an element to the collection, the element exists in the collection, and updates the corresponding score

Zrem Key Member

Deletes the specified element, 1 indicates success, if the element does not exist return 0

Zincrby Key INCR Member

Increase the score value of the corresponding member, then move the element and keep the skip list in order. Returns the updated score value

Zrank Key Member

Returns the rank (subscript) of the specified element in the collection, in which the elements are sorted by score from small to large

Zrevrank Key Member

Ditto, but the elements in the collection are sorted by score from large to small

Zrange Key Start end

Similar to the Lrange operation to specify the elements of the interval from the collection. Returns an ordered result

Zrevrange Key Start end

Ibid., return results are in reverse order score

Zrangebyscore Key min Max

Returns the elements of a set in a given interval score

Zcount Key min Max

Returns the number of score in a set in a given interval

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 an element in a collection that is ranked in a given interval

Zremrangebyscore Key min Max

Deletes an element in a collection that score at a given interval

6.Hash:

Redis Hash is a string-type field and value mapping table. It's added, the delete operation is O (1) (average). Hash is particularly useful 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 memory is because it has a storage optimization mechanism, which is described later.

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 to the given value

Hexists key Field

Test to specify whether the field exists

Hdel key Field

Deletes the specified hash field

Hlen Key

Returns the number of field for the specified hash

Hkeys Key

Return hash of all field

Hvals Key

Returns all the value of a hash

Hgetall

Returns all filed and value of the hash

7. View status information:

[[email protected] ~]# REDIS-CLI Info

redis_version:2.4.15

redis_git_sha1:00000000

redis_git_dirty:0

Arch_bits:64

Multiplexing_api:epoll

process_id:2204

Uptime_in_seconds:25

uptime_in_days:0

lru_clock:2013834

used_cpu_sys:0.00

used_cpu_user:0.00

used_cpu_sys_children:0.00

used_cpu_user_children:0.00

Connected_clients:1

connected_slaves:0

client_longest_output_list:0

client_biggest_input_buf:0

blocked_clients:0

used_memory:17505392

used_memory_human:16.69m

used_memory_rss:1617920

used_memory_peak:17496792

used_memory_peak_human:16.69m

mem_fragmentation_ratio:0.09

mem_allocator:jemalloc-2.2.1

loading:0

Aof_enabled:1

Changes_since_last_save:5

bgsave_in_progress:0

last_save_time:1320372561

bgrewriteaof_in_progress:0

Total_connections_received:1

total_commands_processed:0

expired_keys:0

evicted_keys:0

Keyspace_hits:2

Keyspace_misses:8

pubsub_channels:0

pubsub_patterns:0

latest_fork_usec:0

Vm_enabled:1

Role:master

aof_current_size:237

aof_base_size:237

aof_pending_rewrite:0

vm_conf_max_memory:0

Vm_conf_page_size:32

vm_conf_pages:134217728

Vm_stats_used_pages:3

Vm_stats_swapped_objects:3

vm_stats_swappin_count:0

Vm_stats_swappout_count:3

vm_stats_io_newjobs_len:0

vm_stats_io_processing_len:0

vm_stats_io_processed_len:0

vm_stats_io_active_threads:0

vm_stats_blocked_clients:0

Db0:keys=4,expires=0

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Redis Tutorial 2--redis data types and related commands

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.