2

I've been using the redis-cli to get the hang of how redis works. I understand that using this tool I can do this:

127.0.0.1:6379> set post:1:title "Redis is cool!"
OK
127.0.0.1:6379> set post:1:author "haye321"
OK
127.0.0.1:6379> get post:1:title
"Redis is cool!"

What I cannot seem to figure out is how I would accomplish this with redis-py. It doesn't seem the set commanded provided allows for an object-type or id. Thanks for your help.

2 Answers 2

2

You are setting individual fields of a Redis hash one by one (a hash is the common data structure in Redis to store objects).

A better way to do this is to use Redis HMSET command, that allows to set multiple fields of a given hash in one operation. Using Redis-py it will look like this:

import redis
redisdb = redis.Redis(host="localhost",db=1)
redisdb.hmset('post:1', {'title':'Redis is cool!', 'author':'haye321'})

update:

Of course you could have set Hash field members one by one using the HSET command, but it's less efficient as it requires one request per field:

import redis
redisdb = redis.Redis(host="localhost",db=1)
redisdb.hset('post:1', 'title', 'Redis is cool!')
redisdb.hset('post:1', 'author', 'haye321'})
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the response. How would I increment to the next available post id if I was using hashes?
Use Redis INCR command to get unique IDs the concatenate them with your 'post:' key.
How do I pass the "post": key to the INCR command? Sorry for being difficult but an example would be very helpful thanks.
You really should read Redis introduction documentation and follow the interactive tutorial.
I have read the Redis documentation, extensively. I don't feel that it does a good job of explaining the distinctions at play here. I found this link to be very helpful for someone in my position. joshtronic.com/2013/07/29/mysql-and-redis-command-equivalents/…
|
1

Another way: you can use RedisWorks library.

pip install redisworks

>>> from redisworks import Root
>>> root = Root()
>>> root.item1 = {'title':'Redis is cool!', 'author':'haye321'}
>>> print(root.item1)  # reads it from Redis
{'title':'Redis is cool!', 'author':'haye321'}

And if you really need to use post.1 as key name in Redis:

>>> class Post(Root):
...     pass
... 
>>> post=Post()
>>> post.i1 = {'title':'Redis is cool!', 'author':'haye321'}
>>> print(post.i1)
{'author': 'haye321', 'title': 'Redis is cool!'}
>>> 

If you check Redis

$ redis-cli
127.0.0.1:6379> type post.1
hash

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.