程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python uses redis (mainly for Zset data structure)

編輯:Python

About Redis Installation configuration , Refer to the previous article :
https://blog.csdn.net/weixin_46307478/article/details/122204294

Two 、 Use python operation Redis

python We use redis-py Library to operate Redis database , The following will focus on .

(base) [[email protected] ~]$ conda activate odc
(odc) [[email protected] ~]$ pip install redis

1. Connect

The first way : Ordinary

import redis # Import redis modular , adopt python operation redis You can also directly redis The server operation cache database of the host 
r = redis.Redis(host='localhost', port=6379, decode_responses=True) # host yes redis host , need redis Both the server and the client start redis The default port is 6379
r.set('name', 'junxi') # key yes "name" value yes "junxi" Store key value pairs redis cache 
print(r['name'])
print(r.get('name')) # Remove key name Corresponding value 
print(type(r.get('name')))
# Specified password , database 
redis_conn = redis.Redis(host='127.0.0.1', port= 6379, password= 'your pw', db= 0)

The second way : Connection pool

redis-py Use connection pool To manage one redis server All connections , Avoid every build 、 Free the overhead of the connection . Default , Every Redis Each instance maintains its own connection pool .
You can create a connection pool directly , And then as an argument Redis, This allows you to implement multiple Redis Instances share a connection pool .

import redis # Import redis modular , adopt python operation redis You can also directly redis The server operation cache database of the host 
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True) # host yes redis host , need redis Both the server and the client are up redis The default port is 6379
r = redis.Redis(connection_pool=pool)
r.set('gender', 'male') # key yes "gender" value yes "male" Store key value pairs redis cache 
print(r.get('gender')) # gender Remove key male Corresponding value 
# redis_pool = redis.ConnectionPool(host='127.0.0.1', port= 6379, password= 'your pw', db= 0)

The Conduit

redis-py The default is created every time a request is executed ( Connection pool request connection ) And disconnect ( Return connection pool ) One connection operation , If you want to specify multiple commands in a single request , You can use pipline Implement a request that specifies more than one command at a time , And next time by default pipline Atomic operations .

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import redis
pool = redis.ConnectionPool(host='192.168.22.132', port=6379)
r = redis.Redis(connection_pool=pool)
# pipe = r.pipeline(transaction=False)
pipe = r.pipeline(transaction=True)
pipe.set('name', 'root')
pipe.set('role', 'root')
pipe.execute()

2. Common data structure

Python Use in Redis Detailed explanation - You know (zhihu.com)

Redis data type | Novice tutorial (runoob.com)

  • String- character string
  • List- list
  • Hash- Hash
  • Set- aggregate
  • ZSet- Ordered set
  • Bitmap- Bitmap

Application scenarios of various data types :

type brief introduction characteristic scene String( character string ) Binary security Can contain any data , such as jpg Picture or serialized object , Maximum storage of one key 512M—Hash( Dictionaries ) Key value pair set , In programming language Map type Suitable for storing objects , And it can be like in a database update Only one property value can be modified for one property (Memcached The entire string needs to be taken out and deserialized into an object, and then serialized and saved ) Storage 、 Read 、 Modify user properties List( list ) Linked list ( Double linked list ) Additions and deletions quickly , Provides for manipulating a certain element API1, Latest news ranking and other functions ( For example, the timeline of the circle of friends ) 2, Message queue Set( aggregate ) Hash table implementation , Elements do not repeat 1、 add to 、 Delete , The complexity of searching is O(1) 2、 Provides intersection for sets 、 Combine 、 Subtraction and so on 1、 Common friends 2、 Using uniqueness , Count all the independent websites visited ip 3、 When friends recommend , according to tag Find the intersection , More than a certain threshold can be recommended Sorted Set( Ordered set ) take Set Add a weight parameter to the element in score, Element press score Arrange in order When data is inserted into a collection , A natural sequence has been made 1、 Ranking List 2、 Weighted message queue

Because the author mainly uses zset data structure , The following is a summary of Zset Use of structure :

3.zset Set operations

redis Ordered set :

Redis zset and set The same is true. string Collection of type elements , And duplicate members are not allowed .

The difference is that each element is associated with a double Score of type .redis It's the scores that sort the members of a collection from small to large .

zset Members of are unique , But fractions (score) But it can be repeated .

python redis The method provided is basically consistent with the command line , Specific functions and meanings can be used by referring to the given command line , The corresponding function name is basically the same as the command name

The conventional ZSET Official operation order :

1 ZADD key score1 member1 [score2 member2] Add one or more members... To an ordered collection , Or update scores of existing members
2 ZCARD key Get the number of members of the ordered set
3 ZCOUNT key min max Calculates the number of members of a specified interval fraction in an ordered set
4 ZINCRBY key increment member Add the increment... To the score of the specified member in the ordered set increment
5 ZINTERSTORE destination numkeys key [key ...] Calculates the intersection of a given ordered set or sets and stores the result set in a new ordered set key in
6 ZLEXCOUNT key min max Computes the number of members in the specified dictionary interval in an ordered collection
7 ZRANGE key start stop [WITHSCORES] Returns an ordered set through an index interval to synthesize members in a specified interval
8 ZRANGEBYLEX key min max [LIMIT offset count] Returns the members of an ordered set through a dictionary interval
9 ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT] Returns the members of an ordered set in a specified interval through scores
10 ZRANK key member Returns the index of a specified member in an ordered collection
11 ZREM key member [member ...] Remove one or more members of an ordered collection
12 ZREMRANGEBYLEX key min max Remove all members of a given dictionary interval from an ordered set
13 ZREMRANGEBYRANK key start stop Remove all members of a given rank range from an ordered set
14 ZREMRANGEBYSCORE key min max Remove all members of a given fraction interval from an ordered set
15 ZREVRANGE key start stop [WITHSCORES] Returns the members of a specified interval in an ordered set , Through the index , Score from high to the end
16 ZREVRANGEBYSCORE key max min [WITHSCORES] Returns the members of the specified score range in an ordered set , Rank scores from high to low
17 ZREVRANK key member Returns the rank of a specified member in an ordered set , Members of an ordered set are decremented by fractions ( From big to small ) Sort
18 ZSCORE key member Back to the ordered set , The score of a member
19 ZUNIONSTORE destination numkeys key [key ...] Computes the union of a given ordered set or sets , And store it in the new key in
20 ZSCAN key cursor [MATCH pattern] [COUNT count] Iterate over elements in an ordered set ( Include element members and element scores )
21 BZPOPMAX kes timeout BZPOPMAX It's an ordered set ZPOPMAX Blocking variants of primitives . When no member pops up from any given ordered set ,
It will block the connection timeout Timeout for blocking , To prevent constant blockage for example : BZPOPMAX zset1 zset2 0
22 BZPOPMIN Block throw minimum
23 ZPOPMAX Throw the maximum value
24 ZPOPMIN Throw the minimum value
25 ZREVRANGEBYLEX When all the elements in the sorting set insert the same score , To enforce dictionary sorting , This command will return all the elements in the sort set , Its key The value is max Between and min

Python Of Zset

python-redis The corresponding is provided 25 Command support , The corresponding name is basically the same as the command line

The following is the usage of some functions :

