[redis basics] ten data types of redis

foreword

Accept the suggestion of Brother Xu Zhu, and a series of articles on redis will be published in the future

This article explains the operations with high utilization rate of Redis7 data types. For all operations of Redis7 data types, please refer to: Commands | Redis

Previous article: Getting to know redis [installation, use and uninstallation of redis]_Work hard and work hard mlx's blog-CSDN blog

If you have any questions, you can private message me anytime~


Table of contents

redis key (key)

redis string (String)

Redis list (List)

Redis hash (Hash)

Redis collection (Set)

Redis ordered collection Zset (sorted set)

Redis bitmap (bitmap)

Redis cardinality statistics (HyperLogLog)

Redis Geospatial (GEO)

Redis style (Stream)

Redis bit field (bitfield)


redis key (key)

A list of commonly used redis commands:

The detailed introduction of common commands for keys is as follows:
 keys * #View all keys in the current k= library

exists key #Judge whether a certain key exists (in redis instructions, 0 means that 0 instructions are queried (the instruction that meets the conditions cannot be found), and 1 means that the query is successful)


type key #View the data type of the current key


del key #Delete the specified key


unlink key #Non-blocking delete, just delete keys from the keyspace metadata, no real deletion will be performed in subsequent asynchronous operations, at present we only need to have a certain impression of this command, and we will further introduce it later


ttl key #Check how many seconds the key we queried has expired -1 means it will never expire -2 means it has expired


expire key seconds #Set the expiration time for the key


move key [0-15] #Move the key of the current database to the specified database, redis has 16 databases by default
select [0-15] #Switch database [0-15], the default is 0, the subscript exceeds 0 A range of -15 will report an error


dbsize # View the number of keys in the current database


flushdb #Empty the current library, use with caution


flushall #Empty 16 databases with caution

Considering that this operation is very dangerous, I will not demonstrate it here. 

help @ type to view a type of help documentation

Notes: The instructions we operate are not case-sensitive, but the keys we manually set are case-sensitive

redis string (String)

String is the most basic data type in redis. A key corresponds to a value. String data is binary safe, which means it can store any data, including jpg files and

Common instructions in String:

 The detailed introduction to the String type command is as follows:
set key value

 

 get key # Get the value corresponding to the specified key

mset [key1] [value1] [key2] [value2] [key3] [value3] #Set one or more key-value pairs at the same time


mget [key1] [key2] [key3] #Get the values ​​of multiple keys at the same time


msetnx [key1] [value1] [key2] [value2] #Set one or more key-value pairs at the same time. It must be ensured that none of the keys exists to succeed

 

 

Get the specified interval
getrange [key] 0 -1 # Get all the values ​​of this key
getrange [key] 0 3 # Get the value of this key between index 0 and index 2
getrange [key] 1 xxx #Set the range of the specified interval the value within


 
Value increase or decrease
incr [key] # increment number +1
incr [key] [increment] # increase the specified integer +increment 
decr [key] # decrease the number -1
decr [key] [increment] # decrease the specified integer -increment 


Get the length of the string and add the content
strlen [key] # Get the length of the value corresponding to the key


append [key] [vale] #add string content
 

distributed lock
setex [key] [expiration time] [value] # set the key with expiration time, dynamic setting


setnx [key] [value] # Set the value of the key only when the key does not exist.


set [key] [value] get # Set the value of the given key to value and return the old value of the key


getset [key] [value] # Set the value of the given key to value and return the old value of the key

 

Application Scenarios:
1. Douyin likes

2. Like the article

Redis list (List)

Introduction to list

The structure of a double-ended linked list, the capacity is 2 to the 32nd power minus 1 element, about more than 4 billion, the main functions include push/pop, etc., generally used in stacks, queues, message queues and other scenarios. The list corresponds to a single key with multiple values

Both left and right can be inserted and added;

If the key does not exist, create a new linked list;

If the key already exists, add the content;

If all values ​​are removed, the corresponding keys disappear.

  • The bottom layer of its list is actually a doubly linked list, which has high performance on both ends of the operation, and the performance of nodes in the middle through index subscript operations will be poor.
  • of
  • li; common operations of list

A common introduction to list operations 

lpush [key] [value] ... // Put elements into the head (left) of the list


rpush [key] [value] ... // put elements into the list (right)


lrange [key] 0 -1 // Traversing the list from the left can only traverse from the left


lpop [key] // The leftmost stack is the first one traversed by lrange


rpop [key] // The rightmost stack is the last one traversed by lrange


