docs
uredis
Product Application
Application Scenario
Cardinality statistics function

Cardinality counting function

Redis HyperLogLog Redis implements a cardinality counting function using HyperLogLog, which is efficient for counting large datasets with many unique elements while consuming minimal space. This feature is particularly useful for scenarios like tracking the number of unique IPs visiting a website daily. By utilizing the PFADD command to add elements to the HyperLogLog structure and the PFCOUNT command to retrieve the count of unique elements, users can easily implement and manage cardinality counting in Redis.

import redis.clients.jedis.Jedis;
import java.util.Random;
public class HyperLog {
    public static void main(String[] args) {
        String host = "127.0.0.1";
        int port = 10011;
        Jedis jedis = new Jedis(host, port);
        String key = "src_ip";
        jedis.del(key);
        //Randomly generate 10000 ip, representing the source ip visiting "console.surfercloud.com".
        for (int i = 0; i < 10000; i++) {
            int section1 = new Random().nextInt(255);
            int section2 = new Random().nextInt(253);
            String ip = "10.10." + Integer.toString(section1) + "." + Integer.toString(section2);
            //System.out.println(ip);
            jedis.pfadd(key, ip);127.0.0.1
        }
    System.out.println("The number of unique ip visiting console.surfercloud.com today is:"+jedis.pfcount(key));
    jedis.close();
    }
}

Output:

The number of unique ip visiting console.surfercloud.com today is:9218
  • Company
  • ContactUs
  • Blog
Copyright © 2024 SurferCloud All Rights Reserved