70

For lists I can do the operation:

LLEN KeyName

and it will return the size of a list in Redis. What is the equivalent command for sets? I can't seem to find this in any documentation.

Elijah
  • 13,368
  • 10
  • 57
  • 89

3 Answers3

113

You are looking for the SCARD command:

SCARD key

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

Return value
Integer reply: the cardinality (number of elements) of the set, or 0 if key does not exist.

Time complexity: O(1)

You can view all of the set commands on the documentation webpage.

Amin Shojaei
  • 5,451
  • 2
  • 38
  • 46
  • 4
    One of the most stupid thing about redis is that there are different commands to do the same thing depending on data type. Finding Length is one of these. – Scalable Nov 29 '19 at 14:47
  • @Scalable those Redis engineers suck :) they could not think of it :) – Yilmaz Aug 07 '22 at 17:34
4

If it's a sorted set, you can use

ZCOUNT myset -inf +inf

or

ZCARD myset
Brimstedt
  • 3,020
  • 22
  • 32
Donald
  • 321
  • 1
  • 2
  • 10
  • 4
    Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality, and are more likely to attract upvotes. – today Apr 28 '20 at 23:19
2
  • zCard is short for cardinality (cardinality is the number of elements in a set). It gives you total number of members inside of a "sorted set".

  • Sometimes you might wanna extract how many members are inside of a range in a sorted set. For that you can use zCount.

    ZCOUNT cars 0 50  // inclusive
    

this will include 0 and 55. 0 <= .... <=50. But if you do not want to include them

ZCOUNT cars (0 (50
  • if it is regular set

    SCARD cars 
    
Yilmaz
  • 35,338
  • 10
  • 157
  • 202