Redis common command notes

Posted by on Fri, 11 Feb 2022 22:06:07 +0100

1, Common commands for keys

keys * View all current key
exists key Judge a key Does it exist
type key View your key What type is it
del key Delete the specified key data
unlink key according to value Select non blocking delete to delete only keys from keyspace If the metadata is deleted, the real deletion will be carried out in subsequent asynchronous operations.
expire key 10 For a given key Set 10 second expiration time
ttl key See how many seconds are left to expire,-1 Means never expires,-2 Indicates that it has expired
select Switch database
dbsize View the current database key Number of
flushdb Empty current library
flushall Empty all libraries

2, Redis String (String)

1. Introduction

String is the most basic type of Redis. A key corresponds to a value.

The string type is binary safe (as long as the content can be represented by a string, it can exist in this type). It means that the string of IDS can contain any data. For example, jpg images or serialized objects.

String type is the most basic data type of IDS. The string value in a Redis can be 512M at most.

2. Common commands

set <key> <value>
get <key> Query corresponding key value
append <key> <value> Will the given<value>Append to the end of the original value
strlen <key> Get the length of the value
setnx <key> <value> only key It can only be set when it does not exist key
incr <key> take key If the number stored in is increased by 1, you can only operate on the number value. If it is empty, the new value-added is 1
decr <key> take key The numeric value stored in minus 1
incrby/decrby <key><step> take key Increase or decrease the digital value stored in. Custom step size.
mset <key1><value1><key2><value2> Set one or more at the same time key-value yes
mget <key1><value1><key2><value2> One or more at the same time value
msetnx <key1><value1><key2><value2> Set one or more at the same time key-value Yes, if and only if all given key If there is no existence, you can succeed. If there is one existence, you will fail. Atomicity, there is a failure, all of them fail
getrange <key><Starting position><End position> Obtain the range of values, and the results include the start position and end position
setrange <key><Starting position><value> use value make carbon copies<key>Stored string value, from<Starting position>Start (index starts at 0).
setex <key> <Expiration time> <value> Set the expiration time in seconds while setting the key value.
getset <key><value> Replace the old with the new, set the new value and obtain the old value at the same time.

Note that incr and decr are atomic.

The so-called atomic operation refers to the operation that will not be interrupted by the thread scheduling mechanism;

Once this operation starts, it will run until the end, and there will be no context switch in the middle.

  1. In a single thread, any operation that can be completed in a single instruction can be regarded as an "atomic operation", because interrupts can only occur between instructions.
  2. In multithreading, operations that cannot be interrupted by other processes (threads) are called principle operations.

The atomicity of Redis single command is mainly due to the single thread of Redis.

3, Redis List

1. Introduction

Single key multi value. Redis list is a simple string list, sorted by insertion order. You can add an element to the head (left) or tail (right) of the list.

Its bottom layer is actually a two-way linked list, which has high operation performance at both ends. The performance of the middle node through the operation of index subscript will be poor.

2. Common commands

lpush/rpush <key1><value1><value2><value3> From the left/Insert one or more values to the right
lpop/rpop <key> From the left/Spit out a value on the right. The value is in the key, and the value light key dies.
rpoplpush <key1><key2> from<key1>Spit out a value on the right side of the list and insert it into<key2>To the left of the list.
lrange <key><start><stop> Get elements by index subscript (from left to right), such as lrange mylist 0 -1 Means get all
lindex <key><index> Get elements by index subscript (left to right)
llen <key> Get list length
linsert<key> before/after <value> <newvalue> stay value Insert before or after newvalue value
lrem <key><n><value> Delete from left n The first name is value Value of
lset <key><index><value> Will list key Subscript index Replace the value of with value

3. Underlying data structure

The data structure of List is quicklist. First, when there are few List elements, a continuous memory storage will be used. This structured ziplost is also called compressed List. It stores all the elements next to each other and allocates a continuous piece of memory.

When there is a large amount of data, it will be changed to quicklist. Because the additional pointer space required by ordinary linked lists is too large, it will waste space. For example, only int type data is stored in the list, and two additional pointers prev and next are required in the structure.

