简体   繁体   中英

not able to insert data using ZADD(sorted set ) in redis using python

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

@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"). 这个有效......试图弄清楚如何在不使用 execute_command 方法的情况下将元素添加到排序集中。

@divyanayan awasthi answered:

rediscleint.execute_command('ZADD', "rishu", 1, "123")

we can execute raw queries.

Further explanations :

In redis-cli

>>> zadd rishu nx  1 "123"
# sorted set key = rishu 
# nx = new item 
# score = 1
# member = "123"

Now our command in python will be

rediscleint.execute_command('ZADD', "rishu",'nx' 1, "123")

In above code we added new argument into zadd command is nx (add new item). If we want to update sorted set member then we pass 'xx' instead of nx.

in execute_command we can run same redis command separated by commas.

See also:

Redis sorted set commands

Think you are using a newer version of the redis library. From the documentation here , it looks like the method signature changed. Think this would work:

redisClient.zadd("players", rishu=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM