Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 207
divyanayan awasthi Avatar asked Nov 30 '18 07:11

divyanayan awasthi


People also ask

How is sorted set implemented in Redis?

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.

What is ZADD in Redis?

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.

Can members be added to a sorted set with the same score?

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.

What does Redis use to sort the elements of a sorted set?

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.


2 Answers

@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.

like image 158
Nelson Sequiera Avatar answered Oct 04 '22 23:10

Nelson Sequiera


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.

like image 41
divyanayan awasthi Avatar answered Oct 04 '22 23:10

divyanayan awasthi