Amir Afianian
Amir Afianian

Reputation: 2785

How to Get The Counts of Redis Values for A Set in Python

I want to get the count of values given the key schema. I have a set in my Redis with their keys being: 'sample:key:schema'

I want to get total number of values associated with this key.

Currently, I do the following and it works

import redis

redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
key_schema = 'sample:key:schema'
count_of_values = len(redis_client.smembers(key_schema))

Is there a better way to get the counts directly without having to fetch all the records and count them?

Upvotes: 1

Views: 1986

Answers (1)

Ersoy
Ersoy

Reputation: 9586

You don't have to get with smembers and len later. You may use scard for this, this is the link for python documentation.

This is from the official redis documentation

Returns the set cardinality (number of elements) of the set stored at key.

Upvotes: 2

Related Questions