The Redis command uses

Source: Internet
Author: User
Tags add numbers data structures hash numeric min redis serialization set set

prior to the installation of Redis, for how to use, is not particularly clear, so Baidu down, at the same time combined with their own common commands, did the next integration,

The following are some of the commonly used commands;

  < /c14>1 Redis data types and application scenarios

The most commonly used data types of Redis are the following five kinds:

· String

· Hash

· List

· Set

· Sortedset The following figure describes how these different data types are described in Redis internal memory management:


First, Redis internally uses a Redisobject object to represent all key and value,redisobject most important information as shown in the figure above: type represents what data type a value object is, Encoding is how different data types are stored inside the Redis, such as: Type=string represents a normal string for value, then the corresponding encoding can be raw or int, If it is an int, the actual redis interior is stored and represented by a numeric class, assuming that the string itself can be represented numerically, such as a string such as "123" "456". Here you need to specify the VM field, only the virtual memory feature of Redis is turned on, this field will actually allocate memory, which is turned off by default, which is described later in this function. Using the above figure, we can find that Redis uses Redisobject to represent all key/value data as a waste of memory, and of course, the cost of memory management is mainly to provide a unified management interface for different data types of Redis. The actual author also offers several ways to help us save memory as much as possible, which we'll discuss in detail later.

1.1String Type

Common commands:

Set,get,decr,incr,mget and so on.

Application Scenarios:

String is the most commonly used type of data, and ordinary key/value storage can be categorized as such, which is not explained here.

Implementation method:

String in the Redis internal storage By default is a string, referenced by Redisobject, when encountered INCR,DECR and other operations will be converted to a numeric type for calculation, at this time Redisobject encoding field is an int.

1.2List Type

Common commands:

Lpush,lpop,rpop,lrange and so on.

Application Scenarios:

Redislist has a lot of applications and is one of the most important data structures of redis, such as Twitter's watchlist, fan list, etc., which can be implemented using the REDIS list structure, which is better understood and not repeated here.

Implementation method:

The implementation of Redislist is a doubly linked list, which can support reverse lookup and traversal, more convenient operation, but with some additional memory overhead, many implementations within Redis, including sending buffer queues, are also used in this data structure.

1.3Set Type

Common commands:

Sadd,spop,smembers,sunion and so on.

Application Scenarios:

Redisset external functionality is a list-like feature, except that set is automatic, and when you need to store a list of data and you don't want duplicate data, set is a good choice. and set provides an important interface to determine whether a member is within a set set, which is not available in list.

Implementation method:

The internal implementation of set is a value that is always null hashmap, which is actually calculated by hashing the way to fast weight, which is also set to provide a judge whether a member is within the cause of the collection.

1.4Sorted set Type

Common commands:

Zadd,zrange,zrem,zcard, etc.

Usage Scenarios:

Redissorted Set's usage scenario is similar to set, except that the set is not automatically ordered, and the sorted set can be ordered by the user by providing an additional priority (score) parameter, and is inserted in an ordered, automatic sort. When you need an ordered and non-repeating collection list, you can choose sorted set data structures, such as the public Timeline of Twitter, which can be stored as score in the publication time, which is automatically sorted by time.

Implementation method:

redissorted set internal use HashMap and jump Table (skiplist) to ensure the storage and ordering of data, HashMap in the member to score mapping, and the jumping table is all the members, sorted by HashMap in the score , the use of the structure of the jumping table can obtain a relatively high efficiency of finding, and it is relatively simple to implement.

1.5Hash Type

Common commands:

Hget,hset,hgetall and so on.

Application Scenarios:

Let's simply cite an example to describe the application scenario for a hash, such as storing a user information object data that contains the following information:

The user ID is the key to find, the stored value user object contains the name, age, birthday and other information, if the ordinary key/value structure to store, mainly has the following 2 kinds of storage methods:



The disadvantage of using the user ID as a lookup key to encapsulate other information as a serialized object is to increase the cost of serialization/deserialization and to retrieve the entire object when one of the information needs to be modified, and the modification operation requires concurrency protection. Introduce complex problems such as CAs.



The second method is how many members of this user information object will be saved into the number of key-value, with the user id+ the name of the corresponding property as a unique identifier to obtain the value of the corresponding property, although the cost of serialization and concurrency is omitted, but the user ID is repeated storage, if there is a large number of such data, The memory waste is still very considerable.

So the hash provided by Redis is a good solution to this problem, the Redis hash is actually the internal storage value of a hashmap, and provides direct access to the map member interface, as shown below:



That is, the key is still the user ID, value is a map, the map key is a member of the property name, value is the property value, so that the data can be modified and accessed directly through its internal map key (Redis called internal map key field), This means that the corresponding attribute data can be manipulated by key (user ID) + field (attribute tag), without the need to store the data repeatedly and without the problem of serialization and concurrency modification control. A good solution to the problem.

It is also important to note that Redis provides an interface (Hgetall) that can fetch all of the property data directly, but if the internal map has a large number of members, it involves traversing the entire internal map, which can be time-consuming due to the Redis single-threaded model. The other client requests are not responding at all, which requires extra attention.

Implementation method:

