In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Today, I would like to share with you the relevant knowledge of how python operates the redis database. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
I. installation
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 redis II, connection import redis# mode 1 r = redis.StrictRedis (host='localhost', port=6379, db=0) # mode 2 r = redis.Redis (host='localhost', port=6379, decode_responses=True) # mode 3, connection pool pool = redis.ConnectionPool (host='localhost', port=6379, decode_responses=True) r = redis.Redis (host='localhost', port=6379, decode_responses=True) 3, string basic command import redisr = redis.Redis (host='localhost', port=6379, decode_responses=True) # set the value and set the expiration time Ex unit: second r.set ('food',' mutton', ex=3) # get value r.get ('food') # set value and set expiration time, px unit: millisecond r.set (' food', 'beef', px=3) # nx=True, then only when name does not exist When the current set operation executes r.set ('fruit',' watermelon', nx=True) # xx=True, the current set operation executes the r.set ('fruit',' watermelon', xx=True) # setnx setting value only if name exists, and only if name does not exist Perform the setting operation r.setnx ('fruit1',' banana') # setex the first parameter is key, the second is the expiration time (seconds), the third is the value r.setex ("fruit2", 5, "orange") # psetex the first parameter is key, the second is the expiration time (milliseconds), and the third is the value r.psetex ("fruit3", 5000, "apple") # batch setting value mset (* args, * * kwargs) r.mset (K1 = "v1") K2 = "v2") # get r.mget in batches ('K1, 'K2') r.mget ([' K1, 'K2']) # set the new value and get the original value r.getset ("food", "barbecue") # get the subsequence (based on bytes Non-character) r.getrange ("cn_name", 0,2) r.getrange ("en_name", 0,-1) # modify the string content, replacing it backwards from the specified string index (if the new value is too long Then add) r.setrange ("en_name", 1, "ccc") # to operate on the bits in the binary representation of the corresponding values of name r.setbit (name, offset, value) # to obtain the value of a bit in the binary representation of the values corresponding to name, 0 or 1r.getbit ("foo1", 0) # to obtain the number of 1 in the binary representation of values corresponding to name r.bitcount ("foo", 0prime1) # to obtain multiple values, and perform bit operations on the values Save the final result to the new name corresponding value r.bitop ("AND", "new", "foo", "foo1") # returns the byte length of the corresponding value of name (3 bytes of a Chinese character) r.strlen ("foo") # increments the corresponding value of name, when name does not exist, name=amount is created, otherwise, it increments itself. R.incr ("foo", amount=1) # increments the corresponding value of name. If name does not exist, create name=amount. Otherwise, it increments itself. R.incrbyfloat ("foo1", amount=2.0) # subtracts the value of name. If name does not exist, name=amount is created, otherwise, it is self-subtracted. R.decr ("foo4", amount=3) # append the content r.append ("name", "") after the corresponding value of redis name. 4. The hash basic command import redisr = redis.Redis (host='localhost', port=6379, decode_responses=True) # name sets a key-value pair in the hash corresponding to the value that does not exist. otherwise, Modify) r.hset ("hash2", "K1", "v1") # set the key value pair r.hmset in batch in the hash corresponding to name ("hash3", {"K2": "v2", "K3": "v3"}) # obtain valuer.hmget ("hash3", "K2", "K3") r.hmget ("hash3", ["K2") from the hash corresponding to name. "K3") # take out all key-value pairs r.hgetall ("hash2") # get the format hash length of all key-value pairs r.hlen ("hash2") # get all keys (similar dictionary take all keys) r.hkeys ("hash2") # get all value (similar dictionary take all value) r.hvals ("hash2") # determine whether members exist (similar to dictionary in) r.hexists ("hash2") "K4") # Delete key value pair r.hdel ("hash2", "K1") # self-increasing and decreasing integer r.hincrby ("hash2", "K3", amount=-1) # self-increasing and decreasing floating point r.hincrbyfloat ("hash2", "K5", amount=-1.0) # value view-- sharding reading r.hscan ("hash2") # creating a generator using yield encapsulated hscan To get data from redis in batches for item in r.hscan_iter ('hash2'): print (item) print (r.hscan_iter ("hash2")) 5. List basic command import redisr = redis.Redis (host='localhost', port=6379, decode_responses=True) # increased (new from the left)-- no new r.lpush ("list1", 11,22,33) # increased (from the right)-- no new r.rpush ("list2", 11,22) 33) # add elements to the list corresponding to name Only when name already exists, the value is added to the leftmost r.lpushx ("list10", 10) # to the right of the list of existing name Cannot create r.rpushx ("list2", 99) # insert a new value r.linsert ("list2", "before", "11", "00") # modify (specify the index number to modify) r.lset ("list2", 0,-11) # delete (specify the value to delete) r.lrem ("list2", "11") 1) # Delete and return r.lpop ("list2") # Delete the leftmost element of the list And return the deleted element r.rpop ("list2") # delete the rightmost element in the list And return the deleted element # delete the value outside the index r.ltrim ("list2", 0,2) # take the value r.lindex ("list2", 0) # move the element from one list to another list r.rpoplpush ("list1", "list2") # move the element from one list to another list can set the timeout r.brpoplpush ("list1", "list2") Timeout=2) # remove multiple lists at a time r.blpop (["list10", "list11"], timeout=2) # Custom incremental iteration def list_iter (name): "" Custom redis list incremental iteration: param name: name in redis That is, the list corresponding to iterative name: return: yield returns the list element "" list_count = r.llen (name) for index in range (list_count): yield r.lindex (name, index) VI. Set basic command import redisr = redis.Redis (host='localhost', port=6379, decode_responses=True) # add r.sadd ("set1", 33, 44, 55) 66) # getting the number of elements is similar to lenr.scard ("set1") # getting all members in the collection r.smembers ("set1") # getting all members in the collection-- tuple form r.sscan ("set1") # how to get all members in the collection-- iterator for i in r.sscan_iter ("set1"): print (I) # difference r.sdiff ("set1") "set2") # difference-- difference exists in a new set r.sdiffstore ("set3", "set1", "set2") # intersection r.sinter ("set1", "set2") # intersection-intersection exists in a new set r.sinterstore ("set3", "set1", "set2") # Union r.sunion ("set1") "set2") # Union-Union exists a new collection r.sunionstore ("set3", "set1", "set2") # determines whether it is a member of a collection similar to inr.sismember ("set1", 33) # Mobile moves a member from one collection to another collection r.smove ("set1", "set2") 44) # Delete-- randomly delete and return deleted value r.spop ("set2") # Delete-- specify value to delete r.srem ("set2", 11) 7. Zset basic command import redisr = redis.Redis (host='localhost', port=6379, decode_responses=True) # add r.zadd ("zset2",'M1, 22, 'm2') 44) # get the number of elements in an ordered set similar to lenr.zcard ("zset1") # get all elements of an ordered set r.zrevrange ("zset1", 0,-1) # get all elements-- iterator for i in r.zscan_iter ("zset3"): # ergodic iterator print (I) # get the number of r.zcount with scores between [min,max] in the ordered set corresponding to name ("zset3", 11) 22) # add r.zincrby ("zset3", "N2", amount=2) # to get the index number r.zrank ("zset3", "N1") # delete-- specify the value to delete r.zrem ("zset3", "N2") # delete-delete according to the ranking range Delete r.zremrangebyrank according to index number ("zset3", 0,1) # delete-delete r.zremrangebyscore ("zset3", 11,22) # get the corresponding score r.zscore ("zset3", "N27") 8, other general commands import redisr = redis.Redis (host='localhost', port=6379) Decode_responses=True) # Delete any data type r.delete ("gender") # check the existence of the name r.exists ("zset1") # Fuzzy match gets the namer.keys ("foo*") of redis based on the model # set the timeout r.expire ("list5", time=3) # rename r.rename ("list5") "list5-1") # randomly get namer.randomkey () # get type r.type ("set1") # query all Keyr.keys () # how many pieces of data does the current redis contain r.dbsize () # clear all data in r r.flushdb () IX, pipe command
By default, redis creates (connection pool applies for connection) and disconnects (returns connection pool) a connection operation for each request.
If you want to specify multiple commands in one request, you can use pipline to implement multiple commands in one request
And by default, the pipline is atomic.
Pipeline is a subclass of the base class of redis that buffers multiple server commands in a single request
It reduces repeated TCP database packages between the server and the client
As a result, the function of executing batch commands is greatly improved.
Import redisr = redis.Redis (host='localhost', port=6379, decode_responses=True) # by default Commands executed in pipes guarantee atomicity # default pipe = r.pipeline (transaction=True) # prohibit pipe = r.pipeline (transaction=False) # create a pipe pipe = r.pipeline () pipe.set ('name',' jack') pipe.set ('role',' sb') pipe.sadd ('faz',' baz') pipe.incr ('num') pipe.execute () # or write pipe.set (' hello') 'redis'). Sadd (' faz', 'baz'). Incr (' num'). Execute () print (r.get ("name")) print (r.get ("role")) print (r.get ("num")) are all the contents of the article "how python operates the redis database" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to 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.