Redis combines the linked list and zipplist to form a quicklist. That is to string multiple ziplist s using bidirectional pointers. This not only meets the fast insertion and deletion performance, but also does not appear too much spatial redundancy.

4, Redis Set

1. Introduction

The function provided by set is similar to that of a list. The special feature is that set can be rearranged automatically. When you need to store a list data and do not want duplicate data, set is a good choice, and set provides an important interface to judge whether a member is in a set set, which is not provided by list.

Set is an unordered set of string type. Its bottom layer is actually a hash table with null value, so the complexity of adding, deleting and searching is O(1).

2. Common commands

sadd <key><value1><value2>.... One or more member Add element to collection set Existing in member Element will be ignored.
smembers <key> Fetch all values of the set
sismember <key> <value> Judgment set<key>Whether it contains the<value>Value, 1 if any, otherwise 0
scard <key> Returns the number of elements in the collection
srem <key><value1><value2>.. Delete an element in the collection
spop <key> Spit out a value randomly from the set.
srandmember <key><n> Randomly extracted from the set n A value that will not be deleted from the collection.
smove <source><destination><value> Moves a value in a set from one set to another
sinter <key1><key2> Returns the intersection element of two collections
sunion <key1><key2> Returns the union element of two collections
sdiff <key1><key2> Returns the difference element of two sets(key1 In, excluding key2 Medium)

3. Underlying data structure

The set data structure is a dict dictionary, which is implemented with a hash table.

The internal implementation of HashSet in Java uses HashMap, but all values point to the same object. Redis's set structure is the same. It also uses a hash structure internally. All values point to the same internal value.

5, Redis Hash

1. Introduction

redis hash is a set of key value pairs, similar to map < string, Object > in java.

redis hash is a mapping table of field and value of string type. Hash is especially suitable for storing objects.

Considering the following situations, it is necessary to store a student's information.

  • Method 1: user: "{id=1,name=zhangsan,age=20}". Using method 1 means that the key is user and the value is the string of characters. In this way, it is very inconvenient to modify the information.
  • Method 2: user:id 1 user:name zhangsan user:age 20. Method 2 means to store the data with three key values. In this way, the data is stored dispersedly, and it is difficult to deal with a large amount of data
  • Method 3: user:[id=1,name=zhangsan,age=20], using the hash method of redis.

2. Common commands

hset <key><field><value>   to<key>In the collection<field>Key assignment<value>
hget <key><field> from<key>aggregate<field>take out value
hmset <key1><field1><value1><field2><value2>... Batch setting hash Value of
hexists <key><field> View hash table key Given domain field Whether it exists.
hkeys<key> List this hash All of the collection field
hvals<key> List this hash All of the collection value
hincrby<key><field><increment> Is a hash table key Domain in field Value plus increment
hsetnx <key><field><value> Hash table key Domain in field The value of is set to value,If and only if domain field When not present

3. Data structure

There are two data structures corresponding to hash type: ziplost (compressed list) and hashtable (hash table). When the length of field value is short and the number is small, use ziplist; otherwise, use hashtable.

6, Redis ordered set Zset

1. Introduction

Redis ordered set zset is very similar to ordinary set. It is a string set without duplicate elements.

The difference is that each member of the ordered set is associated with a score, which is used to sort the members of the set from the lowest score to the highest score. The members of the collection are unique, but the scores can be repeated.

Because the elements are ordered, you can also quickly get a range of elements according to score or position.

Accessing the intermediate elements of an ordered set is also very fast, so you can also use an ordered set as a smart list without duplicate members.

2. Common commands

zadd <key><score1><value><score2><value2>... One or more member Element and its score Add value to ordered set key among.
zrange <key><start><stop>[withscores] Returns an ordered set key Middle, subscript in<start><stop>Elements between, with withscores,You can return scores and values together to the result set.
zrangebyscore key min max [withscores][limit offset count]Returns an ordered set key Medium, all score Value between min and max Between (including equal to) min or max)Members of. Ordered set members by score Value increment order
zrevrangebyscore key max min [withscores][limit offset count]Same as above, change from large to small.
zincrby<key><increment><value> For element score Plus increment
zrem <key><value> Delete the specified value of the element under the set
zcount <key><min><max> Count the number of elements in the score interval of the set
zrank<key><value>Returns the ranking of the value in the collection, starting from 0.

