I. Installation
- redis is a Key-Value database.
- Value supports string, list, set, zset, hash and so on.
pip install redis
II. Connections
import redis # Mode I r = (host='localhost', port=6379, db=0) # Mode II r = (host='localhost', port=6379, decode_responses=True) # Way three, connection pooling pool = (host='localhost', port=6379, decode_responses=True) r = (host='localhost', port=6379, decode_responses=True)
III. Basic string commands
import redis r = (host='localhost', port=6379, decode_responses=True) # Set the value and set the expiration time, ex unit: seconds ('food', 'mutton', ex=3) # Get the value ('food') # Set value and set expiration time, px unit: milliseconds ('food', 'beef', px=3) # nx=True, then the current set operation is executed only if name does not exist. ('fruit', 'watermelon', nx=True) # xx=True, then the current set operation is executed only if name exists. ('fruit', 'watermelon', xx=True) # setnx sets the value and performs the set operation only if name does not exist ('fruit1', 'banana') # setex The first argument is the key, the second is the expiration time (in seconds), and the third is the value. ("fruit2", 5, "orange") # psetex The first argument is the key, the second is the expiration time (in milliseconds), and the third is the value. ("fruit3", 5000, "apple") # batch set values mset(*args, **kwargs) (k1="v1", k2="v2") # Batch fetch ('k1', 'k2') (['k1', 'k2']) # Set the new value and get the original value ("food", "barbecue") # Fetch subsequences (byte-based, not character-based) ("cn_name", 0, 2) ("en_name", 0, -1) # Modify string content, replacing backward from the specified string index (or adding backward if the new value is too long) ("en_name", 1, "ccc") # Operate on the bits of the binary representation of the value corresponding to name (name, offset, value) # Get the value of a bit in the binary representation of the value corresponding to name, 0 or 1. ("foo1", 0) # Get the number of 1's in the binary representation of the value corresponding to name. ("foo",0,1) # Get multiple values and do bitwise operations on the values, saving the final result to the value corresponding to the new name ("AND","new","foo","foo1") # Returns the length in bytes of the value corresponding to name (3 bytes for a Chinese character) ("foo") # Self-increment the value corresponding to name, create name=amount when name does not exist, otherwise, self-increment. ("foo", amount=1) # self-increment The value corresponding to name, created when name does not exist name = amount, otherwise, self-incremented. ("foo1", amount=2.0) # Self-decrease the value corresponding to name, create name = amount when name does not exist, otherwise, self-decrease. ("foo4", amount=3) # append to the value corresponding to redis name ("name", "haha")
IV. Basic hash commands
import redis r = (host='localhost', port=6379, decode_responses=True) # name sets a key-value pair in the corresponding hash (if it doesn't exist, create it; otherwise, modify it) ("hash1", "k1", "v1") # Bulk set key-value pairs in the hash corresponding to name ("hash2", {"k2": "v2", "k3": "v3"}) # Get the value based on the key in the hash corresponding to the name ("hash2", "k2", "k3") ("hash2", ["k2", "k3"]) # Fetch all key-value pairs ("hash1") # Get the format hash length of all key-value pairs ("hash1") # Get all the keys (similar to a dictionary that takes all the keys) ("hash1") # Get all the values (similar to a dictionary that takes all the values) ("hash1") # Determine if a member exists (dictionary-like in) ("hash1", "k4") # Delete key-value pairs ("hash1", "k1") # Self-increasing and self-decreasing integers ("hash1", "k3", amount=-1) # Self-incrementing and self-decrementing floating point numbers ("hash1", "k5", amount=-1.0) # Fetch View - Sliced Reads ("hash1") # Create a generator using yield wrapped hscan to batch fetch data from redis for item in r.hscan_iter('hash1'): print(item) print(r.hscan_iter("hash1"))
V. List Basic Commands
import redis r = (host='localhost', port=6379, decode_responses=True) # Add (new from the left) - new if you don't have one ("list1", 11, 22, 33) # Add (from the right) - if not there, create a new one ("list2", 11, 22, 33) # Add an element to the list corresponding to name, only if name already exists, the value is added to the far left of the list ("list10", 10) # Add an element to the right of a list of names that already exists, but can't be created without it. ("list2", 99) # Insert a new value before or after one of the values in the list corresponding to name. ("list2", "before", "11", "00") # Modify (specify index number to modify) ("list2", 0, -11) # Delete (specify value for deletion) ("list2", "11", 1) # Delete and return ("list2") # Removes the leftmost element of the list and returns the deleted element ("list2") # Delete the rightmost element of the list and return the deleted element # Delete values outside the index ("list2", 0, 2) # Value based on index number ("list2", 0) # move The element moves from one list to another ("list1", "list2") # move An element is moved from one list to another A timeout can be set ("list1", "list2", timeout=2) # Remove multiple lists at once (["list10", "list11"], timeout=2) # Customize incremental iterations def list_iter(name): """ Customize the incremental iteration of a redis list :param name: name in redis, i.e.: iterate over the list corresponding to name :return: yield Returns the list element """ list_count = (name) for index in range(list_count): yield (name, index)
VI. Set basic commands
import redis r = (host='localhost', port=6379, decode_responses=True) # New ("set1", 33, 44, 55, 66) # Get the number of elements similar to len ("set1") # Get all the members of the collection ("set1") # Get all members of a collection - in tuple form ("set1") # Get all the members of a collection - the iterator way for i in r.sscan_iter("set1"): print(i) # Difference sets ("set1", "set2") # Difference sets - difference sets exist in a new set ("set3", "set1", "set2") # Intersection ("set1", "set2") # Intersection - intersection exists in a new set ("set3", "set1", "set2") # And the concatenation ("set1", "set2") # Concatenation - a new set exists for concatenation ("set3", "set1", "set2") # Determine if it's a member of a collection similar to in ("set1", 33) # Move Move a member from one collection to another collection ("set1", "set2", 44) # Delete - randomly deletes and returns the deleted value ("set2") # Delete - specified value deletion ("set2", 11)
VII. zset basic commands
import redis r = (host='localhost', port=6379, decode_responses=True) # New ("zset2", 'm1', 22, 'm2', 44) # Get the number of elements in an ordered set similar to len ("zset1") # Get all the elements of an ordered set ("zset1", 0, -1) # Get all elements - iterator for i in r.zscan_iter("zset3"): # Iterate over the iterator print(i) # Get the number of scores between [min,max] in the ordered set corresponding to name. ("zset3", 11, 22) # Self-incrementing ("zset3", "n2", amount=2) # Get the index number of the value ("zset3", "n1") # Delete - specified value deletion ("zset3", "n3") # Delete - delete based on ranking range, by index number ("zset3", 0, 1) # Delete - based on score ranges ("zset3", 11, 22) # Get the score corresponding to the value ("zset3", "n27")
VIII. Other general orders
import redis r = (host='localhost', port=6379, decode_responses=True) # delete Based on deleting any data type in redis ("gender") # Check if the name exists ("zset1") # fuzzy matching Get name of redis based on the model ("foo*") # Set the timeout period ("list5", time=3) # Rename ("list5", "list5-1") # Randomize the name () # Get type ("set1") # Query all Keys () # How many pieces of data does redis currently contain () # Clear all data in r ()
IX. Pipeline commands
- By default, redis creates (pools a connection) and disconnects (returns it to the pool) one connection per request.
- If you want to specify multiple commands in a single request, you can use pipline to specify multiple commands in a single request
- And by default, a pipline is atomic.
- Pipeline is a subclass of redis' base class that buffers multiple server commands in a single request.
- It does this by reducing the number of repeated TCP database packets between server-client
- This greatly improves the ability to execute batch commands
import redis r = (host='localhost', port=6379, decode_responses=True) # By default, commands executed in the pipeline guarantee atomicity of execution # Default pipe = (transaction=True) # Prohibit pipe = (transaction=False) # Create a pipeline pipe = () ('name', 'jack') ('role', 'sb') ('faz', 'baz') ('num') () # Or write ('hello', 'redis').sadd('faz', 'baz').incr('num').execute() print(("name")) print(("role")) print(("num"))
to this article on the python package redis database operation tutorial article is introduced to this, more related to the operation of the redis database content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!