def zadd(self, name, mapping, nx=False, xx=False, ch=False, incr=False)
# stay name Adds elements to the corresponding ordered collection 
rediscli.zadd("me1", mapping={
"x1": 1, "x2": 3})
1
def zcard(self, name)
# Get the number of members of the ordered set 
rediscli.zcard("me1")
1
def zcount(self, name, min, max)
# obtain name The fraction in the corresponding ordered set stay [min,max] The number between 
rediscli.zcount("me1", 0, 5)
1
def zincrby(self, name, amount, value)
# Ordered set name Add the increment to the score of the specified member in increment
def zinterstore(self, dest, keys, aggregate=None)
# Calculates the intersection of a given ordered set or sets and stores the result set in a new ordered set key in 
def zlexcount(self, name, min, max)
# Computes the number of members in the specified dictionary interval in an ordered collection 
rediscli.zlexcount('me1', "[a", "[v")
1
def zpopmax(self, name, count=None)
# Throw the maximum value 
def zpopmin(self, name, count=None)
# Throw the minimum value 
def bzpopmax(self, keys, timeout=0)
# Throw the maximum value 
def bzpopmin(self, keys, timeout=0)
def zrange(self, name, start, end, desc=False, withscores=False, score_cast_func=float)
# By index range name The elements of the corresponding ordered set 
""" Parameters : name,redis Of name start, An ordered collection index starting position ( The score ) end, End of index of ordered collection ( The score ) desc, Sort rule , By default, sort by score from small to large withscores, Whether to get the score of the element , The default is to get only the values of the elements score_cast_func, A function that converts data to scores """
rediscli.zrange('me1', 0, 5)
Output : ['x1', 'x2']
rediscli.zrange('me1', 0, 5, withscores=True)
Output :
[('x1', 1.0), ('x2', 3.0)]
1
2
3
4
5
6
def zrangebylex(self, name, min, max, start=None, num=None)
# Returns the members of an ordered set through a dictionary interval 
""" Parameters : name,redis Of name min, Left interval ( value ). + Positive infinity ; - Negative infinity ; ( Open interval ; [ Is a closed interval min, The right range ( value ) start, The results are segmented , Index position num, The results are segmented , After index num Elements """
zrangebylex('me1', '-', '(x')
1
def zrevrangebylex(self, name, max, min, start=None, num=None)
def zrangebyscore(self, name, min, max, start=None, num=None, withscores=False, score_cast_func=float)
rediscli.zrangebyscore('me1', 2, 5)
1
def zrank(self, name, value)
# Get some value at name The rank in the corresponding ordered set ( from 0 Start )
def zrem(self, name, *values)
# Delete name The median of the corresponding ordered set is values Members of 
def zremrangebylex(self, name, min, max)
def zremrangebyrank(self, name, min, max)
# Delete according to rank range 
def zremrangebyscore(self, name, min, max)
# Delete by score range 
def zrevrange(self, name, start, end, withscores=False, score_cast_func=float)
def zrevrangebyscore(self, name, max, min, start=None, num=None, withscores=False, score_cast_func=float)
def zrevrank(self, name, value)
def zscore(self, name, value)
zscan(name, cursor=0, match=None, count=None, score_cast_func=float)
rediscli.scan()
Output : (0L, ['me1', 'm1', 'name', 'm2'])
1
2
3
zscan_iter(name, match=None, count=None,score_cast_func=float)
# List all the keys , The form of the generator , New relative to string score_cast_func, Used to operate on fractions 
def zinterstore(dest, keys, aggregate=None)
# Gets the intersection of two ordered sets , If you have the same value and different scores , According to aggregate To operate 
aggregate The value of is : SUM MIN MAX
def zunionstore(dest, keys, aggregate=None)
# Gets the union of two ordered sets , If you have the same value and different scores , According to aggregate To operate 
aggregate The value of is : SUM MIN MAX

The sample program :

# coding:utf-8
import redis
rediscli = redis.Redis(host='127.0.0.1', port=8888, db=13)
print rediscli.zadd("me1", mapping={
"x1": 1, "x2": 3})
print rediscli.zadd("me2", mapping={
"x1": 1, "x3": 5, "x4": 3})
print rediscli.zcard("me1")
print rediscli.zcount("me1", 0, 5)
print rediscli.zrange('me1', 0, 5, withscores=False)
print rediscli.zrange('me1', 0, 5, withscores=True)
print rediscli.zincrby("me1", amount=1, value="x1")
print rediscli.zinterstore(dest="me3", keys=['me1', 'me2'])
print rediscli.zrange('me3', 0, 5, withscores=True)
print rediscli.zlexcount('me1', "[a", "[v")
print rediscli.zrangebylex('me1', '-', '(x')
print rediscli.zrangebyscore('me1', 2, 5)
print rediscli.zrank('me1', 'x1')
print rediscli.zscore('me1', 'x1')
print rediscli.zadd('me1', mapping={
"x4": 4})
print rediscli.zrem('me1', 'x4')
print rediscli.zremrangebyrank('me1', 7, 10)
print rediscli.zremrangebyscore('me1', 11, 15)
print rediscli.zrevrangebyscore('me1', 8, 3)
print rediscli.zrevrange('me1', 0, -1, withscores=True)
print rediscli.zrange('me1', 0, -1, withscores=True)
print rediscli.scan()

Output results :

2
3
2
2
['x1', 'x2']
[('x1', 1.0), ('x2', 3.0)]
2.0
1
[('x1', 3.0)]
0
[]
['x1', 'x2']
0
2.0
1
1
0
0
['x2']
[('x2', 3.0), ('x1', 2.0)]
[('x1', 2.0), ('x2', 3.0)]
(0L, ['me3', 'me2', 'me1'])

Reference resources :

python redis Detailed explanation ( 7、 ... and )ZSET Ordered set _comprel The blog of -CSDN Blog _python redis zset


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved