I would like to insert data into sorted set in redis using python to do complex queries like on range etc.
import redis
redisClient = redis.StrictRedis(host='localhost', port=6379,db=0)
redisClient.zadd("players",1,"rishu")
but when i run the the above piece of code ,i get the following error as
AttributeError: 'str' object has no attribute 'items'
What am i doing wrong here.used this link for reference https://pythontic.com/database/redis/sorted%20set%20-%20add%20and%20remove%20elements
Sorted sets are implemented as a dual data structure: It is a combination of both a hash and skip list. The hash part maps objects to scores and the skip list maps scores to objects. We already know how hashes are implemented in Redis from our previous post.
Redis ZADD command is used to add all the specified members with the specified scores to the sorted set stored at key. If a specified member is an existing member of the stored set, the score is updated and the element reinserted at the right position to ensure the correct ordering.
While the same element can't be repeated in a sorted set since every element is unique, it is possible to add multiple different elements having the same score.
A Redis sorted set is a collection of unique strings (members) ordered by an associated score. When more than one string has the same score, the strings are ordered lexicographically. Some use cases for sorted sets include: Leaderboards.
@TheDude is almost close.
The newer version of redis from (redis-py 3.0), the method signature has changed. Along with ZADD, MSET and MSETNX signatures were also changed.
The old signature was:
data = "hello world"
score = 1
redis.zadd("redis_key_name", data, score) # not used in redis-py > 3.0
The new signature is:
data = "hello world"
score = 1
redis.zadd("redis_key_name", {data: score})
To add multiple at once:
data1 = "foo"
score1 = 10
data2 = "bar"
score2 = 20
redis.zadd("redis_key_name", {data1: score1, data2: score2})
Instead of args/kwargs, a dict is expected, with key as data and value is the ZADD score. There are no changes in retrieving the data back.
rediscleint.execute_command('ZADD', "rishu", 1, "123").this one works ...trying to figure how to add elements to sorted sets without using execute_command approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With