Python's common operations on redis (list, string, and hash structure operations) and pythonredis

Source: Internet
Author: User
Tags install redis

Python's common operations on redis (list, string, and hash structure operations) and pythonredis

All the discussions here are based on the python redis-py library.

Installation and use:

pip install redis

Then obtain a redis client:

redis_conn = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)

There are five basic types of redis. Including string type, hash type, list type, set type, and ordered set type. For each type, the reids client provides many different operation methods. Below I will record some of the most commonly used python-based operations .. The main purpose is to facilitate the query, because you don't have to forget it for a long time. Every query is too slow and the cost is too high. This kind of thing should have no brains and efficiency at first.

Note: The client redis_conn I obtained above is assigned to x, and the following x represents the python redis client.

 

String type:

 
 

In [15]: x. set ("foo", 1)
True

 

In [16]: x. get ("foo ")
'1'

 

In [17]: x. set ("foo", "today I want to apologize to myself ")
True

 

In [18]: x. get ("foo ")
'Today I want to apologize to myself'

 

# Because the key word del in python conflicts, redis-py on the python client here uses delete instead of del as the key word for deletion.

In [19]: x. delete ("foo ")
1

 

In [20]: x
Redis <ConnectionPool <Connection

 

In [21]: x. get ("foo ")

String addition, deletion, modification, and query methods are very simple. Note that when you call the delete method, the number of successful objects is returned. There is also an incremental key value operation, but I think it is basically difficult to use redis if it is not used as a database, but here we also introduce it:

In [27]: x.incr("num")1In [28]: x.incr("num")2In [29]: x.incr("num")3In [30]: x.incr("num")4

When the key num is not set, you can directly use the incr function to set it to 1, and then the call will increase sequentially, in addition, this operation is an atomic operation, so there will be no race condition. It can be used to record the number of visits or something, and the speed is faster than directly inserting data into the database. Of course, the string also involves a set of binary operation methods, including the get \ set method. Because it is not commonly used, it is not recorded here. If you are interested, you can check it yourself.

 

Hash type:

First, the simplest way is to set the dictionary of a car key to {"price": 400}, and then use the hget method to obtain the value of the corresponding field under the key.

In [44]: x.hset("car", "price", 400)1LIn [45]: x.hget("car", "price")'400'

 

The following shows whether the judgment key and key value exist:

# Checking whether the key exists In [47]: x. exists ("car") TrueIn [48]: x. exists ("m") False # judge whether the key value exists In [50]: x. hexists ("car", "price") TrueIn [51]: x. hexists ("car", "name") False

 

Assign a value when the field does not exist:

In [52]: x.hsetnx("car", "name", "hahaha")1LIn [53]: x.hsetnx("car", "name", "hahaha")0LIn [54]: x.hsetnx("car", "name", "xixiix")0LIn [56]: x.hget("car", "name")'hahaha'

We can see that when the property name with the key as car does not exist, the first operation is successful, but the second operation fails. This is because hsetnx is assigned only when the field does not exist. The number of affected items returned after successful execution. When the data exists, you cannot modify the value using hsetnx.

 

To view all attributes and values under a key, you can use hkeys and hval or use hlen to view the number of key attributes:

In [58]: x.hkeys("car")['price', 'name']In [59]: x.hvals("car")['400', 'hahaha']

In [60]: x. hlen ("car ")
2

 

List type:

The list of redis uses a double-ended linked list, so the list type of redis supports inserting data from both sides. Because it is a double-ended linked list, no matter which side the insertion or query efficiency is not related to the List itself.

The following shows how to insert and pop up data and index data:

In [61]: x.lpush("challenge", 1)1LIn [62]: x.rpush("challenge", 2)2LIn [63]: x.lrange("challenge", 0, 20)['1', '2']In [64]: x.lpop("challenge")'1'In [65]: x.rpop("challenge")'2'In [66]: x.lrange("challenge", 0, 20)[]

Here we show the insertion pop-up methods that need to be used for index array data. In fact, there are also llen and llen methods that can directly obtain the number of existence of the array, in addition, the algorithm time complexity is O (1), because it is a constant reading, and not the same as that of traditional relational databases.

 

Next we will talk about the lrange command separately, that is, the command for reading data from the list. In addition to the usage shown above, lrange also supports negative indexes, if you are a python player, will you feel very friendly? However, the negative index cannot reverse the list. The following is a demonstration:

In [77]: x.lrange("challenge", 0, 20)['8', '7', '6', '5', '4', '3', '2', '1']In [81]: x.lrange("challenge", -20, -1)['8', '7', '6', '5', '4', '3', '2', '1']

 

In addition, the delete method is a bit similar to the remove Method in python. It is used to delete the corresponding value, rather than deleting the index. Note that this search will be inefficient when the list is large:

In [101]: x.lrange("challenge", 0, -1)['8', '7', '6', '5', '4', '3', '2']In [102]: x.lrem("challenge", 4)1LIn [103]: x.lrange("challenge", 0, -1)['8', '7', '6', '5', '3', '2']

 

There are also a number of list-based index-based commands:

In [103]: x.lrange("challenge", 0, -1)['8', '7', '6', '5', '3', '2']In [104]: x.lindex("challenge", 1)'7'In [105]: x.lindex("challenge", 2)'6'

In [109]: x. lset ("challenge", 1, 22)
True

 

In [110]: x. lrange ("challenge", 0,-1)
['8', '22', '6', '5', '3', '2']

 

In addition to the index operation value assignment and the value on the corresponding index, there are several more special operation functions, which are not very common here:

# Only keep the value In the list range In [112]: x. ltrim ("challenge", 0, 4) TrueIn [113]: x. lrange ("challenge", 0,-1) ['8', '22', '6', '5 ', '3'] # insert an element In the list In [131]: x. lrange ("challenge", 0,-1) ['8', '22', '6', '5', '3'] In [132]: x. linsert ("challenge", "before", 22, 3) 6In [133]: x. lrange ("challenge", 0,-1) ['8', '3', '22', '6', '5', '3']

Note that the third parameter of the linsert method is to find the first qualified value and insert an element into its second parameter (either before or after.

 

 

Reference:

Http://www.cnblogs.com/melonjiang/p/5342505.htmlPython operations on redis

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.