lindex [key] [index] // Get the value by index value

  
llen [key] // Get the number of elements


lrem [key] [num] [value] // delete num value value from left to right


lrem [key] 0 [value] // Delete all values ​​​​that are valued from left to right


ltrim [key] [start] [end] // intercept the value in the specified range and then assign it to [key], that is, delete the value outside this range


rpoplpush [key1] [key2] [value] //Remove the last element of the list, and add this element to the first of another list and return


lset [key] [index] [value] //Change the index value of key to value


linsert [key] brfore/after [value1] [value2] // Add a specific value before and after an existing value in the list

Application Scenario
 WeChat official account pushes me to subscribe to the author's articles

When the author I subscribed publishes two new articles, the corresponding ids are 11 and 22 respectively

lpush likearticle:ljl 11 22

I want to view the first ten subscribed article information:

lrange likearticle:ljl 0 9

Redis hash (Hash)

brief introduction

When we talk about hashing, our first reaction must be hashmap in java. The hash in redis is similar to the hash in java, the kv mode remains unchanged, but v is a key-value pair => Map<String,Map<Object,Object>

List of common commands

Commonly used commands in detail

hset/hget/hmset/hmget/hgetall/hdel //hset/get corresponds to get value and get value hmset/hmget is to get and get multiple values ​​hgetall is to get all values ​​hdel is to delete a value 


hlen // Get all the quantities in a key


hexists [key] [k1] // see if there is a key k1 in the key

 
hkeys [key] // Get all the keys in the key


hvals [key] // Get all the values ​​in the key


hincrby [key] k1 [num] // The value of k1 in the key increases by num integer


hincrbyfloat [key] k1 [num] // The value of k1 in the key increases by num decimals

 


hsetnx [key] k1 [value] // There is no assignment, there is invalid

Typical application scenarios of hash:

Early adoption of the shopping cart

Redis collection (Set)

brief introduction

 When we think of set, the first thing we think of is hashset in java, and set collection in redis. The values ​​in set must not be repeated. The way he stores data is single value and multiple values.

common command

Detailed introduction of commonly used commands 

SADD key member ... // add element


SMEMBERS key // traverse all elements in the collection


SISMEMBER key member // determine whether an element is in the set

SREM key member ... // delete element


SCARD key // Get the collection length


SRANDMEMBER key m // Randomly select m from the set collection If it exceeds the maximum number, all will be taken out  

If the written value is a negative number, such as -3, it means that 3 need to be taken out, but there may be duplicate values ​​that will not be deleted


SPOP key m // Randomly pop an element from the collection, remove one and delete one


SMOVE key1 key2 an existing value in key1 // Assign an existing value of key1 to key2

 

set operation

SDIFF keyA keyB // A - B is a collection of elements that belong to A but not to B


SUNION keyA keyB // AUB is the merged collection of elements belonging to A or B


SINTER keyA keyB // A ∩ B belongs to both A and B


SINTERCARD numkeys keyA keyB [LIMIT limit] // It also seeks intersection, does not return the result set, only returns the cardinality of the result limit is used to limit the cardinality of the intersection, if the result exceeds the limited number of limit during the operation, it returns directly

Typical Application Scenarios

1. vx lottery

2. Vx circle of friends set like friends

3. Tweet people you may know in QQ

Redis ordered collection Zset (sorted set)

Introduction to zset

Zset adds a field such as score on the basis of set. It is precisely because of this field that zset can sort elements on the basis of satisfying the characteristics of set

Commonly used instructions about zset

Detailed introduction to zset common commands

ZADD key score member [ score member ] // add element


ZRANGE key start stop [WITHSCORES] // Return the order of element scores from small to large Return all elements with indexes from start to stop


ZREVRANGE key 0 - 1 [WITHSCORES] // reverse order


ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count] // Get the elements of the specified score range (min, max) excluding limit is the return limit, how many to return 


ZSCORE key member // Get the score of the element


ZCARD key // Get the number of elements in the collection


ZREM key The value corresponding to a certain score // delete the element


ZINCRBY key increment member // increase the score of an element


ZCOUNT key min max // Get the number of elements within the specified score range


ZMPOP numkeys key [key …] <MIN | MAX> [COUNT count] // Pop one or more keys from the first non-empty sorted set in the key name list, which are member-score pairs


ZRANK key values ​​value // get subscript value


ZREVRANK key values ​​// Obtain subscript values ​​in reverse order   

 

Application scenario:
Sort products according to their sales volume

  

Redis bitmap (bitmap)

The concept of bitmap

Description: A statistical binary state data type implemented with the String type as the underlying data structure

A bitmap is essentially an array , which is a bitwise operation based on the String data type. The array consists of bits, each of which corresponds to an offset (we call it an index). The maximum number of bits supported by Bitmap is 2^32 bits, which can greatly save storage space. Using 512M memory, it can store up to 4.29 billion bytes of information (2^32 = 4294967296)

List of common commands

Commonly used commands in detail

SETBIT key offset value // Set the value of the first offset to value, value can only be 0 or 1, offset starts from 0


GETBIT key offset // Get the value of the offset bit


STRLEN key // Find out how many bytes are more than 8 bits, and then expand the capacity according to 8 bits per byte


BITCOUNT key // Find out how many 1s are contained in the key


BITOP and destKey key1 key2 // Do a logical union of one or more keys and save the result to destkey 


The following operations are the same, and will not be repeated here~ 

BITOP or destKey key1 key2 // Do logical OR for one or more keys, and save the result to destkey 

BITOP XOR destKey key1 key2 // Do logical XOR for one or more keys, and save the result to destkey 
BITOP NOT destKey key1 key2 // Do logic NOT for one or more keys, and save the result to destkey

 Typical application scenario:
the application scenario of sign-in is very suitable for bitmap

365 days a year, how many days are signed in every day?

by year

Redis cardinality statistics (HyperLogLog)

  basic introduction

The cardinality estimation algorithm of the deduplication statistics function is HyperLogLog, and the cardinality is the real number of a data set after deduplication. Cardinality statistics are used to count the number of unique elements in a collection, that is, the calculation of the remaining elements after deduplication of the collection only needs to spend memory, and can record the cardinality of 2 to the 64th power = 18446744073709551616 different elements. However, because HyperLogLog only calculates the cardinality based on the input elements and does not store the input elements themselves, HyperLogLog cannot return the individual elements of the input like a set.

common command

 pfadd hyl1 1 1 1 1 2 3 6
pfadd hyl2 2 4 4 4 6 7 8 9
pfcount hyl2 //Calculate the number of elements in hyl2 after deduplication
pfmerge distResult hyl2 hyl1 //Merge the elements in hyl2 and hyl1 and deduplicate
pfcount disResult / /Calculate the number of elements after deduplication in hyl2

Application Scenario

Tmall website homepage billion level UV redis statistical scheme

Redis Geospatial (GEO)

brief introduction

The geographic location on the earth is represented by two-dimensional latitude and longitude, longitude range (-180, 180], latitude range (-90, 90], as long as we determine the latitude and longitude of a point, we can obtain its position on the earth.

For example, Didi Taxi, the most intuitive operation is to record and update the location of each car in real time.
Then when we want to find a car, we search the database for the latitude and longitude of the vehicle within r kilometers from us (coordinates x0, y0) and
copy it directly on the map. :
pick coordinate system

common command

 Commonly used designation details 

GEOADD city 116.403963 39.915119 "Tiananmen" 116.403414 39.924091 "Forbidden City" //GEOADD adds latitude and longitude coordinates


ZRANGE city 0 -1 // View (Chinese garbled characters will appear)


redis -cli -a 111111 -p 6379 -- raw // Solve Chinese garbled characters


GEOPOS city Tiananmen Forbidden City // GEOPOS returns the latitude and longitude
// GEOHASH returns the geohash representation of the coordinates (base32 encoding)


GEOHASH city Tiananmen Forbidden City


//GEODIST returns the distance between two locations (m km )
GEODIST city Tiananmen Great Wall km
//GEORADIUS takes the given latitude and longitude as the center, returns the location elements contained in the key, and the distance from the center does not exceed the given maximum distance All positional elements.
GEORADIUS city 116.418017 39.9144444 10 km withdist withcoord count 10 desc
//GEORADIUSBYMEMBER Find the elements within the specified range, the center point is determined by the given position element
GEORADIUsbymember city Tiananmen 10 km withdist withcoord count 10 withhash

Application Scenario

  • Restaurants and hotels near Meituan
  • Stores near Gaode map

Redis style (Stream)

I will organize the content of the flow into a separate blog~

redis [stream]: a detailed introduction to redis stream data types

Redis bit field (bitfield)

basic introduction

Purpose: In a word, a Redis string is regarded as an array composed of binary bits, and can address and modify variable-length bit-width and any specified integer bit field without byte alignment

The two functions are as follows:

  • bit field modification
  • overflow control

 basic grammar

Guess you like

Origin blog.csdn.net/m0_65431718/article/details/130768211