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

Python general operation redis (not to be missed)

編輯:Python

Share the theme today :Python Normal operation redis The content of

Part1: Five types of data

Redis Support 5 Type of data :

  • string( character string )
  • hash( Hash )
  • list( list )
  • set( aggregate )
  • zset(sorted set: Ordered set )

1.String String data type

String Is the most commonly used data type , ordinary key/value Storage can all be classified as such , That is to say, we can fully realize the current Memcached The function of , And more efficient .

You can also enjoy Redis Time persistence of , Operation log and Replication And so on .

Common commands :
  • get
  • set
  • incr
  • decr
  • mget

2.Hash Hash data type

Redis hash It's a key value (key => value) The collection .

Redis hash It's a string Type of field and value Mapping table ,hash Ideal for storing objects .

Common commands :
  • hget
  • hset
  • hgetall
Application scenarios :

Take an example to describe hash Application scenarios of , For example, we need to store a user information object data , You can use Redis hash.

3.List data type

Redis list List is a simple list of strings , Sort by insertion order . You can add an element to the head of the list ( On the left ) Or tail ( On the right ).

Common commands :
  • lpush( Add the left element )
  • rpush( Add the right element )
  • lpop( Remove the first element on the left )
  • rpop( Remove the first element on the right )
  • lrange( Get list snippets ,LRANGE key start stop)
Application scenarios :

Redis list There are many application scenarios , It's also Redis One of the most important data structures .

such as twitter The list of concerns , Fans list can be used Redis Of list Structure to achieve .

4.Set data type

Redis set yes string Unordered collection of type . Set is through hashtable Realized , The concept is basically similar to the set in mathematics , Can intersect , Combine , Subtraction and so on ,set There is no order for the elements in .

Common commands :
  • sadd
  • spop
  • smembers
  • sunion
Application scenarios :

Redis set The functions and list Similar to a list function , What's special is set It can automatically arrange the weight .

When you need to store a list of data , You don't want duplicate data ,set Is a good choice , also set Provides a way to determine whether a member is in a set Important interfaces within a collection , This is also list What cannot be provided .

5.zset Ordered collection data types

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

zadd command : Add elements to the collection , Update corresponding if element exists in collection score.

Common commands :
  • zadd
  • zrange
  • zrem
  • zcard
Use scenarios :

Redis sorted set Use scenarios and set similar , The difference is that set It's not automatic , and sorted set You can provide an additional priority through the user (score) To sort the members , And it's inserted in order , That is, automatic sorting .

Part2: Code content
import redis
# Use connection pool to connect redis
redis_pool=redis.ConnectionPool(host="127.0.0.1",port=6379,db=15,decode_responses=True)
redis_conn=redis.Redis(connection_pool=redis_pool)
#2.1 String character string
# Commands related to string data types are used for management redis A string value
# Set the specified key Value
redis_conn.set("name","tony")
redis_conn.set("age",33)
redis_conn.set('strtest','{"addr":" Beijing good","phone":13300000000}')
#Setnx(SET if Not eXists) The order is at the designated key When there is no , by key Set the specified value
redis_conn.setnx("job","computer")
# Get specified key Value
print(redis_conn.get('name'))
print(redis_conn.get('age'))
print(redis_conn.get('strtest'))
#Incr The order will key The value of the number stored in is increased by one
# If key non-existent , that key The value of is initialized to 0 , And then execute INCR operation
# If the value contains the wrong type , A value of type or string cannot be represented as a number , So return an error
print(redis_conn.incr("age"))
# Decr The order will key Subtract one from the number stored in
# If key non-existent , that key The value of is initialized to 0 , And then execute DECR operation
# If the value contains the wrong type , A value of type or string cannot be represented as a number , So return an error
print(redis_conn.decr("age"))
print(redis_conn.get("job"))
#Strlen Command to get the specified key The length of the stored string value . When key When a string value is not stored , Return an error
print(redis_conn.strlen("strtest"))
print("*"*10)
#2.2 Hash Hash
#hash It's a string Type of field( Field ) and value( value ) Mapping table ,hash Ideal for storing objects .
#Hmget The command is used to return , The value of one or more given fields
redis_conn.hset('myhash','f1','v1')
redis_conn.hset('myhash','f2','v2')
#Hget The command returns the value of the specified field in the hash table , If a given field or key When there is no , return None
print(redis_conn.hget("myhash","testhash"))
print(redis_conn.hmget('myhash','f1','f2'))
#Hgetall The command is used to return , All fields and values
redis_conn.hset("hashstrtest","student2",'idcard:123456,sex:man,age:33')
print(redis_conn.hgetall("hashstrtest"))
# Hmset The command is used to transfer multiple field-value ( Field - value ) Set to hash table
redis_conn.hmset('hashjsontest', {'student3': '{"perform": "game","num":123456789}'})
redis_conn.hmset('jsontest',{"id":1,"name":" Zhang Sanfeng ","birth":"2000-07-07","age":17,"clazz":" A year 1 class ","createTm":1504856483000})
print(redis_conn.hgetall("hashjsontest"))
print(redis_conn.hgetall("jsontest"))
# Get all the fields in the hash table
print(redis_conn.hkeys("jsontest"))
#Hvals The command returns all the values of the hash table
print(redis_conn.hvals("jsontest"))
# Get the number of fields in the hash table
print(redis_conn.hlen("jsontest"))
print("*"*20)
#2.3 List list
# Is a simple list of strings , Sort by insertion order . You can add an element to the head of the list ( On the left ) Or tail ( On the right
# Insert one or more values into the list header
redis_conn.lpush("teachkey","redis")
redis_conn.lpush("teachkey","mysql")
redis_conn.lpush("teachkey","mongodb")
redis_conn.lpush("teachkey","mq")
redis_conn.lpush("teachkey","job")
# Get the elements in the specified range of the list
print(redis_conn.lrange('teachkey',1,10))
#Lindex The command is used to get the elements in the list by index . You can also use negative subscripts , With -1 Represents the last element of the list , -2 Represents the penultimate element of a list , And so on
# The subscript in the list is the element with the specified index value . If the specified index value is not within the range of the list , return None
print(redis_conn.lindex("teachkey",-1))
# Get list length
print(redis_conn.llen("teachkey"))
# Move out and get the first element of the list
print(redis_conn.lpop("teachkey"))
# Insert one or more values into the list header
print(redis_conn.lpush("teachkey","goodjob"))
print(redis_conn.lrange('teachkey',1,10))
print("*"*30)
#2.4 Set aggregate
#Set yes String Unordered collection of type . Collection members are unique , This means that duplicate data cannot appear in the collection .
# Add one or more members to the collection
redis_conn.sadd('lovekey','booking')
redis_conn.sadd('lovekey','booking')
redis_conn.sadd('lovekey','eating')
redis_conn.sadd('lovekey','runing')
redis_conn.sadd('lovekey','jumping','fishing')
redis_conn.sadd("dokey","working","thinking","runing","doing","fishing")
#Scard The command returns the number of elements in the collection , When set key When there is no , return 0
print(redis_conn.scard("lovekey"))
#Sdiff The command returns the difference between the first set and other sets , It can also be said that the unique elements in the first set . Nonexistent collection key Treat as an empty set
print(redis_conn.sdiff("lovekey","dokey"))
#Sinter The command returns the intersection of all given sets . Nonexistent collection key Be regarded as an empty set . When there is an empty set in a given set , It turned out to be an empty set
print(redis_conn.sinter("lovekey","dokey"))
#Sismember Command to determine whether a member element is a member of a collection
print(redis_conn.sismember("lovekey","eating"))
#Smembers The command returns all members of the collection . Nonexistent collection key Is treated as an empty set
print(redis_conn.smembers("dokey"))
#Spop The command is used to remove the specified key One or more random elements of , After removal, the removed element will be returned
print(redis_conn.spop("dokey",2))
#Srem The command is used to remove one or more member elements from the collection , Nonexistent member elements are ignored , The number of elements successfully removed , Don't include elements that are ignored
print(redis_conn.srem("dokey","ok","isok","doing"))
#Sunion Command returns the union of a given set . Nonexistent collection key Be regarded as an empty set
print(redis_conn.sunion("dokey","lovekey"))
#Sunionstore Store the given set of commands in the specified set destination in . If destination Already exist , Then cover it , The number of elements in the result set
print(redis_conn.sunionstore("destkey","dokey","lovekey"))
print("*"*40)
#2.5 sorted set Ordered set
# An ordered set is the same as a set 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
# Members of an ordered set are unique , But fractions (score) But it can be repeated
dict1=dict(lenovo=1)
redis_conn.zadd('computerkey',dict1)
dict2=dict(dell=2)
dict3=dict(asus=2)
redis_conn.zadd('computerkey',dict2)
redis_conn.zadd('computerkey',dict3)
dict4=dict(asustest=4,goodjob=3)
redis_conn.zadd('computerkey',dict4)
# Return the members in the specified interval of the ordered set through the index interval
print(redis_conn.zrange('computerkey',0,10))
#Zcard The command is used to count the number of elements in the collection
print(redis_conn.zcard("computerkey"))
#Zscore Command back to ordered set , The score of a member . If the member element is not an ordered set key Members of , or key non-existent , return nil
print(redis_conn.zscore("computerkey","dell"))
#Zrank Returns the ranking of specified members in an ordered set . The members of the ordered set are incremented by the fractional value ( From small to large ) Sequential arrangement
print(redis_conn.zrank("computerkey","goodjob"))
# Redis Zrem Command to remove one or more members of an ordered set , Members that do not exist will be ignored . When key When there is but not an ordered set type , Return an error , When key In existence , Returns the number of members successfully removed , Excluding ignored members
print(redis_conn.zrem("computerkey","goodjob"))
Part3: Console output content

tony

33

{"addr":" Beijing good","phone":13300000000}

34

33

computer

41


None

['v1', 'v2']

{'student2': 'idcard:123456,sex:man,age:33'}

{'student3': '{"perform": "game","num":123456789}'}

{'id': '1', 'name': ' Zhang Sanfeng ', 'birth': '2000-07-07', 'age': '17', 'clazz': ' A year 1 class ', 'createTm': '1504856483000'}

['id', 'name', 'birth', 'age', 'clazz', 'createTm']

['1', ' Zhang Sanfeng ', '2000-07-07', '17', ' A year 1 class ', '1504856483000']

6


['mq', 'mongodb', 'mysql', 'redis']

redis

5

job

5

['mq', 'mongodb', 'mysql', 'redis']


5

{'eating', 'booking', 'jumping'}

{'fishing', 'runing'}

True

{'fishing', 'runing', 'doing', 'thinking', 'working'}

['thinking', 'working']

1

{'jumping', 'fishing', 'runing', 'booking', 'eating'}

5


['lenovo', 'asus', 'dell', 'goodjob', 'asustest']

5

2.0

3

1

end


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