Home Database Redis Introduction to basic commands of 5 data types in redis

Introduction to basic commands of 5 data types in redis

Mar 11, 2020 am 09:12 AM
redis

Introduction to basic commands of 5 data types in redis

redis is a database of key-value pairs. There are 5 main data types:

String type (string), hash type (hash), list type ( list), set type (set), ordered set type (zset)

Recommended: redis tutorial

Several basic commands:

##keys *Get all keys of the current databaseexists key [key ...]Determine whether the key exists and return the number. If the key has the same key, it will also be a superposition numberdel key [key ...]Delete key, return the number of deleted itemstype keyGet the reduced value Data type (string, hash, list, set, zset)flushallClear all databasesconfig [get , set]redis configuration

-inf negative infinity

inf positive infinity

1: String type (string)

The string type is the most basic type of Redis, it can store any string in the form. The other four types are all different forms of the string type.

Function Description
Function Syntax
The most basic commands: GET, SET GET key, SET key value If there are spaces, double quotes are needed to distinguish the value.
Integer increment: INCR INCR key The default value is 0, So first execute the command to get 1, which is not an integer and prompts an error
Increase the specified integer: INCRBY INCRBY key increment
Decrease the integer: DECR DECR key The default value is 0, so first execute the command to get -1, which is not an integer and prompt an error
Decrease the specified integer: DECRBY DECRBY key increment
Increase the specified floating point number: INCRBYFLOAT INCRBYFLOAT key increment is similar to the INCR command, except that it can increment a double-precision floating point number
Append value to the end: APPEND APPEND key value The redis client does not output the appended string, but outputs the total length of the string
Get the string length: STRLEN STRLEN key If the key does not exist, return 0. Note that if there is Chinese, the length of a Chinese character is 3, and redis uses UTF-8 to encode Chinese
Get multiple key values: MGET MGET key [key ...] For example: MGET key1 key2
Settings Multiple key values: MSET MSET key value [key value ...] For example: MSET key1 1 key2 "hello redis"
Binary specified position value: GETBIT

GETBIT key offset For example: GETBIT key1 2, key1 is hello and returns 1. The returned value is only 0 or 1. When the key does not exist or exceeds the actual length, it is 0

Set the binary position value: SETBIT SETBIT key offset value, return the old value of the position
The binary number is 1: BITCOUNT BITCOUNT key [start end], start and end are the start and end bytes
Bit operation: BITOP BITOP operation destkey key [ key ...], operation supports AND, OR, XOR, NOT
Offset: BITPOS BITPOS key bit [start] [end]

Two: Hash type (hash)

Function Syntax
Set a single: HSET HSET key field value, returns 1 if it does not exist, returns 0 if it exists, there is no distinction between update and insertion
Set multiple: HMSET HMSET key field value [field value ...]
Read a single: HGET HGET key field, if it does not exist, return nil
Read multiple: HMGET HMGET key field [field ...]
Read all: HGETALL HGETALL key, return a list of fields and field values
Judge whether the field exists: HEXISTS HEXISTS key field, return 1 if it exists, if not Existence returns 0
Assignment when the field does not exist: HSETNX HSETNX key field value, different from the hset command, hsetnx sets the value when the key does not exist
Increase number: HINCRBY HINCRBY key field increment, return the increased number, if it is not an integer, an error will be prompted
Delete field: HDEL HDEL key field [field ...], returns the number of deleted fields
Get only the field name: HKEYS HKEYS key , return all field names of the key
Get only field values: HVALS HVALS key , return all field values ​​of the key
Number of fields: HLEN HLEN key, return the total number of fields

Three: List type (list)

Internally implemented using a doubly linked list, so the elements closer to both ends are obtained faster, but access through indexes will be slower

Function Syntax
Add the left element: LPUSH LPUSH key value [value .. .] , returns the total number of added list elements
Add the right element: RPUSH RPUSH key value [value ...] , returns the added The total number of list elements
Remove the first element on the left: LPOP LPOP key, return the value of the removed element
Remove the first element on the right: RPOP RPOP key, return the value of the removed element
Number of elements in the list: LLEN LLEN key, returns 0 when it does not exist. Redis directly reads the ready-made value, not the statistical number
Get the list fragment: LRANGE

LRANGE key start stop, if start is later than stop, an empty list is returned, 0 -1 returns the entire list when it is a positive number: start starts the index value, stop ends the index value (the index starts from 0) when it is a negative number: for example, lrange num -2 -1, -2 means the second from the right, -1 means the first from the right,

Delete the specified value: LREM

LREM key count value, returns the deleted number

count>0, deletes the first count elements with value from the left

count<0, deletes the previous ones from the right |count| elements whose value is value

count=0, delete all elements whose value is value

Index element value: LINDEXLINDEX key index, returns the element value of the index, -1 means setting the element value from the rightmost first position
: LSETLSET key index value
Keep list fragment: LTRIMLTRIM key start stop, start, top refer to lrange command
Transfer one list to another List: RPOLPPUSH

RPOPLPUSH source desctination, transfer from the source list to the desctination list. This command is divided into two steps. First, remove the source list RPOP right, and then remove the desctination list LPUSH

Four: Set type (set)

Set type values ​​are unique. Common operations are to add, delete, and determine whether a value exists in the set. The internal set is implemented using a hash table with empty values. of.

FunctionSyntax
Add element: SADD

SADD key member [member ...], adds one or more elements to a set. Because of the uniqueness of the set, adding the same value will be ignored. Returns the number of successfully added elements.

Delete elements: SREMSREM key member [member ...] Delete one or more elements in the collection and return the number of successfully deleted elements.
Get all elements: SMEMBERSSMEMBERS key, return all elements of the collection
Whether the value exists: SISMEMBER
SISMEMBER key member, if it exists, it returns 1, if it does not exist, it returns 0
Difference operation: SDIFF SDIFF key [key ...], For example: set A and set B, the difference set represents A-B, if there are elements in A that are not in B, the difference set is returned; multiple sets (A-B)-C
intersection operation: SINTER SINTER key [key ...], returns the intersection set, each set has elements
And operation: SUNION SUNION key [key...], returns the union set, the elements of all sets
The number of set elements: SCARDSCARD key, returns the number of set elements
Storage results after set operation

SDIFFSTROE destination key [key ...], difference operation and store in destination new setSINTERSTROE destination key [key .. .], intersect and store it in the new collection of destination SUNIONSTROE destination key [key ...], and perform the operation and store it in the new collection of destination

Randomly obtain elements: SRANDMEMGER

SRANDMEMBER key [count], there are different results depending on the count. When the count is greater than the total number of elements, all elements count>0 are returned. Count

Pop element: SPOP SPOP key [count], because the collection is unordered, So spop will randomly pop up an element

Five: Ordered set type zset (sorted set: ordered set)

Redis zset, like set, is also a collection of string type elements, and duplicate members are not allowed.

The difference is that each element is associated with a double type score.

Redis uses scores to sort the members of the set from small to large. The members of zset are unique, but the scores can be repeated.

##Add a collection element: ZADDZADD key [NX|XX] [CH] [INCR] score member [score member ...], there is no addition, there is update. Get the element score: ZSCOREZSCORE key member, return the score score of the element memberElements from small to large: ZRANGEElements from large to small: ZREVRANGEZREVRANGE key start [WITHSCORES], the difference from zrange is that zrevrange is sorted from large to smallSpecifies the score range Element: ZRANGEBYSCORESpecify the score range elements: ZREVRANGESCOREIncrease the score :ZINCRBYZINCRBY key increment member, note that the score is increased and the increased score is returned; if the member does not exist, a member of 0 is added.
Function Syntax
ZRANGE key start top [WITHSCORES], refer to LRANGE, plus withscores to return the band elements, that is, elements, scores. When the scores are the same, sort by elements

ZRANGEBYSCORE key min max [WITHSCORE] [LIMIT offest count] returns the elements between min and max from small to large, ( symbol means not included, for example: 80-100, (80 100, withscore returns the mixed fraction limit offest count, offset offset count to the left, and obtain the first count elements

ZREVRANGEBYSCORE key max min [WITHSCORE] [LIMIT offest count] is similar to zrangebyscore, except that the command is sorted from large to small.

Related recommendations:

mysql video tutorial:

https://www.php.cn/course/list/51.html

The above is the detailed content of Introduction to basic commands of 5 data types in redis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

How to read the source code of redis How to read the source code of redis Apr 10, 2025 pm 08:27 PM

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to view all keys in redis How to view all keys in redis Apr 10, 2025 pm 07:15 PM

To view all keys in Redis, there are three ways: use the KEYS command to return all keys that match the specified pattern; use the SCAN command to iterate over the keys and return a set of keys; use the INFO command to get the total number of keys.

How to implement the underlying redis How to implement the underlying redis Apr 10, 2025 pm 07:21 PM

Redis uses hash tables to store data and supports data structures such as strings, lists, hash tables, collections and ordered collections. Redis persists data through snapshots (RDB) and append write-only (AOF) mechanisms. Redis uses master-slave replication to improve data availability. Redis uses a single-threaded event loop to handle connections and commands to ensure data atomicity and consistency. Redis sets the expiration time for the key and uses the lazy delete mechanism to delete the expiration key.

See all articles