3. Data structure

zset is a very special data structure provided by redis. On the one hand, it is equivalent to the java data structure map < string, double >, which can assign a weight score to each element value. On the other hand, it is similar to TreeSet. The internal elements will be sorted according to the weight score to get the ranking of each element, You can also get the list of elements through the scope of score.

Two data structures are used at the bottom of zset

  1. hash is used to associate the element value with the weight score to ensure the uniqueness of the element value. The score value of the response can be found through the element value.
  2. Jump table. The purpose of jump table is to sort the element value and obtain the element list according to the range of score.

7, bitmaps

1. Introduction

Modern computers use binary as the basic unit of information, and one byte is equal to 8 bits. Rational use of operators can effectively improve memory utilization and development efficiency.

Redis provides Bitmaps, which can realize bit-to-bit operation:

  1. Bitmaps itself is not a data type. In fact, it is a string, but it can operate on the bits of the string.
  2. Bitmaps provides a separate set of commands, so the methods of using bitmaps and string in Redis are different. Bitmaps can be imagined as an array in bits. Each unit of the array intelligently stores 0 and 1. The array subscript is called offset in bitmaps.

2. Command

setbit<key><offset><value> set up Bitmaps The value of an offset in (0 or 1)
getbit<key><offset>obtain Bitamps The value of an offset in
bitcount <key>[start end] Statistics string from start Byte to end Number of bytes with a bit value of 1
bitop and(or/not/xor)<destkey> [key...] bitop It is a conforming operation, which can do multiple operations bitmaps of and(Intersection) or(Union) not(Non) xor(XOR) operation and save the results in destkey Yes.

8, Hyperlog

1. Introduction

In our work, we often encounter functional requirements related to statistics, such as Statistics website PV, which can be implemented by incr and incrby of Redis.

But how to solve the problems such as UV (independent visitor), the number of independent IP S, the number of search records and so on? This problem of finding the number of non repeating elements in a set is called the cardinality problem.

What is cardinality?

For example, if the dataset {1, 3, 5, 7, 5, 7, 8}, the cardinality set of this dataset is {1, 3, 5, 7, 8}, and the cardinality (non repeating element) is 5. Cardinality estimation is to quickly calculate the cardinality within the acceptable range of error.

There are many solutions to the cardinality problem:

  1. The data is stored in the Mysql table, and distinct count is used to calculate the number of non duplicates
  2. Use the hash, set, bitmaps and other data structures provided by Redis to process

The above scheme results are accurate, but with the continuous increase of data, the occupied space is becoming larger and larger, which is impractical for very large data sets.

Can a certain degree of accuracy be reduced to balance the storage space? Redis launched HyperLogLog, which is an algorithm for cardinality statistics. The advantage of HyperLogLog is that when the number or volume of input elements is very large, the space required to calculate the cardinality is always fixed and very small.

In Redis, each hyperlog key only needs 12kb of memory to calculate the cardinality of nearly 2 ^ 64 different elements. This is in sharp contrast to a collection where the more elements consume more memory when calculating the cardinality.

However, because the HyperLogLog command calculates the cardinality according to the input elements without storing the input elements themselves, HyperLogLog cannot return the input elements like a collection.

2. Command

pfadd<key><element>[element...] Add specified element to HyperLogLog in
pfcount<key>[key...] calculation HLL The approximate cardinality of can be calculated HLL,For example HLL Store daily UV,Calculate a week's UV It can be used for 7 days UV Consolidated calculation is enough.
pfmerge<destkey><sourcekey>[sourcekey...] One or more HLL The merged results are stored in another HLL For example, monthly active users can use daily active users to consolidate and calculate.

9, Geographic

1. Introduction

Redis3.2 added support for Geo types. GEO, Geographic, abbreviation of Geographic information. This type is the 2-dimensional coordinate of the element, which is the longitude and latitude on the map. Based on this type, redis provides longitude and latitude setting, query, range query, distance query, longitude and latitude Hash and other common operations.

2. Command

geoadd<key><longitude><latitude><member>[longitude latitude member...]Add geographic location (longitude, latitude, name)

Topics: Database Redis Cache