directory
- preface
- Redis GUI tools
- Redis meets the Docker
- Redis string
- Redis hash
- Redis list
- Redis set
- Redis zset
- Afterword.
preface
The previous article introduced the MongoDB library. I put MySQL at the end of the article, and this article continues the Redis operation. Redis supports five data types: string, hash, list, set and zset(sorted set). The chemistry of Python and Redis will be discussed briefly.
Redis GUI tools
First of all, I will introduce Medis, a GUI tool of Redis. It is really cool for beginners to use this tool to view data. You can see data add, delete, change and check in real time without operating the command line to view.
Redis meets the Docker
Those who follow me know that my profile says that my official account will involve docker-related knowledge. However, my recent articles do not involve much, so IN the following articles, I will roughly talk about anything related to Docker. The docker-compose code is as follows.
version: '3'
services:
redis_container:
image: redis
command: redis-server --requirepass yourpassword Configure Redis password
ports:
- "6378:6379" # Mapping port
volumes:
- /your/path/data:/data
Copy the code
Start the command
docker-compose up -d
Copy the code
Redis string
install
pip install redis
Copy the code
The connection
# Normal connection
r = redis.StrictRedis(host='localhost', port=6379, db=0)
r = redis.StrictRedis(host='localhost', port=6379, password="your password", db=0)
# connection pool
"""Redis-py uses a Connection pool to manage all connections to a Redis server, avoiding the overhead of establishing and releasing connections each time. By default, each Redis instance maintains its own connection pool, allowing multiple Redis instances to share a connection pool."""
# host is the redis service IP. The default port is 6379
pool = redis.ConnectionPool(host='localhost', port=6379,decode_responses=True)
r = redis.Redis(connection_pool=pool)
Copy the code
increase
set(name, value, ex=None, px=None, nx=False, xx=False) Ex, expiration time (s) px, expiration time (ms) nx, if set to True, only name does not exist if the currentsetOperation xx, if True, exists only if namesetBefore the operation is executedCopy the code
Set the expiration time to 1 second
r.set('foo'.'zone', ex=1)
Same as above
r.setex('foo'.'zone'1),Same as above
r.psetex('foo', 1000, 'zone')
print(r.get('foo'))
Sleep for 2 seconds before printing
time.sleep(2)
print(r.get('foo'))
Copy the code
To find the
Get (key) Common searchCopy the code
print(r.get('foo'))
Copy the code
Mget (keys, *args) batch lookupCopy the code
# Batch fetch
print(r.mget("k1"."k2")) Fetch multiple key values at once
print(r.mget("k1"))
Copy the code
Get subsequence
Getrange (key, start, end) gets subsequence (by byte, non-character) parameters: name, name of Redis start, start position (byte) end, end position (byte)Copy the code
A character is 3 bytes, a letter is 1 byte
r.set("name"."zonezone")
print(r.getrange('name', 0, 3))
Get all bytes
print(r.getrange('name', 0, 1))Copy the code
Modify the
The original value zonezone is changed to zone is a boy
Setrange (name, offset, value) Changes the contents of the string by replacing the specified string index backwards (if the new value is too long, it is added backwards). Parameter: offset, index of the string, byte (three bytes for a Chinese character) value, the value to be setCopy the code
r.set("name"."zonezone")
r.setrange("name", 4, " is a boy")
print(r.get("name"))
Copy the code
Returns the string length of the corresponding key
r.set("name"."zonezone")
print(r.strlen("name"))
Copy the code
Increment the value of name (int)
Incr (self, name, amount=1) Increments the value of name. If name does not exist, create name = amount; otherwise, increments the value. Parameters: name, name of Redis amount, increment (must be integer)Copy the code
r.set("age", 123).print(r.get("age"))
r.incr("age", amount=1)
print(r.get("age"))
Copy the code
Increment the value of name (float)
Incrbyfloat (self, name, amount=1.0) increses the value of name, if name does not exist, then creates name = amount, otherwise. Parameters: name,Redis name amount, autoincrement (floating point)Copy the code
r.set("age", 123.0)
print(r.get("age"))
r.incrbyfloat("age", amount = 0.2)print(r.get("age"))
Copy the code
Decrement the value of name
r.set("age", 123)
r.decr("age", amount=1) Diminishing # 1
print(r.mget("foo1"."foo4"))
Copy the code
Additional content
Append (key, value) Appends content parameters to the value corresponding to redis name: key, redis name value, string to appendCopy the code
r.set("name"."Attention")
print(r.get("name"))
r.append("name"."Zone7")
print(r.get("name"))
Copy the code
Redis hash
hash
Hset (Name, key, value) Name Corresponding tohashSet a key-value pair (if none exists, create; Otherwise, modify) parameter: name, redis name key, name corresponding tohashKey value, name corresponding tohashNote: hsetnx(name, key, value), when name corresponds tohashIs created when the current key does not exist inCopy the code
r.hset("hash1"."k1"."v1")
r.hset("hash1"."k2"."v2")
# fetch all keys in the hash
print(r.hkeys("hash1"))
# The value of a single hash key
print(r.hget("hash1"."k1"))
# Multiple hash keys
print(r.hmget("hash1"."k1"."k2"))
r.hsetnx("hash1"."k2"."v3")
print(r.hget("hash1"."k2"))
Copy the code
Batch add and batch get
# Batch increment
r.hmset("hash2", {"k1": "v1"."k2": "v2"})
# Batch fetch
print(r.hmget("hash2"."k1"."k2"))
Copy the code
Removes all hash key-value pairs
print(r.hgetall("hash1"))
Copy the code
Get hash length
Hlen (name) Gets the corresponding value of namehashNumber of middle key-value pairsCopy the code
print(r.hlen("hash1"))
Copy the code
Get all keys (similar to dictionary get all keys)
Hkeys (name) Obtains the corresponding value of namehashThe values of all keys inCopy the code
print(r.hkeys("hash1"))
Copy the code
Get all values (like dictionary take all values)
Hvals (name) gets the corresponding values of namehashThe value of all values inCopy the code
print(r.hvals("hash1"))
Copy the code
Check whether members exist (dictionary-like in)
Hexists (name, key) Checks the value corresponding to namehashWhether there is a currently passed keyCopy the code
print(r.hexists("hash1"."k1"))
Copy the code
Delete key-value pairs
Hdel (name,*keys) corresponds to namehashDelete the key-value pair specified in keyCopy the code
r.hset("hash1"."name"."zone")
print(r.hget("hash1"."name"))
r.hdel("hash1"."name")
print(r.hget("hash1"."name"))
Copy the code
Autoincrement autodecrement (int)
Hincrby (name, key, amount=1) Increments the value corresponding to namehashCreate key=amount parameter: name, redis name key,hashCorresponding key amount, incremented (integer)Copy the code
r.hset("hash1"."age", 123)
r.hincrby("hash1"."age", amount=-1)
print(r.hget("hash1"."age"))
r.hincrby("hash1"."age", amount=1) If # does not exist, value defaults to 1
print(r.hget("hash1"."age"))
Copy the code
Increment and decrement (float)
Hincrbyfloat (name, key, amount=1.0) Increment corresponding to namehashCreate key=amount parameter: name, redis name key,hashCorresponding key amount, increment (floating point number) increment name correspondinghashIf not, create key=amountCopy the code
r.hset("hash1"."age"(123.0), r.h. incrbyfloat"hash1"."age", amount = 0.3)print(r.hget("hash1"."age"))
r.hincrbyfloat("hash1"."age", amount = 0.5)If # does not exist, value defaults to 1
print(r.hget("hash1"."age"))
Copy the code
Redis list
Add (none will be created automatically)
Lpush (name,values) adds elements to the list corresponding to name, and each new element is added to the leftmost part of the listCopy the code
r.lpush("left_list", 11, 22, 33)
print(r.lrange('left_list', 0, -1))
r.rpush("right_list", 11, 22, 33)
print(r.lrange("right_list", 0, 3))
print(r.llen("right_list")) List length
Copy the code
Add (does not exist and will not be created automatically)
Lpushx (name,value) adds elements to the list corresponding to name. If name already exists, the value is added to the left of the list. If it does not exist, it will not be created automatically.Copy the code
r.lpushx("left_list", 2222).print(r.lrange('left_list', 0, -1))
r.rpushx("right_list", 1111).print(r.lrange('right_list', 0, 1))Copy the code
new
Linsert (name,where, refValue, value)) insert a new value parameter before or after a value in the list corresponding to name: name, name of rediswhere, BEFORE or AFTER refValue, the benchmark value, that is, the data to be inserted BEFORE and AFTER itCopy the code
Insert element "00" before the first element "11" in the list on the left
r.linsert("left_list"."before"."11"."00")
print(r.lrange("left_list", 0, 1))Copy the code
Modify the
R.set (name, index, value) reassigns an index position in the list corresponding to name: name, redis name index, list index position value, the value to be setCopy the code
r.lset("left_list", 0, "Zone7") [zone7] select * from zone7 where id = 0
print(r.lrange("left_list", 0, 1))Copy the code
delete
R.rem (name, value, num) delete (redis name value, num, num=0) delete (redis name value, num=0) delete (redis name value, num=0) delete (redis name value, num=0) delete (redis name value, num=0) delete (redis name value, num=0) delete (redis name value, num=0) Num =2; If num=1, delete the first num=-2 from front to backCopy the code
# Remove the first occurrence of "33" on the left of the list
r.lrem("left_list"."33"1),print(r.lrange("left_list", 0, 1))Copy the code
Delete and return
Lpop (name) takes the first element to the left of the list corresponding to name and removes it from the list, and returns the first elementCopy the code
print(r.lpop("left_list"))
print(r.lrange("list2", 0, 1))Copy the code
Redis set
increase
Sadd (name,values) Adds elementsCopy the code
r.sadd("set1", 1, 2, 3, 4)
Get the set length
print(r.scard("set1"))
Get all the elements in the collection
print(r.smembers("set1"))
Copy the code
delete
# Common deleteSrem (name, values) deletes some values from the collection corresponding to nameCopy the code
# remove the specified value 1 from the set
print(r.srem("set1", 1))
print(r.smembers("set1"))
Copy the code
Delete randomly and return the deleted valueSpop (name) removes a member from the collection and returns it. To clarify, the collection is unordered and everything is deleted randomlyCopy the code
print(r.spop("set2")) The deleted value is randomly deleted, and the collection is unordered
print(r.smembers("set2"))
Copy the code
To find the
# common fetchSmembers (name) Gets all the members of the collection corresponding to nameCopy the code
print(r.smembers("set1")) Get all the members of the collection
Copy the code
Get the collection as a tuple
sscan(name, cursor=0, match=None, count=None)
Copy the code
print(r.sscan("set1"))
Copy the code
Get the collection as an iteratorSscan_iter (name, match=None, count=None) Is a string operation used to obtain elements in batches by incremental iteration to avoid memory consumptionCopy the code
for i in r.sscan_iter("set1") :print(i)
Copy the code
intersection
Sinter (keys, *args) gets the intersection of multiple sets of namesCopy the code
r.sadd("set2", 1, 2, 3, 4)
r.sadd("set3", 3, 4, 5, 6)
print(r.sinter("set2"."set3"))
Copy the code
Sinterstore (dest, keys, *args) takes the union of multiple sets of names and adds the union to dest(the target set)Copy the code
r.sadd("set2", 1, 2, 3, 4)
r.sadd("set3", 3, 4, 5, 6)
print(r.sinterstore("set4"."set2"."set3"))
print(r.smembers("set4"))
Copy the code
mobile
Smove (SRC, DST, value) moves a member from one set to anotherCopy the code
r.smove("set2"."set3", 3)
print(r.smembers("set2"))
print(r.smembers("set3"))
Copy the code
Determines if there is an element in the set
Sismember (name, value) checks if value is a member of the set corresponding to name, giving True and FalseCopy the code
print(r.sismember("set2", 3))
print(r.sismember("set3", 1))
Copy the code
And set
Sunion (keys, *args) gets the union of multiple sets corresponding to namesCopy the code
r.sadd("set2", 1, 2, 3, 4)
r.sadd("set3", 3, 4, 5, 6)
print(r.sunion("set2"."set3"))
Copy the code
Sunionstore (dest,keys, *args) fetches the union of multiple sets corresponding to name and saves the result into the set corresponding to destCopy the code
r.sadd("set2", 1, 2, 3, 4)
r.sadd("set3", 3, 4, 5, 6)
print(r.sunionstore("set4"."set2"."set3")) # take the union of 2 sets
print(r.smembers("set4"))
Copy the code
Redis zset
A set is an unordered list that does not allow repetition
increase
Zadd (name, *args, **kwargs) adds elements to the ordered collection corresponding to nameCopy the code
r.zadd("zset1", n1=123, n2=234)
print(r.zrange("zset1", 0, 1))Get all the elements in the ordered collection
Same as above
r.zadd("zset1".'n1', 123, 'n2', 234).Copy the code
delete
Zrem (name, values) Deletes the members in the ordered set corresponding to name whose values are valuesCopy the code
# remove n2
r.zrem("zset2"."n2")
print(r.zrange("zset2", 0, 1))Copy the code
Zremrangebyrank (name, min, Max) is deleted based on the indexCopy the code
Delete by index
r.zremrangebyrank("zset2", 0, 1)
print(r.zrange("zset2", 0, 1))Copy the code
check
Zscore (name, value) Gets the score corresponding to value in the ordered set corresponding to nameCopy the code
Find the value of n5
print(r.zscore("zset2"."n5"))
Copy the code
Gets the length of the set
print(r.zcard("zset1"))
Copy the code
Gets all elements of an ordered collection
r.zrange( name, start, end, desc=False, withscores=False, score_cast_func=float) obtain the element parameter of the ordered set corresponding to name according to the index range: Name, redis name start, ordered set index start (non-score) end, ordered set index end (non-score) desc The default value is score_cast_func, a function that converts the scoreCopy the code
Sort from large to small (like zrange, sets sort from large to small)
zrevrange(name, start, end, withscores=False, score_cast_func=float)
# fetch only elements, no score
print(r.zrevrange("zset1", 0, 1))Get all elements and scores in the ordered set in reverse order
print(r.zrevrange("zset1", 0, -1, withscores=True))
Copy the code
Count the number of elements in the range
Zcount (name, min, Max) gets the number of fractions between [min, Max] in the ordered set corresponding to nameCopy the code
for i in range(1, 30):
key = 'n' + str(i)
r.zadd("zset2", key, i)
print(r.zrange("zset2", 0, -1, withscores=True))
print(r.zcount("zset2", 1, 9))
Copy the code
Since the increase
Zincrby (Name, value, amount) increments the score corresponding to the name of the ordered set corresponding to nameCopy the code
# increment n1 by 5 each time
r.zincrby("zset2"."n2", amount=5)
print(r.zrange("zset2", 0, -1, withscores=True))
Copy the code
Gets the index number of the value
Zrank (name, value) retrieves the index of a value in the ordered set corresponding to name (starting from 0)Copy the code
Get the index number of n2
print(r.zrank("zset2"."n2"))
Copy the code
Afterword.
Reply “Redis” in the background of wechat public number to obtain the source code. Redis’ SAO operation is introduced here, after will continue to write MySQL ‘SAO operation. Look forward to it.
This article was first published on the public account “Zone7”. Stay tuned for the latest tweets!