BITCOUNT

    Count the number of set bits (population counting) in a string.

    By default all the bytes contained in the string are examined. It is possible to specify the counting operation only in an interval passing the additional arguments start and end.

    Like for the command start and end can contain negative values in order to index bytes starting from the end of the string, where -1 is the last byte, -2 is the penultimate, and so forth.

    Non-existent keys are treated as empty strings, so the command will return zero.

    Integer reply

    The number of bits set to 1.

    1. dragonfly> SET mykey "foobar"
    2. "OK"
    3. (integer) 26
    4. dragonfly> BITCOUNT mykey 0 0
    5. dragonfly> BITCOUNT mykey 1 1
    6. (integer) 6
    7. dragonfly> BITCOUNT mykey 1 1 BYTE
    8. (integer) 6
    9. (integer) 17

    Bitmaps are a very space-efficient representation of certain kinds of information. One example is a Web application that needs the history of user visits, so that for instance it is possible to determine what users are good targets of beta features.

    Using the command this is trivial to accomplish, identifying every day with a small progressive integer. For instance day 0 is the first day the application was put online, day 1 the next day, and so forth.

    Later it will be trivial to know the number of single days the user visited the web site simply calling the BITCOUNT command against the bitmap.

    A similar pattern where user IDs are used instead of days is described in the article called ““.

    In the above example of counting days, even after 10 years the application is online we still have just 365*10 bits of data per user, that is just 456 bytes per user. With this amount of data BITCOUNT is still as fast as any other O(1) Redis command like GET or INCR.

    When the bitmap is big, there are two alternatives: