简体   繁体   English

无法使用python在redis中使用ZADD(排序集)插入数据

[英]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.我想使用 python 将数据插入到 redis 中的排序集中,以执行复杂的查询,例如范围等。

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我在这里做错了什么。使用此链接作为参考https://pythontic.com/database/redis/sorted%20set%20-%20add%20and%20remove%20elements

@TheDude is almost close. @TheDude 几乎接近了。

The newer version of redis from (redis-py 3.0), the method signature has changed.来自(redis-py 3.0)的较新版本的redis,方法签名已更改。 Along with ZADD, MSET and MSETNX signatures were also changed.除了 ZADD,MSET 和 MSETNX 签名也发生了变化。

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.而不是 args/kwargs,需要一个 dict,键作为数据,值是 ZADD 分数。 There are no changes in retrieving the data back.检索数据没有任何变化。

rediscleint.execute_command('ZADD', "rishu", 1, "123"). 这个有效......试图弄清楚如何在不使用 execute_command 方法的情况下将元素添加到排序集中。

@divyanayan awasthi answered: @divyanayan awasthi 回答:

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

we can execute raw queries.我们可以执行原始查询。

Further explanations :进一步解释:

In redis-cli在 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现在我们在 python 中的命令将是

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

In above code we added new argument into zadd command is nx (add new item).在上面的代码中,我们在 zadd 命令中添加了新参数是 nx(添加新项目)。 If we want to update sorted set member then we pass 'xx' instead of nx.如果我们想更新有序集合成员,那么我们传递 'xx' 而不是 nx。

in execute_command we can run same redis command separated by commas.在 execute_command 中,我们可以运行以逗号分隔的相同 redis 命令。

See also:也可以看看:

Redis sorted set commands Redis 排序集命令

Think you are using a newer version of the redis library.认为您正在使用较新版本的 redis 库。 From the documentation here , it looks like the method signature changed.此处的文档来看,方法签名似乎已更改。 Think this would work:认为这会起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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