In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this "python operation redis case analysis" article, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "python operation redis case analysis" article.
Redis is a Key-Value database, Value supports string (string), list (list), set (collection), zset (ordered collection), hash (hash type) and other types.
Pip install redis1, mode 1 regular connection redisimport redisr = redis (host='localhost', port=6379, db=0) r.set ('foo',' bar') print (r.get ('foo'))
The output is as follows:
B'bar'2, mode 2 using connection pooling
By default, each Redis instance maintains its own connection pool. You can directly establish a connection pool, and then as a parameter Redis, so that multiple Redis instances can share a connection pool.
Import redispool = redis.ConnectionPool (host='localhost', port=6379, db=0) r = redis.Redis (connection_pool=pool) r.set ('foo',' bar') print (r.get ('foo')) r.close () # remember to close the connection pool
The output is as follows:
Baggage bar'
The result taken out by redis is byte by default. We can change decode_responses=True to string.
Import redisr = redis (host='localhost', port=6379, db=0, decode_responses=True) r.set ('foo',' bar') print (r.get ('foo'))
The output is as follows:
Different data types of bar'1 and redis are used in scenario 1) String
Counter application
2) List
The operation of taking the latest N pieces of data
Message queue
Delete and filter
Real-time analysis of what is happening for data statistics and prevention of spam (combined with Set)
3) Set
Uniqe operation to obtain all data weight values for a certain period of time
Real-time system, anti-garbage system
Common friend, second-degree friend
Using uniqueness, you can count all the independent IP that visit the website
When recommending a friend, you can find the intersection according to tag. If it is greater than a certain threshold, you can recommend it.
4) Hashes
Store, read, and modify user attributes
5) Sorted Set
Ranking application, take TOP N operation
Applications that require precise expiration time (timestamp as Score)
An element with weight, such as a game's ranking of user scores
Processing of overdue items, sorted by time
2. String six different data types example 1) string type
The String in redis is stored in memory according to a name corresponding to a value. As shown in the figure:
1.1 set add string
Set (name, value, ex=None, px=None, nx=False, xx=False)
Set the value in Redis, default, create if it doesn't exist, and modify it if it exists.
Parameters:
Ex-Expiration time (seconds)
Px-expiration time (milliseconds)
Nx-if set to True, the current set operation is performed only if name does not exist (New)
# premise that there is no key='foo'import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.set ('foo',' bar', nx=True) print (r.get ('foo')) in redis database db
Output:
'bar'
Xx-if set to True, the current set operation is performed (modified) only if name exists
# premise that there is no key='foo'import redisr = redis.Redis (host='199.28.10.122', port=6389, db=3, password='test1234', decode_responses=True) r.set ('foo',' bar', xx=True) print (r.get ('foo')) in redis database db=3
Output:
None
1.2 when the setnx KEY value does not exist, add
Setnx (name, value)
Set value, only if name does not exist, perform the setting operation (add)
# premise redis database db does not have key='too'import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.setnx ('too',' tar') print (r.get ('too')) r.setnx (' too', 'looktar') print (r.get (' too'))
Output:
'tar''tar' # because the corresponding data has been added to the first setnx, the setnx addition (' too', 'looktar') is not performed
1.3 setex sets expiration time seconds
Setex (name, time, value)
Set valu
Parameters:
Time-expiration time (digital seconds or timedelta object)
Import redisimport timer = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.setex ('foo', 5,' bar') print (r.get ('foo')) print (' wait 5 seconds') time.sleep (5) print (r.get ('foo'))
Running result:
Bar waits for 5 seconds None # 5 seconds after data expires
1.4 psetex sets expiration time in milliseconds
Psetex (name, time_ms, value)
Set valu
Parameters:
Time_ms-expiration time (numeric milliseconds or timedelta object)
Import redisimport timer = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.psetex ('foo', 5000,' bar') print (r.get ('foo')) print (' wait 5 seconds') time.sleep (5) print (r.get ('foo'))
Running result:
Bar waits for 5 seconds None # 5 seconds after data expires
1.5 mset batch setup
Mset (* args, * * kwargs)
Batch setting value
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.mset ({'K1:'v1,'K2: 'v2}) print (r.mget ("K1", "K2")) # take out the value print (r.mget ("K1")) corresponding to multiple keys at a time
Running result:
['v1','v2'] ['v1']
1.6 mget batch acquisition
Mget (keys, * args)
Batch setting value
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.mset ({'K1:'v1,'K2:'v2'}) print (r.mget ("K1", "K2")) # take out the value # or print (r.mget ([K1 "," K2 "])) # take out the value print (r.mget (" K1 ")) corresponding to multiple keys at one time
Running result:
['v1','v2'] ['v1','v2'] ['v1']
1.7 getset sets the new value and gets the original value
Getset (name, value)
Set and get the original value
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.set ('food',' beef') print (r.get ('food')) print (r.getset ("food", "barbecue")) # the new value set is beefprint (r.get (' food')) before barbecue setting
Running result:
Beef # the original value beef # return is the original value barbecue # to retrieve the value of "food"
1.8 getrange get subsequence (byte-based, non-character)
Getrange (key, start, end)
Get subsequence (based on bytes, not characters)
Parameters:
Name of name-Redis
Start-start position (in bytes)
End-end position (in bytes)
For example, "long live the motherland", 0-3 means "ancestor" (Chinese characters in Python occupy three bytes under utf-8 coding and two bytes under gbk coding)
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.set ("cn_name", "long live the motherland") # Chinese character print (r.getrange ("cn_name", 0,2)) # Byte ancestor slicing operation (one Chinese character with 3 bytes, 1 letter and one byte per byte) print (r.getrange ("cn_name", 0) -1)) # take all the bytes of the motherland slicing operation r.set ("en_name", "zuguowansui") # letter print (r.getrange ("en_name", 0,2)) # take the index number of the first three bytes of the byte zug slice operation (one Chinese character 3 bytes, 1 letter one byte 8bit) print (r.getrange ("en_name", 0) -1)) # fetch all bytes of uguowansui slicing operation
Running result:
Long live the motherland, zugzuguowansui.
1.9 setrange modifies string contents
Setrange (name, offset, value)
Modify the contents of the string, replacing backwards from the specified string index (if the new value is too long, add backwards)
Parameters:
Offset-Index of the string, bytes (three bytes of a Chinese character)
Value-value to set
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.setrange ("en_name", 1, "ccc") print (r.get ("en_name")) # zcccowansui original value is zuguowansui replaced with ccc starting with the index number 1
Running result:
Zcccowansui
1.10 setbit operates on bits in the binary representation of name corresponding values
Setbit (name, offset, value)
Operate on the bits in the binary representation of the name corresponding value
Parameters:
Note: if there is a correspondence in Redis: N1 = "foo"
Then the binary representation of the string foo is: 01100110 01101111 01101111
So, if you execute setbit ('N1, 7, 1), bit 7 will be set to 1
Then the final binary becomes 01100111 01101111 01101111, that is, "goo".
Name of name-redis
Index of offset-bit (convert the value to binary before indexing)
Value-value can only be 1 or 0
1.11 getbit gets the value of a bit (0 or 1) in the binary representation of the value corresponding to name
Getbit (name, offset)
Gets the value of a bit in the binary representation of the value corresponding to name (0 or 1)
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.getbit ("foo1", 0)) # 0 foo1 corresponding to 4 bytes of binary 32 bits 0 or 1
1.12 bitcount gets the number of 1s in the binary representation of the values corresponding to name
Bitcount (key, start=None, end=None)
Gets the number of 1s in the binary representation of the values corresponding to name
Parameters:
Name of key-Redis
Start-Byte start position
End-Byte end position
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.set ('foo','baksks') print (r.get ("foo")) # goo1 01100111print (r.bitcount ("foo", 0meme 1)) # 11
Running result:
Baksks6
1.13 bittop acquires multiple values, performs bit operations on the values, and saves the final results to the values corresponding to the new name
Bitop (operation, dest, * keys)
Get multiple values, do bit operation on the values, and save the final result to the corresponding value of the new name
Parameters:
Operation-AND (and), OR (or), NOT (non), XOR (XOR)
Dest-name of the new Redis
* keys-the name of the Redis to be found
Such as:
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.set ("N1", 'goo1') r.set ("N2",' baaanew') r.set ("n3", 'appaanew') r.bitop ("AND",' new_name','N1,'N2, 'n3') print (r.get (' new_name'))
Running result:
```!
1.14 strlen returns the byte length of the name corresponding value (3 bytes for a Chinese character)
Strlen (name)
Returns the byte length of the name corresponding value (3 bytes of a Chinese character)
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.set ('foo1s',' flash') print (r.strlen ("foo1s"))
Running result:
five
1.15 incr increments the corresponding value of name. If name does not exist, a name=amount is created. Otherwise, the value is incremented.
Incr (self, name, amount=1)
The value corresponding to the self-incrementing name. If the name does not exist, the name=amount will be created. Otherwise, the value will be incremented.
Parameters:
Name of name-Redis
Amount-self-increment (must be an integer)
Note: same as incrby
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.set ('foo1',' flash') r.set ('foo2',' fla2sh') r.set ("foo", 123) print (r.mget ("foo", "foo1", "foo2", "K1", "K2") r.incr ("foo", amount=1) print (r.mget ("foo", "foo1", "foo2", "K1") "K2")) r.incr ("foono", amount=1) # there is no 'foono'print (r.mget ("foono", "foo1", "foo2", "K1", "K2"))
Running result:
['123name,' flash', 'fla2sh',' v1century, 'v2'] [' 1244th, 'flash',' fla2sh', 'v1century,' v2'] ['1century,' flash', 'fla2sh',' v1century, 'v2'] # create a name=amount when the name=amount does not exist
Application scenarios:
Suppose we need to record the number of clicks on a series of pages. For example, each post in the forum records the number of clicks, and the number of clicks is much more than the number of replies. If you use a relational database to store clicks, there may be a lot of row-level lock contention. So it's best to use redis's INCR command for an increase in the number of clicks.
When the redis server starts, the initial number of clicks can be read from the relational database (12306 this page has been accessed 34634 times)
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.set ("visit:12306:totals", 34634) print (r.get ("visit:12306:totals")) r.incr ("visit:12306:totals") print (r.get ("visit:12306:totals"))
Running result:
3463434635
1.16 incrbyfloat increments the corresponding value of name. If name does not exist, create name=amount. Otherwise, it increments itself.
Incrbyfloat (self, name, amount=1.0)
The value corresponding to the self-incrementing name. If the name does not exist, the name=amount will be created. Otherwise, the value will be incremented.
Parameters:
Name of name-Redis
Amount-self-increment (floating point)
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.set ("foo1", "123.0") r.set ("foo2", "221.0") print (r.mget ("foo1", "foo2") r.incrbyfloat ("foo1", amount=2.0) r.incrbyfloat ("foo2", amount=3.0) print (r.mget ("foo1", "foo2"))
Running result:
['123.0,' 221.0] ['125,' 224']
1.17 decr subtracts the value corresponding to name. If name does not exist, name=amount is created, otherwise, it is reduced by itself.
Decr (self, name, amount=1)
The value corresponding to the self-subtractive name. If the name does not exist, the name=amount is created, otherwise, it is self-subtracted.
Parameters:
Name of name-Redis
Amount-self-decrement (integer)
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.set ("foo1", "123") r.set (" foo4 "," 221") r.decr ("foo4", amount=3) # decreasing 3r.decr ("foo1", amount=1) # decreasing 1print (r.mget ("foo1", "foo4"))
Running result:
['122', '218']
1.18 appen appends the content after the corresponding value of name
Append (key, value)
Append the content after the corresponding value of redis name
Parameters:
Name of key-redis
Value-string to append
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.set ("foo1", "123") r.append (" foo1 "," ") # append the string print (r.mget (" foo1 ")) to the value junxi corresponding to name
Running result:
['123'] 2) hash
2.1 hset added individually-modified (single take out)-added if not, modified if necessary
Hset (name, key, value)
Set a key-value pair in the hash corresponding to name (if it does not exist, create it; otherwise, modify it)
Parameters:
Name of name-redis
Key in hash corresponding to key-name
Value in hash corresponding to value-name
Note: hsetnx (name, key, value) is created when the current key does not exist in the hash corresponding to the name (equivalent to adding
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.hset ("hash1", "K1", "v1") r.hset ("hash1", "K2", "v2") print (r.hkeys ("hash1")) # take all keyprint in hash (r.hget ("hash1", "K1")) # single key corresponding to hash print (r.hmget ("hash1", "K1") ("K2")) # more than one key corresponding to hash r.hsetnx ("hash1", "K2", "v3") # can only create a new print (r.hget ("hash1", "K2"))
Running result:
['K1', 'K2'] v1 [' v1, 'v2'] v2 # here, because it exists, the original value has not been modified, has not been added
2.2 hmset sets key-value pairs in batch in the hash corresponding to name
Hmset (name, mapping)
Set key-value pairs in batch in the hash corresponding to name
Parameters:
Name of name-redis
Mapping-Dictionary, such as: {'K1BZ],' K2dictionary: 'v2'}
Such as:
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.hmset ("hash2", {"K2": "v2", "K3": "v3"}) print (r.hget ("hash2", 'K2'))
Running result:
V2
2.3 hmget obtains the values of multiple key in the hash corresponding to name
Hmget (name, keys, * args)
Get the values of multiple key in the hash corresponding to name
Parameters:
Name corresponding to name-reids
Keys-to get the key collection, for example: ['K1','K2','K3']
* args-the key to be obtained, such as: K1, K2, K3
Such as:
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.hmset ("hash2", {"K2": "v2", "K3": "v3"}) print (r.hget ("hash2", "K2")) # the valueprint corresponding to the key-k2 that takes out "hash2" (r.hmget ("hash2", "K2") ("K3")) # batch take out the value corresponding to key-k2 K3 of "hash2"-mode 1print (r.hmget ("hash2", ["K2", "K3")) # batch take out the value corresponding to key-k2 K3 of "hash2"-mode 2
Running result:
V2 ['v2','v3'] ['v2','v3']
2.4 hgetall takes out all key-value pairs
Hgetall (name)
Get all the key values of the corresponding hash of name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.hmset ("hash2", {"K2": "v2", "K3": "v3"}) print (r.hgetall ("hash2"))
Running result:
{'K2':'v2','K3':'v3'}
2.5 hlen gets the format hash length of all key-value pairs
Hlen (name)
Get the number of key-value pairs in the hash corresponding to name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.hmset ("hash2", {"K2": "v2", "K3": "v3"}) print (r.hlen ("hash2"))
Running result:
two
2.6 hkeys gets all keys (similar dictionary takes all keys)
Hkeys (name)
Get the values of all key in the hash corresponding to name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.hmset ("hash2", {"K2": "v2", "K3": "v3"}) print (r.hkeys ("hash2"))
Running result:
['K2','K3']
2.7 hvals get all value (similar to dictionary take all value)
Hvals (name)
Get the values of all key in the hash corresponding to name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.hmset ("hash2", {"K2": "v2", "K3": "v3"}) print (r.hvals ("hash2"))
Running result:
['v2','v3']
2.8 hvals determines whether a member exists (similar to in of a dictionary)
Hexists (name, key)
Check whether the hash corresponding to name has the currently passed key
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.hmset ("hash2", {"K2": "v2", "K3": "v3"}) print (r.hexists ("hash2", "K4")) # False does not exist print (r.hexists ("hash2", "K2")) # True exists
Running result:
FalseTrue
2.9 hdel delete key-value pair
Hdel (name,*keys)
Delete the key-value pair of the specified key in the hash corresponding to name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.hgetall ("hash1")) r.hset ("hash1", "K2", "v222") # modify the existing key k2r.hset ("hash1", "K11", "v1") # add a key pair k11r.hdel ("hash1", "K1") # Delete a key pair print (r.hgetall ("hash1"))
Running result:
{'K2Qing:' v222, 'K11:' v1,'K3: 'v22332, K1: V1} {' K2: 'v222, K11: V1, K3: v22332} # K1 has been deleted
2.10 hincrby self-increment and minus integers (increase the value-- integers corresponding to key by 1 or 2, or other integer negative integers are self-subtractive)
Hincrby (name, key, amount=1)
The value of the specified key in the hash corresponding to the self-incrementing name. If it does not exist, a key=amount is created.
Parameters:
Name in name-redis
Key corresponding to key-hash
Amount-self-increment (integer)
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.hset ("hash1", "K3", 123) r.hincrby ("hash1", "K3", amount=-1) print (r.hgetall ("hash1")) r.hincrby ("hash1", "K4", amount=1) # if it does not exist, value defaults to 1print (r.hgetall ("hash1"))
Running result:
{'K2Qing:' v222, 'K11:' v1,'K3: '122} {' K2: 'v222,' K11:'v1,'K3: '122, K4:' 1'}
2.11 hscan value view-multipart read
Hscan (name, cursor=0, match=None, count=None)
Incremental iterative acquisition is very useful for large data. Hscan can obtain data in pieces, not all the data at once, so that the memory is burst.
Parameters:
Name of name-redis
Cursor-cursors (get data based on cursor fetching in batches)
Match-matches the specified key, and the default None represents all key
Count-the minimum number of shards is obtained at a time. The default None indicates the default number of shards using Redis.
Such as:
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.hgetall ("hash1")) print (r.hscan ("hash1"))
Running result:
{'K2Qing:' v222, 'K11:' v1,'K3: '122, K4:' 1'} (0, {'K2: 'v222, K11: V1, K3:' 122, K4:'1'})
2.12 hscan_iter uses yield to encapsulate hscan to create a generator to obtain data from redis in batches
Hscan_iter (name, match=None, count=None))
Using yield to encapsulate hscan to create a generator to obtain data from redis in batches.
Parameters:
Match-matches the specified key, and the default None represents all key
Count-the minimum number of shards is obtained at a time. The default None indicates the default number of shards using Redis.
Such as:
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.hgetall ("hash1")) for item in r.hscan_iter ('hash1'): print (item) print (r.hscan_iter ("hash1")) # Generator memory address
Running result:
{'K2Qing:' v222, 'K11):' v1,'K3: '122,' K4):'1'} ('K2, 'v222) (' K11, v1) ('K3, '122) (' K4,) 3) list
3.1 lpush increase (similar to list's append, except here is a new addition from the left)-create a new one if you don't
Lpush (name,values)
Add elements to the list corresponding to name, and each new element is added to the leftmost side of the list
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.lpush ("list1", 11,22,33) print (r.lrange ('list1', 0,-1))
Running result:
['33','22','11']
3.2 rpush increase (similar to list's append, except here is a new addition from the right)-if not, create a new one.
Rpush (name,values)
Add elements to the list corresponding to name, and each new element is added to the rightmost side of the list
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.rpush ("list2", 11,22,33) print (r.lrange ('list2', 0,-1))
Running result:
['11,'22,'33]
3.3 llen query list length
Llen (name)
Add elements to the list corresponding to name, and each new element is added to the rightmost side of the list
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.rpush ("list2", 11,22,33) print (r.llen ("list2")) # list length print (r.lrange ('list2', 0,-1))
Running result:
['11','22','33','11','22','33']
3.4 lpushx adds an element to the left of the list of existing name, which cannot be created without it
Lpushx (name,value)
Add an element to the list corresponding to name. Only if name already exists, the value is added to the leftmost part of the list.
More:
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.lpushx ("list10", 10) # print (r.llen ("list10")) # 0print (r.lrange ("list10", 0,-1)) # [] r.lpushx ("list2", 77) # here "list2" already exists, add an element to the far left of the list Only one print (r.llen ("list2")) # list length print (r.lrange ("list2", 0,-1)) # can be added at a time. The range is index number 0 to-1 (last element).
Running result:
0 [] 7 ['77,'11,'22,'33,'11,'22,'33]
3.5 rpushx adds an element to the right of the existing name list, which cannot be created without it
Rpushx (name,value)
Add an element to the list corresponding to name. Only if name already exists, the value is added to the rightmost part of the list.
More:
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.rpushx ("list2", 99) # here "foo_list1" already exists, add an element to the far right of the list, add only one print (r.llen ("list2")) # list length print (r.lrange ("list2", 0,-1)) # slice fetch values, ranging from index 0 to-1 (last element)
Running result:
8 ['77,'11,'22,'33,'11,'22,'33,'99]
3.6 linsert added (insert element at fixed index number position)
Linsert (name, where, refvalue, value)
Insert a new value before or after a value in the list corresponding to name
Parameters:
Name of name-redis
Where-BEFORE or AFTER
Refvalue-benchmarking value, that is, inserting data before and after it
Value-data to insert
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.linsert ("list2", "before", "11", "00") # insert element "00" print (r.lrange ("list2", 0,-1)) # slice out value before the first element "11" in the list, in the range of index number 0-last element
Running result:
['77,'00,'11,'22,'33,'11,'22,'33,'99]
3.7 lset modification (specify index number for modification)
R.lset (name, index, value)
Reassign an index position in the list corresponding to name
Parameters:
Name of name-redis
Index location of index-list
Value-value to set
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.lset ("list2", 0,-11) # modify the element whose index number is 0 to-11print (r.lrange ("list2", 0,-1))
Running result:
['- 11,'00,'11,'22,'33,'11,'22,'33,'99]
3.8 lset modification (specify the index number to modify)
R.lset (name, index, value)
Reassign an index position in the list corresponding to name
Parameters:
Name of name-redis
Index location of index-list
Value-value to set
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.lset ("list2", 0,-11) # modify the element whose index number is 0 to-11print (r.lrange ("list2", 0,-1))
Run result (found to be unsuccessful, no reason found):
['- 11,'11,'- 11,'00,'11,'22,'33,'11,'22,'33,'99]
3.9 lrem deletion (specify a value for deletion)
R.lrem (name, value, num)
Delete the specified value in the list corresponding to name
Parameters:
Name of name-redis
Value-value to delete
Num-num=0 to delete all specified values in the list
Num=2-from front to back, delete 2, num=1, from front to back, delete the first one on the left
Num=-2-delete 2 from back to front
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.lrem ("list2", "11", 1) # delete the "11" that first appears on the left side of the list print (r.lrange ("list2", 0,-1) r.lrem ("list2", "99",-1) # delete print (r.lrange ("list2", 0) that first appears on the right side of the list -1)) r.lrem ("list2", "22", 0) # removes all "22" from the list from print (r.lrange ("list2", 0,-1))
Run result (found to be unsuccessful, no reason found):
['- 11','11','- 11','00','11','22','33','11','22','33','99'] ['- 11','11','- 11','11','22','33','11','22','33','99'] ['- 11','11','- 11' '00,' 11, 22, 33, 11, 22, 33, 22, 99]
3.10 lpop delete and return
R.lpop (name)
Get the first element on the left side of the list corresponding to name and remove it from the list, and the return value is the first element.
More:
Rpop (name) means to operate from right to left
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.lrem ("list2", "11", 1) # delete the "11" that first appears on the left side of the list print (r.lrange ("list2", 0,-1) r.lrem ("list2", "99",-1) # delete print (r.lrange ("list2", 0) that first appears on the right side of the list -1)) r.lrem ("list2", "22", 0) # removes all "22" from the list from print (r.lrange ("list2", 0,-1))
Running result:
['11','- 11','00','11','22','33','11','22','33','99'] ['11','- 11','00','11','22','33','11','22','33']
3.11 ltrim deletes values other than the index
Ltrim (name, start, end)
Remove values that are not between start-end indexes in the list corresponding to name
Parameters:
Name of name-redis
Start-start position of the index
End-where the index ends
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.lrange ("list2", 0,-1)) r.ltrim ("list2", 0, 2) # Delete elements with index numbers other than 0-2, and values retain elements with index numbers 0-2 print (r.lrange ("list2", 0,-1))
Running result:
['11','- 11','00','11','22','33','11','22','33'] ['11,'- 11,'00']
3.12 lindex value (based on index number)
Lindex (name, index)
Get the list elements according to the index in the list corresponding to name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.lrange ("list2", 0,-1)) print (r.lindex ("list2", 0)) # take out the value where the index number is 0
Running result:
['11','- 11','00'] 11
3.13 rpoplpush move elements from one list to another
Rpoplpush (src, dst)
Take the rightmost element from one list and add it to the leftmost part of another list
Parameters:
Src-name of the list to fetch data
Dst-name of the list to add data to
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.lrange ("list1", 0,-1)) print (r.lrange ("list2", 0,-1) r.rpoplpush ("list1", "list2") print (r.lrange ("list2", 0,-1))
Running result:
['33','22','11'] ['11','- 11','00'] ['11,'11,'- 11, '00']
3.14 brpoplpush moving elements from one list to another can set a timeout
Brpoplpush (src, dst, timeout=0)
Remove an element from the right side of one list and add it to the left side of another list
Parameters:
Src-name corresponding to the list of elements to be removed and removed
Dst-name corresponding to the list of elements to be inserted
Timeout-when there is no data in the list corresponding to src, the blocking waits for the timeout for which it has data (in seconds). 0 indicates permanent blocking.
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.lrange ("list1", 0,-1)) print (r.lrange ("list2", 0,-1) r.brpoplpush ("list1", "list2", timeout=2) print (r.lrange ("list2", 0,-1))
Running result:
['33','22'] ['11','11','- 11','00'] ['22','11','11','11','00']
3.15 blpop removes multiple lists at a time
Blpop (keys, timeout)
Arrange multiple lists according to the elements that pop the corresponding list from left to right
Parameters:
Collection of name for keys-redis
Timeout-timeout. When all the list elements of the element have been fetched, the blocking waits for the time in which there is data in the list (in seconds). 0 means forever blocking.
More:
R.brpop (keys, timeout), like blpop, arranges multiple lists and removes elements from each list from the right image to the left.
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.lpush ("list10", 3,4,5) r.lpush ("list11", 3,4,5) while True: r.blpop (["list10", "list11"], timeout=2) print (r.lrange ("list10", 0,-1), r.lrange ("list11", 0,-1))
Running result:
['44th,' 3'] [54th, 44th, 3'] [3'] [54th, 44th, 3'] [] [54th, 44th, 3'] [] [54th, 44th, 3'] [] [44th, 3'] [] [3'] []
3.16 Custom incremental iterations:
Since incremental iterations over list elements are not provided in the redis class library, if you want to loop through all the elements of the list corresponding to name, you need to get all the lists corresponding to name.
Circular list
However, if the list is very large, it is possible to burst the contents of the program in the first step, so it is necessary to customize the functionality of an incremental iteration:
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.lrange ("list2", 0,-1)) def list_iter (name): "" Custom redis list incremental iteration: param name: name in redis That is: iterate through the list corresponding to name: return: yield returns the list element "" list_count = r.llen (name) for index in range (list_count): yield r.lindex (name, index) # use for item in list_iter ('list2'): # to traverse the list print (item)
Running result:
['22,'11,'11,'- 11,] 221111-11004) set
4.1 New to sadd
Sadd (name,values)
Name-add elements to the corresponding collection
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.sadd ("set1", 33, 44, 55, 66) # add elements print (r.scard ("set1")) # the length of the collection is 4print (r.smembers ("set1")) # get all the members of the collection
Running result:
4 {'66','55,'44','33'}
4.2 scard. Getting the number of elements is similar to len
Scard (name)
Get the number of elements in the set corresponding to name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.smembers ("set1")) # get all members of the collection print (r.scard ("set1")) # the length of the collection is 4
Running result:
{'55','66','33,'44'} 4
4.3 smembets gets all the members of the collection
Smembers (name)
Get all members of the collection corresponding to name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.smembers ("set1")) # get all members of the collection sscan (name, cursor=0, match=None, count=None)
Running result:
{'55,'66,'33,'44'}
4.4 sscan gets all the members of the collection-tuple form
Sscan (name, cursor=0, match=None, count=None)
Get all the members in the collection-- tuple form
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.sscan ("set1"))
Running result:
(0, ['33,'44,'55,'66])
4.5 the way sscan_iter gets all the members of the collection-- iterators
Sscan_iter (name, match=None, count=None)
The way to get all the members of the collection-- iterators
The operation of the same string is used to incrementally iterate and get elements in batches to avoid consuming too much memory.
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.sscan ("set1"))
Running result:
33445566
4.6 sdiff difference
Sdiff (keys, * args)
A collection of elements in the set corresponding to the first name and not in the set corresponding to the other name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.sadd ("set2", 11,22,33) print (r.smembers ("set1")) # get all members of the collection print (r.smembers ("set2")) print (r.sdiff ("set1", "set2")) # print (r.sdiff ("set2") in the collection set1 but not in the collection set2 "set1")) # in the collection set2 but not in the collection set1
Running result:
{'55','33,'66,'44'} {'22','33','11'} {'55','66','44'} {'22', '11'}
4.6 sdiffstore difference-difference exists in a new set
Sdiffstore (dest, keys, * args)
Get the set corresponding to the first name and not in the other name, and then add it to the set corresponding to dest
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.sdiffstore ("set3", "set1", "set2") # print in the collection set1 but not in the collection set2 (r.smembers ("set3"))
Running result:
{'55','44','66'}
4.7 sinter intersection
Sinter (keys, * args)
Get the intersection of more than one name corresponding set
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.sinter ("set1", "set2")) # take the intersection of two sets
Running result:
{'33'}
4.8 sunion Union
Sunion (keys, * args)
Get the union of sets corresponding to multiple name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.sunion ("set1", "set2")) # take the union of two sets
Running result:
{'66,'33,'44, 11, 22, 55}
4.9 sunionstore union-there is a new set for union
Sunionstore (dest,keys, * args)
Get the union of one more set corresponding to name, and save the result to the set corresponding to dest
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.sunionstore ("set3", "set1", "set2")) # take the union of two sets print (r.smembers ("set3"))
Running result:
6 {'33,'66,'55,'22,'11,'44'}
4.10 sismember determines whether a member of a collection is similar to in
Sismember (name, value)
Check whether value is a member of the collection corresponding to name, and the result is True and False
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.sismember ("set1", 33)) # 33 is a member of the collection print (r.sismember ("set1", 23)) # 23 is not a member of the collection
Running result:
TrueFalse
4.11 smove Mobility
Smove (src, dst, value)
Move a member from one collection to another
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.smove ("set1", "set2", 44) print (r.smembers ("set1")) print (r.smembers ("set2"))
Running result:
{'66','55,'33'} {'44','33','22','11'}
4.11 spop deletion-randomly delete and return deleted value
Spop (name)
Remove a member from the collection and return it, indicating that the collection is unordered and all are randomly deleted
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.spop ("set2")) # this deleted value is randomly deleted, and the collection is unordered print (r.smembers ("set2"))
Running result:
44 {'11,'22,'33'}
4.12 srem deletion-specify a value to delete
Srem (name, values)
Delete some values from the collection corresponding to name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.srem ("set2", 11)) # removes the specified value 11print (r.smembers ("set2")) from the collection
Running result:
1 {'22','33'} 5) ordered set
Set operation, the Set collection is not allowed to repeat the list, itself is unordered.
An ordered set sorts each element on the basis of the set; the sorting of elements needs to be compared according to another value, so, for an ordered set, each element has two values, that is, a value and a score, and the score is used specifically for sorting.
5.1 New
Zadd (name, mapping, nx=False, xx=False, ch=False, incr=False)
Add elements to the ordered set corresponding to name
Such as:
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.zadd ("zset1", {'n1triple zset1 100,' n2triple zset2 99, 'n3triple zset2 87}) r.zadd ("zset2", {' m1bicycle Vist100, 'M2colored Vista 99,' M3vertical r.zcard 87}) print (r.zcard ("zset1")) # set length print (r.zcard ("zset2")) # set length print (r.zrange ("zset1", 0) -1)) # get all elements in an ordered set print (r.zrange ("zset2", 0,-1, withscores=True)) # get all elements and scores in an ordered set
Running result:
33 ['n _ 3,'n _ 2,'n _ 1] [('m _ 3, 87.0), ('m _ 2, 99.0), ('m _ 1, 100.0)]
5.2 zcard gets the number of ordered set elements similar to len
Zcard (name)
Gets the number of ordered collection elements corresponding to name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.zcard ("zset1")) # Collection length
Running result:
three
5.3 zrange gets all the elements of an ordered collection
Zrange (name, start, end, desc=False, withscores=False, score_cast_func=float)
Get the elements of the ordered collection corresponding to name according to the index range
Parameters:
Name of name-redis
Start-ordered set index start position (non-fractional)
End-ordered set index end position (non-fractional)
Desc-collation, sorted by default by score from smallest to largest
Withscores-whether to get the score of the element. By default, only the value of the element is obtained.
Score_cast_func-function for data conversion of fractions
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.zrange ("zset1", 0,1)) # Collection length
Running result:
['n3','n2']
5.3 zrevrange sorts from largest to smallest (like zrange, collections are sorted from largest to smallest)
Zrevrange (name, start, end, withscores=False, score_cast_func=float)
Sort from large to small (like zrange, collections are sorted from large to small)
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.zrevrange ("zset1", 0,-1)) # get only elements, do not display print (r.zrevrange ("zset1", 0,-1, withscores=True)) # get all elements and fractions in an ordered set, and score in reverse order
Running result:
['N1,'N2, 'N3'] [(' N1, 100.0), ('N2, 99.0), ('n3), 87.0)]
5.4 zrangebyscore gets the elements of the ordered set corresponding to name according to the range of scores
Zrangebyscore (name, min, max, start=None, num=None, withscores=False, score_cast_func=float)
Get the elements of the ordered set corresponding to name according to the range of scores
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) for i in range (1,30): element ='n'+ str (I) r.zadd ("zset3", {element: I}) print (r.zrangebyscore ("zset3", 15,25) # # between 15 and 25, take out the eligible element print (r.zrangebyscore ("zset3", 12,22, withscores=True)) # and the score is between 12 and 22 Take out eligible elements (with scores)
Running result:
['n15,' n16, 'n17,' n18, 'n19,' n20, 'n21,' n22, 'n23,' n24, 'n25] [(' n12, 12.0), ('n13, 13.0), (' n14, 14.0), ('n15, 15.0), (' n16, 16.0), ('n17, 17.0), (' n18, 18.0) ('n19, 19.0), (' n20, 20.0), ('n21, 21.0), (' n22, 22.0)]
5.5 zrevrangebyscore gets the elements of an ordered collection by score range and sorts them (by default, sort from largest to smallest)
Zrevrangebyscore (name, max, min, start=None, num=None, withscores=False, score_cast_func=float)
Get the elements of an ordered collection according to the range of scores and sort them (sort from largest to smallest by default)
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.zrevrangebyscore ("zset3", 22, 11, withscores=True)) # when the score is between 22 and 11, take out the eligible elements according to
Running result:
[('n 22, 22.0), ('n 21, 21.0), ('n 20, 20.0), ('n 19, 19.0), ('n 18, 18.0), ('n 17, 17.0), ('n 16, 16.0), ('n 15, 15.0), ('n 14, 14.0), ('n 13, 13.0), ('n 12, 12.0), ('n 11, 11.0)]
5.6 zscan gets all elements-sort by default in fractional order
Zscan (name, cursor=0, match=None, count=None, score_cast_func=float)
Get all elements-sort by default in fractional order
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.zscan ("zset3"))
Running result:
(0, [('n1, 1.0), ('n2, 2.0), ('n3, 3.0), ('n4, 4.0), ('n5, 5.0), ('n6, 6.0), ('n7, 7.0), ('n9, 9.0), ('n10, 10.0), (' n11, 11.0), ('n12') 12.0), ('n13, 13.0), (' n14, 14.0), ('n15, 15.0), (' n16, 16.0), ('n17, 17.0), (' n18, 18.0), ('n20, 20.0), (' n21, 21.0), ('n22, 22.0), (' n23, 23.0), ('n24') 24.0), ('n25, 25.0), (' n26, 26.0), ('n27, 27.0), (' n28, 28.0), ('n29, 29.0)])
5.7 zscan_iter gets all elements-- iterator
Zscan_iter (name, match=None, count=None,score_cast_func=float)
Get all elements-- iterators
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.zscan ("zset3"))
Running result:
('n _ 1, 1.0) ('n _ 2, 2) ('n _ 3, 3) ('n _ 4, 4. 0) ('n _ 5, 5), 5.0) ('n _ 6, 6, 6.0) ('n _ 7, 7. 0) ('n _ 8, 8) (9.0) ('n _ 10, 10.0) ('n _ 12, 12.0) ('n _ 13, 13.0) ('n _ 14, 14.0) ('n _ 15' 15.0) ('n16 cycles, 16.0) (' n17 cycles, 17.0) ('n18 cycles, 18.0) (' n20 cycles, 19.0) ('n20 cycles, 20.0) (' n21 cycles, 21.0) ('n22 cycles, 22.0) (' n24 cycles, 23.0) ('n24 cycles, 24.0) (' n26 cycles, 26.0) ('n27 cycles, 27.0) (' n28 cycles, 28.0) ('n29 cycles, 29.0)
5.8 zcount obtains the number of scores between [min,max] in the ordered set corresponding to name
Zcount (name, min, max)
Get the number of scores between [min,max] in the ordered set corresponding to name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.zrange ("zset3", 0,-1, withscores=True)) print (r.zcount ("zset3", 11,22))
Running result:
[('n _ 1, 1.0), ('n _ 2, 2), ('n _ 3, 3.0), ('n _ 4, 4. 0), ('n _ 5, 5), ('n _ 6, 6), ('n _ 7, 7.0), ('n _ 8, 8.0), ('n _ 9, 9.0), ('n _ 10, 10.0), ('n _ 11, 11.0), ('n _ 12, 12.0) ('n 13, 13.0), ('n 14, 14.0), ('n 15, 15.0), ('n 16, 16.0), ('n 17, 17.0), ('n 18, 18.0), ('n 19, 19.0), ('n 20, 20.0), ('n 21, 21.0), ('n 22, 22.0), ('n 23, 23.0), ('n 24, 24.0) ('n25, 25.0), (' n26, 26.0), ('n27, 27.0), (' n28, 28.0), ('n29, 29.0)] 12
5.9 zincrby self-increasing
Zincrby (name, amount, value)
The score of name corresponding to the ordered set corresponding to the self-increasing name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.zincrby ("zset3", 2, "N2") # increase the score of N2 by 2print (r.zrange ("zset3", 0,-1, withscores=True)) each time
Running result:
[('n1stories, 1.0), (' n3cycles, 3.0), ('n2cycles, 4.0), (' n4cycles, 4.0), ('n5cycles, 5.0), (' n6cycles, 6.0), ('n7cycles, 7.0), (' n8cycles, 8.0), ('n9cycles, 9.0), (' n10cycles, 10.0), ('n11levels, 11.0), (' n12cycles, 12.0) ('n 13, 13.0), ('n 14, 14.0), ('n 15, 15.0), ('n 16, 16.0), ('n 17, 17.0), ('n 18, 18.0), ('n 19, 19.0), ('n 20, 20.0), ('n 21, 21.0), ('n 22, 22.0), ('n 23, 23.0), ('n 24, 24.0) ('n25, 25.0), (' n26, 26.0), ('n27, 27.0), (' n28, 28.0), ('n29, 29.0)]
5.10 the index number of the value obtained by zrank
Zrank (name, value)
Gets the index of a value in the ordered collection corresponding to name (starting at 0)
More:
Zrevrank (name, value), sorted from big to small
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.zrank ("zset3", "N1")) # N1 is 0 where the index number of print (r.zrank ("zset3", "N1") # N1 is 1print (r.zrevrank ("zset3", "N1")) # N1 is 29 here in reverse order of scores (from big to small)
Running result:
0528
5.11 zrem deletion-specify a value to delete
Zrem (name, values)
Delete the ordered set corresponding to name. The values are members of values.
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.zrem ("zset3", "n3") # Delete elements in an ordered set n3 Delete a single print (r.zrange ("zset3", 0,-1))
Running result:
['N1,'n2,'n4,'n5,'n6,'n7,'n8,'n9, 'n10,' n11, 'n12,' n13, 'n14,' n15, 'n16,' n17, 'n18,' n19, 'n20,' n21, 'n22,' n23, 'n24,' n25, 'n26,' n27' 'n28percent, 'n29']
5.12 zremrangebyrank deletion-delete according to ranking range and index number
Zremrangebyrank (name, min, max)
Delete according to ranking range
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.zremrangebyrank ("zset3", 0,1) # Delete the element print (r.zrange ("zset3", 0,-1)) whose index number is 0,1 in the ordered set
Running result:
['n4,'n5,'n6,'n7,'n8,'n9, 'n10,' n11, 'n12,' n13, 'n14,' n15, 'n16,' n17, 'n18,' n19, 'n20,' n21, 'n22,' n23, 'n24,' n25, n26, n27, n28, n29]
5.13 zremrangebyscore deletion-delete based on score range
Zremrangebyscore (name, min, max)
Delete according to ranking range-delete according to score range
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.zremrangebyscore ("zset3", 11,22) # Delete the element print (r.zrange ("zset3", 0,-1)) with a score of 11-22 in the ordered set
Running result:
['n4,'n5,'n6,'n7,'n8,'n9, 'n10,' n23, 'n24,' n25, 'n26,' n27, 'n28,' n29']
5.14 zscore gets the score corresponding to the value
Zscore (name, value)
Get the score corresponding to value in the ordered set corresponding to name
Import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) print (r.zscore ("zset3", "N27")) # gets the score 27 for element N27
Running result:
27.01. Delete delete (* names)
Based on the deletion of any data type in redis (string, hash, list, set, ordered set)
R.delete ("gender") # removes the key-value pair whose key is gender. Check if the name exists exists (name)
Check whether the name of redis exists. It means that True,False does not exist.
Print (r.exists ("zset1")) 3. Fuzzy matching keys (pattern='')
Get the name of redis based on model
More:
KEYS * matches all the key in the database.
KEYS h?llo matches hello, hallo, hxllo and so on.
KEYS hllo matches hllo, heeeeello, and so on.
KEYS h [ae] llo matches hello and hallo, but not hillo
Print (r.keys ("foo*")) 4. Set the timeout expire (name, time)
Set the timeout for a name of a redis
R.lpush ("list5", 11,22) r.expire ("list5", time=3) print (r.lrange ("list5", 0,-1)) time.sleep (3) print (r.lrange ("list5", 0,-1)) 5. Rename rename (src, dst)
Rename the name of redis
R.lpush ("list5", 11,22) r.rename ("list5", "list5-1") 6. Get namerandomkey randomly ()
Randomly get the name of a redis (do not delete)
Print (r.randomkey ()) 7. Get type type (name)
Get the type of name corresponding value
Print (r.type ("set1") print (r.type ("hash2")) 8. View all elements import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.scan (cursor=0, match=None, count=None) print (r.hscan ("hash2")) print (r.sscan ("set3")) print (r.zscan ("zset2") print (r.getrange ("foo1", 0,-1) print (r.lrange ("list2", 0,-1) print (r.smembers ("set3")) print (r.zrange ("zset3", 0) -1)) print (r.hgetall ("hash1"))
Running result:
(0, {'k2fang:' v2fang, 'K3efficiency:' v3'}) (0, ['11,'22,'33,'44,'55,'66]) (0, [('m3), 87.0), ('m2, 99.0), ('m1, 100.0)]) 123 ['22,'11,'11,'- 11, '00'] {' 66' '55,' 11,'44, 22,'33} ['n4,'n5,'n6,'n7,'n8,'n9, 'n10,' n23, 'n24,' n25, 'n26,' n27, 'n28,' n29] {'k2: 'v222,' k11: v1,'k3: '122' 'k4':'1'} 9. View all elements-iterator import redisr = redis.Redis (host='localhost', port=6379, db=0, decode_responses=True) r.scan_iter (match=None, count=None) for i in r.hscan_iter ("hash1"): print (I) for i in r.sscan_iter ("set3"): print (I) for i in r.zscan_iter ("zset3"): print (I)
Running result:
('k2trees,' v222') ('K11levels,' v1') ('K3lines,' 122') ('k4legs,' 1') 112233445566 ('n4cycles, 4.0) (' n5cycles, 5.0) ('n7cycles, 6.0) (' n7cycles, 7.0) ('n9cycles, 9.0) (' n10cycles, 10.0) ('n23levels, 23.0) (' n24levels, 24.0) ('n25') Import redisr = redis.Redis (host='localhost', port=6379, db=0) Decode_responses=True) print (r.get ('name')) # query the value of key as name r.delete ("gender") # Delete the key value of key as gender to print (r.keys ()) # query all Keyprint (r.dbsize ()) # how many pieces of data r.save () is currently contained in redis # perform a "checkpoint" operation Write the data back to disk. Block # r.flushdb () # clear all data in r when saving
Running result:
None ['set2',' K2Qing, 'food',' visit:12306:totals', 'foo',' foono', 'set3',' list2', 'cn_name',' foo2', 'n3examples,' foo1', 'new_name',' too', 'zset1',' list1', 'set1',' hash1', 'zset2',' N1, 'hash2',' foo4','N2, 'en_name' 'K1century, 'zset3',' foo1s'] 27
By default, redis creates (connection pooling requests for connections) and disconnects (returns connection pooling) for each request. If you want to specify multiple commands in one request, you can use pipline to specify multiple commands for one request, and pipline is atomic by default.
Pipeline is a subclass of the base class that redis buffers multiple server commands in a single request. It greatly improves the ability to execute batch commands by reducing the repeated TCP database packages between the server and the client.
Import redisimport timepool = redis.ConnectionPool (host='localhost', port=6379, decode_responses=True) r = redis.Redis (connection_pool=pool) # pipe = r.pipeline (transaction=False) # by default, commands executed in pipes guarantee atomicity, and execution pipe = r.pipeline (transaction=False) disables this feature. # pipe = r.pipeline (transaction=True) pipe = r.pipeline () # create a pipe pipe.set ('name',' jack') pipe.set ('role',' sb') pipe.sadd ('faz',' baz') pipe.incr ('num') # vaule is 1 if num does not exist, if it exists Then value adds 1pipe.execute () print (r.get ("name")) print (r.get ("role")) print (r.get ("num"))
Running result:
Jacksb1
Pipe commands can be written together, such as:
Import redisimport timepool = redis.ConnectionPool (host='localhost', port=6379, decode_responses=True) r = redis.Redis (connection_pool=pool) pipe = r.pipeline () # create a pipe pipe.set ('hello',' redis'). Sadd ('faz',' baz'). Incr ('num'). Execute () print (r.get ("name") print (r.get ("role")) print (r.get ("num"))
Running result:
Jacksb1 above is about the content of this article on "redis instance Analysis of python Operation". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.