The above has been said that the Redis hash corresponds to value inside the actual is a hashmap, actually there will be 2 different implementations, this hash of the members of the relatively small redis in order to save memory will be similar to a one-dimensional array to compact storage, without the use of a real HASHMAP structure , the encoding of the corresponding value Redisobject is Zipmap, and when the number of members increases, it automatically turns into a true hashmap, at which time encoding is HT.

2 Redis data type related commands 2.1String Command

String data type String

The string type is a redis base data type that can store any form of string, including binary data.

Set Key value Assignment

Get key value

INCR key Increment number (all Redis commands are atomic operations)

Redis key naming Practice Object type: Object ID: Object properties, recommended for multiple words. Split. If the key user:1:friends represents the friend list of the user with ID 1.

Incrby key increment increments the specified integer

Decrby key decrement reduces the specified integer

Incrbyfloat key increment add specified floating-point number

Append key value appends a value to the tail, returning the length of the appended string

Strlen Key returns the length of the key value

Mget key [key ...] get multiple health values

Mset key value [key value ...] set multiple key values

-bit operation

Getbit key offset gets a string specifying the position of the bits value (0 or 1)

Setbit Key offset value sets the binary value of the string type key at the specified position, returning the old value of that position

Bitcount key [start] [end] counts the number of bits with a value of 1 in the string type and can specify the range of bytes

Bitop operation Destkey Key [key ...] (And, or, XOR, not)

2.2List Command

A list type can store an ordered list of strings, and a common operation is to add elements to the list or to get a fragment of a list.

Internal use of the two-way list implementation, get closer to both ends of the element speed is faster, but the index access element is slow. List types can be very quick to complete scenarios where relational databases are difficult to cope with, such as social networking novelty.

Lpush key value [value ...] adds an element from the left side of the list

Rpush key value [value ...] adds an element to the right of the list

Lpop key pops the element from the left of the list

Rpop key POPs elements from the right of the list

Llen Key gets the number of elements in the list

Lrange key start stop gets the list fragment (including Stop, which supports negative numbers to start counting from the far right)

Lrem key count value is deleted before count values are elements (count>0 is removed from the left, count<0 is removed from the right, count=0 delete all elements that are value)

Lindex key index Gets the element value for the specified index

LSet Key index value sets the element values for the specified indexes

LTrim key start end preserves only the specified fragment

Linsert key Fefore|after Pivot value first finds the pivot element from left to right, and then inserts value in front of or behind the element according to the second entry.

Rpoplpush source Destination Transfers One element to another list, atomic operation. When source and destination are the same, they will continue to move the tail element to the team head to implement the website monitoring system.

2.3Set Command

The collection type is different for each element and unordered.

Sadd key member [member ...] adds element, returns the number of elements successfully added

Srem Key member [member ...] delete element

Smembers key gets all the elements in the collection

Sismember Key member determine if there is a collection of

Inter-collection operations

Sdiff [destination] key [key ...] multiple set differential operation A-B and stored in destination

sinter [destination] key [key ...] multiple collections perform intersection operations

sunion [destination] key [key ...] multiple collection seek and compute

The number of elements in the SCard key collection

Srandmemeber key [Count] randomly obtains the elements in the collection (when count>0 randomly gets count of distinct elements, count<0 does not guarantee repetition)

Spop key randomly pops an element from the collection

2.4Sorted set Command

List types are implemented through linked lists, getting data near both ends extremely fast, when the element is incremented and the intermediate element is slower, and is more suitable for applications that rarely access intermediate elements such as "novelty" or "log".

The ordered collection type is implemented by hashing and jumping tables, so even if the reading is in the middle position it is very fast O (NLGN).

You cannot easily adjust an element position in a list, and an ordered collection can. An ordered set consumes more memory.

Zadd key score member [score member ...] joins an element and the fraction of that element (fractions can be integers or decimals, +inf and-inf represent positive and negative infinity)

Zscore key member get the fraction of the element

Zrange key start stop [Withscore] returns all elements between start and stop in order from small to large (Withscore indicates band score) complexity O (logn+m)

Zrevrange key start stop [Withscore] from large to small order

Zrangebyscore key min Max [withscore] [limit offset count] returns the element between Min and Max according to small to large

Zincrby key increment member increase the score of an element

Zcard Key gets the number of elements in the collection

Zcount Key min Max gets the number of elements in the specified range

Zrem key member [member ...] deleting one or more elements

Zremrangebyrank key start stop removes all elements in the specified rank range by element fraction from small to large, and returns the number of deleted elements

Zremrangebyscore Key min Max deletes all elements in the specified fraction range

Zrank Key member get the ranking of the elements

Zrevrank Key Member

2.5Hash Command

The key value of a hash type is also a dictionary structure that stores the mappings of fields and field values, but the field values can only be strings and no other types are supported. (collection types also do not support data type nesting)

Hset key field value Assignment (returns 1 on INSERT, 0 on update)

Hget key field value

Hmset key field value [field value ...]

Hmget key field [Feild ...]

Hgetall Key

Hexists key field to determine whether the fields exist

Hsetnx key field value is assigned when the field does not exist

Hincrby key field increment add numbers

Hdel key field [field ...] Delete field

Hkeys Key Gets the field name only

Hvals key only gets field values

Hlen key to get the number of fields

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.